diff --git a/README.md b/README.md index a12f9e3..82cab4e 100644 --- a/README.md +++ b/README.md @@ -6,25 +6,54 @@ Red-DiscordBot cogs for dogebot. | Cog | What it does | |---|---| -| `doge_alignment` | A server's D&D alignment chart, with slash commands ([TODO](doge_alignment/TODO.md)) | +| `doge_alignment` | A server's D&D alignment chart, drawn with members' avatars ([TODO](doge_alignment/TODO.md)) | | `watch` | Preload a movie or episodes into the home lab's media cache before you watch | ## doge_alignment -Slash commands for a 3x3 D&D alignment chart per server. Enable them with `[p]slash enable ` and -`[p]slash sync`. +A 3x3 D&D alignment chart per server, drawn with members' avatars cut into circles. Every command works as +`[p]alignment …` and, once enabled (`[p]slash enable alignment`, `[p]slash sync`), as `/alignment …`. | Command | | |---|---| -| `/alignment_show` | the chart, grouped by alignment | -| `/alignment_set` | put yourself on the chart | -| `/alignment_set_other [target]` | place someone who isn't on the chart yet; alignment admins can move anyone | -| `/alignment_remove` | take yourself off | -| `/alignment_add_admin`, `/alignment_remove_admin` | server owner, bot owner or alignment admins only | +| `alignment [image\|gallery\|text]` (`/alignment show`) | the chart: one picture, nine pictures in Discord's 3x3 media gallery, or text | +| `alignment set [member]` | put yourself on the chart, or someone who isn't on it yet; admins can move anyone. Takes `chaotic good`, `CG`, `neutral`, … | +| `alignment remove [user]` | take yourself off; admins can take anyone off | +| `alignment prune` | admins: take off everyone who has left the server (until then they show greyed out) | +| `alignment clear` | admins: take everyone off, after a confirmation | +| `alignment style ` | admins: how the chart shows by default | +| `alignment export` / `alignment import ` | the chart as YAML; admins can import, which replaces everyone | +| `alignment admin add\|remove\|list` | alignment admins, who may move anyone | -Charts are stored in Red's Config. The rules live in `doge_alignment/chart.py` as pure, tested functions. -`render.py` holds image helpers for drawing the chart, which isn't wired up yet. Missing features are in -[doge_alignment/TODO.md](doge_alignment/TODO.md). +Admins are the alignment admins plus, always, the server owner, members with Administrator, Red's admin and +mod roles, and the bot owner. Names and avatars are looked up live; people who left keep the ones saved when +they were placed. Pictures need ImageMagick (`libmagickwand`) on the bot's host; without it, `alignment` falls +back to text. + +### Layout of the code + +The cog is a thin Discord front end on `doge_alignment/core`, which imports neither discord.py nor Red (a test +checks), so a command-line tool or web app can reuse all of it: + +| Module | | +|---|---| +| `core/alignments.py` | the nine alignments, their grid positions, parsing `CG`/`chaotic-good` | +| `core/chart.py` | the immutable `Chart` and pure operations: place, remove, clear, admins, permission rules | +| `core/storage.py` | to and from plain data (Red's Config) and YAML | +| `core/view.py` | the nine cells to show, with live names and who has left | +| `core/layout.py` | pure geometry: where each label, avatar and name goes | +| `core/render.py` | paints a layout with ImageMagick (Wand); the only stateful drawing code | +| `core/fetch.py` | downloads avatars (HTTPS only, size-limited, image formats only) | +| `cog.py`, `ui.py` | Red Config, permissions, commands, the gallery and confirm views | +| `cli.py` | the second front end, below | + +```sh +python -m doge_alignment text chart.yaml # from `alignment export` +python -m doge_alignment image chart.yaml -o chart.png +python -m doge_alignment tiles chart.yaml -o tiles/ # nine PNGs +``` + +Planned work is in [doge_alignment/TODO.md](doge_alignment/TODO.md). ## watch diff --git a/doge_alignment/TODO.md b/doge_alignment/TODO.md index 57ea033..40843bb 100644 --- a/doge_alignment/TODO.md +++ b/doge_alignment/TODO.md @@ -1,36 +1,36 @@ # doge_alignment: TODO -Missing features and known gaps, roughly in priority order. The cleanup of 2026-11-05 already fixed the bugs -listed at the end. +## Next -## Features +1. **Guess alignments from messages (bonus).** Pass someone's most recent 35 messages to a locally hosted + model (an LLM, or a smaller text classifier) and suggest an alignment for them. + - Core: a pure `guess` module that turns messages into a prompt and parses the model's answer with + `parse_alignment`, plus a model client behind a small protocol, so the cog, the command line or a web + app can use any backend (llama.cpp's OpenAI-compatible API on porygon is the obvious first one). + - Cog: `alignment guess [member]`, reading the history only in channels the bot and the invoker can both + see. The result is a suggestion with an "Apply" button, which follows the usual `may_set` rules. + - Privacy: say in the data statement that messages are sent to the model and not stored. Probably let + members opt out. +2. Let members suggest an alignment for someone else, applied when that person or an alignment admin + accepts. +3. Custom charts per server: other axes or labels than lawful/chaotic and good/evil. `layout.Theme` already + takes the cell colours; labels and axes would need to come from the chart. +4. Emoji and non-Latin names render as boxes with DejaVu Sans. Fall back to Noto fonts (Noto Color Emoji + needs ImageMagick built with color-font support). -1. **Draw the chart as an image.** This was the original goal: a 3x3 grid with a labelled cell per - alignment, filled with members' avatars. `render.py` has the building blocks (backgrounds, a grid layout, - round or rounded avatars with borders), but nothing composes them or sends the result yet. - - Decide on the image library first. Wand needs ImageMagick, which dogebot's Red container doesn't have. - Either add `libmagickwand` to `dogebot/containers/red/Containerfile` and `Wand` to `info.json`, or - port `render.py` to Pillow, which needs no system library. - - Download avatars with Red's aiohttp session, cache them briefly, and fall back to the default avatar. - - Show it from `/alignment_show`, perhaps with a `text` option for the current list. -2. **Use live names and avatars.** The chart stores each member's display name and avatar URL from when the - alignment was set, and both go stale. Look the member up when showing the chart, and keep the stored - copy only for members who have left. -3. **Group the slash commands** under one `/alignment` group (`set`, `show`, `remove`, `admin add`, - `admin remove`, `admin list`) instead of six top-level commands. Merge `alignment_set` and - `alignment_set_other`, since the second already covers the first. -4. **List the admins:** `/alignment admin list`. There's no way to see who they are today. -5. **Clear a chart** (alignment admins): wipe the chart, keeping the admins, with a confirmation button. -6. **Members who leave:** take them off the chart on `on_member_remove`, or show them greyed out. -7. **Recognise Red's admin and mod roles** (`bot.is_admin` and `bot.is_mod`) as alignment admins, so each - server doesn't have to set up its own list. -8. **Text commands** (`[p]alignment …`) for servers that haven't enabled slash commands. Today the cog only - works after `[p]slash enable` for each command and a `[p]slash sync`. -9. **Export and import** a chart as YAML, the format the cog used before it moved to Config, for backups and - for moving between servers. -10. Ideas, not commitments: - - let members suggest an alignment for someone else, applied when that person or an admin accepts; - - custom charts per server (other axes or labels than lawful/chaotic and good/evil). +## Done on 2026-11-05 + +- The chart is drawn as an image: one 3x3 picture (`alignment image`), or nine pictures in Discord's media + gallery (`alignment gallery`), which Discord lays out as three rows of three. Avatars are cut into circles. +- Names and avatars are looked up live. People who left are greyed out and struck through, and + `alignment prune` takes them off. +- One `alignment` command group, both as text commands and as `/alignment` slash commands. `set` covers + setting your own alignment and someone else's. +- `alignment admin list`, `alignment clear` (with a confirmation button), `alignment style`. +- Red's admin and mod roles, server Administrators and the server owner always count as alignment admins. +- YAML export and import, in the format the old cog used. +- The logic moved into `core/`, which doesn't import Discord or Red, with `python -m doge_alignment` as a + second front end. ## Fixed in the 2026-11-05 cleanup diff --git a/doge_alignment/__init__.py b/doge_alignment/__init__.py index f1df834..e08ef33 100644 --- a/doge_alignment/__init__.py +++ b/doge_alignment/__init__.py @@ -1,17 +1,26 @@ -"""Red cog: a server's D&D alignment chart.""" +"""Red cog: a server's D&D alignment chart. -from redbot.core.bot import Red +The cog itself (:mod:`.cog`) is a thin Discord front end on :mod:`.core`, which +knows nothing about Discord. Red is only imported when Red loads the cog, so +``doge_alignment.core`` and the command line (``python -m doge_alignment``) +work without it. +""" -from .doge_alignment import AlignmentCog +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from redbot.core.bot import Red __red_end_user_data_statement__ = ( "This cog stores your alignment, display name and avatar URL " "for each server's chart, and whether you are an alignment admin " - "there. `/alignment_remove` takes you off a chart; Red's data " + "there. `/alignment remove` takes you off a chart; Red's data " "deletion removes you everywhere." ) -async def setup(bot: Red) -> None: +async def setup(bot: "Red") -> None: """Red's entry point.""" + from .cog import AlignmentCog # noqa: PLC0415 (keep Red out of core) + await bot.add_cog(AlignmentCog(bot)) diff --git a/doge_alignment/__main__.py b/doge_alignment/__main__.py new file mode 100644 index 0000000..de32a4c --- /dev/null +++ b/doge_alignment/__main__.py @@ -0,0 +1,7 @@ +"""``python -m doge_alignment``: see :mod:`.cli`.""" + +import sys + +from .cli import main + +sys.exit(main()) diff --git a/doge_alignment/chart.py b/doge_alignment/chart.py deleted file mode 100644 index d90e8a6..0000000 --- a/doge_alignment/chart.py +++ /dev/null @@ -1,175 +0,0 @@ -"""The alignment chart: who sits where, and who may change it. - -Pure functions on plain dicts (stored as-is in Red's Config), so they can be -tested without a bot. Every change returns a new chart and leaves the old one -alone. -""" - -from typing import Literal, TypedDict, cast, get_args - -AlignmentName = Literal[ - "Lawful Good", - "Neutral Good", - "Chaotic Good", - "Lawful Neutral", - "True Neutral", - "Chaotic Neutral", - "Lawful Evil", - "Neutral Evil", - "Chaotic Evil", -] - -# The classic 3x3 chart, row by row: good, neutral, evil -ALIGNMENTS: tuple[AlignmentName, ...] = get_args(AlignmentName) - - -class UserAlignment(TypedDict): - """One user's place on the chart.""" - - alignment: AlignmentName - display_name: str - avatar_url: str | None - - -class AlignmentChart(TypedDict): - """A server's chart. User ids are strings (Config keys must be).""" - - users: dict[str, UserAlignment] - admins: list[str] - - -def empty_chart() -> AlignmentChart: - """Return a chart with nobody on it.""" - return {"users": {}, "admins": []} - - -def is_alignment(value: str) -> bool: - """Whether ``value`` is one of the nine alignments.""" - return value in ALIGNMENTS - - -def as_alignment(value: str) -> AlignmentName: - """Return ``value`` as an alignment. - - Raises: - ValueError: if it isn't one of the nine. - - """ - if not is_alignment(value): - msg = f"{value!r} is not an alignment" - raise ValueError(msg) - return cast("AlignmentName", value) - - -def normalize_chart(data: object) -> AlignmentChart: - """Return a well-formed chart from whatever was stored.""" - if not isinstance(data, dict): - return empty_chart() - users = data.get("users") - admins = data.get("admins") - return { - "users": { - str(uid): entry - for uid, entry in (users or {}).items() - if isinstance(entry, dict) - and is_alignment(entry.get("alignment", "")) - }, - "admins": [str(a) for a in (admins or [])], - } - - -def set_user_alignment( - chart: AlignmentChart, - user_id: str, - alignment: AlignmentName, - display_name: str, - avatar_url: str | None = None, -) -> AlignmentChart: - """Return a new chart with ``user_id`` at ``alignment``.""" - users = dict(chart["users"]) - users[user_id] = { - "alignment": alignment, - "display_name": display_name, - "avatar_url": avatar_url, - } - return {"users": users, "admins": list(chart["admins"])} - - -def remove_user_alignment( - chart: AlignmentChart, user_id: str -) -> AlignmentChart: - """Return a new chart without ``user_id``.""" - users = {k: v for k, v in chart["users"].items() if k != user_id} - return {"users": users, "admins": list(chart["admins"])} - - -def add_admin(chart: AlignmentChart, user_id: str) -> AlignmentChart: - """Return a new chart where ``user_id`` is an alignment admin.""" - admins = list(chart["admins"]) - if user_id not in admins: - admins.append(user_id) - return {"users": dict(chart["users"]), "admins": admins} - - -def remove_admin(chart: AlignmentChart, user_id: str) -> AlignmentChart: - """Return a new chart where ``user_id`` is not an alignment admin.""" - admins = [a for a in chart["admins"] if a != user_id] - return {"users": dict(chart["users"]), "admins": admins} - - -def forget_user(chart: AlignmentChart, user_id: str) -> AlignmentChart: - """Return a new chart with no trace of ``user_id`` (data deletion).""" - return remove_admin(remove_user_alignment(chart, user_id), user_id) - - -def may_set( - chart: AlignmentChart, - invoker_id: str, - target_id: str, - *, - privileged: bool, -) -> bool: - """Whether ``invoker_id`` may place ``target_id`` on the chart. - - Anyone may set their own alignment and place someone who isn't on - the chart yet; only alignment admins (or ``privileged`` users, such - as the bot owner) may move someone who already is. - """ - if invoker_id == target_id or target_id not in chart["users"]: - return True - return privileged or invoker_id in chart["admins"] - - -def may_manage_admins( - chart: AlignmentChart, invoker_id: str, *, privileged: bool -) -> bool: - """Whether ``invoker_id`` may add or remove alignment admins. - - ``privileged`` covers the server owner and the bot owner. - """ - return privileged or invoker_id in chart["admins"] - - -def format_chart(chart: AlignmentChart) -> str: - """Return the chart as text, in chart order, with empty cells left out. - - Raises: - ValueError: for an empty chart; check ``chart["users"]`` first. - - """ - if not chart["users"]: - msg = "the chart is empty" - raise ValueError(msg) - lines: list[str] = [] - for alignment in ALIGNMENTS: - names = sorted( - ( - entry["display_name"] - for entry in chart["users"].values() - if entry["alignment"] == alignment - ), - key=str.casefold, - ) - if names: - lines.append(f"**{alignment}**: {', '.join(names)}") - return "\n".join(lines) diff --git a/doge_alignment/cli.py b/doge_alignment/cli.py new file mode 100644 index 0000000..03a2a83 --- /dev/null +++ b/doge_alignment/cli.py @@ -0,0 +1,95 @@ +"""Command-line front end: render a YAML chart without Discord. + + python -m doge_alignment text chart.yaml + python -m doge_alignment image chart.yaml -o chart.png + python -m doge_alignment tiles chart.yaml -o tiles/ + +The YAML is what ``/alignment export`` produces. Everyone in the file counts as +present, and avatars are downloaded from their saved URLs unless +``--no-avatars`` is given. +""" + +import argparse +import asyncio +from collections.abc import Sequence +from pathlib import Path + +import aiohttp + +from .core.fetch import avatar_urls, by_user, fetch_images +from .core.storage import ChartFormatError, from_yaml +from .core.view import ( + Cell, + cells, + everyone, + format_text, + tile_filename, +) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m doge_alignment", + description="Show an exported alignment chart.", + ) + parser.add_argument( + "mode", + choices=("text", "image", "tiles"), + help="text, one PNG, or one PNG per alignment", + ) + parser.add_argument("chart", type=Path, help="exported YAML chart") + parser.add_argument( + "-o", + "--output", + type=Path, + help="PNG file (image) or directory (tiles)", + ) + parser.add_argument( + "--no-avatars", + action="store_true", + help="draw initials instead of downloading avatars", + ) + return parser + + +async def _avatars(chart_cells: tuple[Cell, ...]) -> dict[str, bytes]: + people = everyone(chart_cells) + async with aiohttp.ClientSession() as session: + images = await fetch_images(session, avatar_urls(people)) + return by_user(people, images) + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the command line; return the exit status.""" + parser = _parser() + args = parser.parse_args(argv) + try: + chart = from_yaml(args.chart.read_text(encoding="utf-8")) + except (OSError, ChartFormatError) as error: + parser.error(f"{args.chart}: {error}") + chart_cells = cells(chart) + if args.mode == "text": + print(format_text(chart_cells) or "Nobody is on the chart.") # noqa: T201 + return 0 + # Rendering needs ImageMagick; text mode doesn't + from .core.render import render_chart, render_tiles # noqa: PLC0415 + + avatars = {} if args.no_avatars else asyncio.run(_avatars(chart_cells)) + if args.mode == "image": + out = args.output or Path("alignment.png") + out.write_bytes(render_chart(chart_cells, avatars)) + print(out) # noqa: T201 + return 0 + folder = args.output or Path("alignment-tiles") + folder.mkdir(parents=True, exist_ok=True) + for index, (cell, png) in enumerate( + zip( + chart_cells, + render_tiles(chart_cells, avatars), + strict=True, + ), + start=1, + ): + (folder / tile_filename(index, cell)).write_bytes(png) + print(folder) # noqa: T201 + return 0 diff --git a/doge_alignment/cog.py b/doge_alignment/cog.py new file mode 100644 index 0000000..0bdafed --- /dev/null +++ b/doge_alignment/cog.py @@ -0,0 +1,581 @@ +"""The Discord front end: ``[p]alignment`` and ``/alignment`` commands. + +Everything here is Discord glue: reading and writing Red's Config, permissions, +fetching avatars, and sending messages. The chart's rules, the YAML format and +the drawing all live in :mod:`.core`. +""" + +import asyncio +import io +import logging +from collections import OrderedDict +from collections.abc import Callable, Mapping +from typing import Literal + +import aiohttp +import discord +from redbot.core import Config, app_commands, commands +from redbot.core.bot import Red +from redbot.core.utils.chat_formatting import pagify + +from .core.alignments import AlignmentName, matching, parse_alignment +from .core.chart import ( + Chart, + Entry, + add_admin, + clear, + forget_user, + may_manage, + may_remove, + may_set, + place, + remove_admin, + replace_users, + unplace, + unplace_all, +) +from .core.fetch import avatar_urls, by_user, fetch_images +from .core.storage import ( + ChartFormatError, + from_data, + from_yaml, + to_data, + to_yaml, +) +from .core.view import ( + Cell, + Lookup, + Profile, + absent, + cells, + everyone, + format_text, + tile_filename, +) +from .ui import ConfirmView, gallery_view + +log = logging.getLogger("red.doge_cogs.doge_alignment") + +RequestType = Literal["discord_deleted_user", "owner", "user", "user_strict"] +Style = Literal["image", "gallery", "text"] +STYLES: tuple[Style, ...] = ("image", "gallery", "text") + +AVATAR_CACHE_SIZE = 512 +MAX_IMPORT_BYTES = 1024 * 1024 +NO_MENTIONS = discord.AllowedMentions.none() +BAD_ALIGNMENT = ( + "I don't know the alignment {text!r}. Use a name like " + "`chaotic good`, or its letters: LG NG CG LN TN CN LE NE CE." +) + + +def avatar_url(user: discord.User | discord.Member) -> str: + """Return a 128px PNG of ``user``'s avatar (server avatar if set).""" + return user.display_avatar.replace(format="png", size=128).url + + +def member_lookup(guild: discord.Guild) -> Lookup: + """Return a lookup of live names and avatars in ``guild``.""" + + def lookup(user_id: str) -> Profile | None: + member = guild.get_member(int(user_id)) + if member is None: + return None + return Profile(member.display_name, avatar_url(member)) + + return lookup + + +def remember( + cache: "OrderedDict[str, bytes]", + new: Mapping[str, bytes], + used: frozenset[str], + limit: int, +) -> "OrderedDict[str, bytes]": + """Return an LRU ``cache`` with ``new`` added and ``used`` refreshed.""" + merged = OrderedDict(cache) + merged.update(new) + for url in used & merged.keys(): + merged.move_to_end(url) + while len(merged) > limit: + merged.popitem(last=False) + return merged + + +class AlignmentCog(commands.Cog): + """Keep track of everyone's D&D alignment.""" + + def __init__(self, bot: Red) -> None: + """Create the cog.""" + self.bot = bot + self.config = Config.get_conf( + self, identifier=0xA119E5C4A7, force_registration=True + ) + self.config.register_guild( + users={}, admins=[], default_style="image" + ) + self._locks: dict[int, asyncio.Lock] = {} + self._avatars: OrderedDict[str, bytes] = OrderedDict() + self._session: aiohttp.ClientSession | None = None + + async def cog_unload(self) -> None: + """Close the avatar download session.""" + if self._session is not None: + await self._session.close() + + async def red_delete_data_for_user( + self, *, requester: RequestType, user_id: int + ) -> None: + """Take a user off every chart and every admin list.""" + del requester + for guild_id in await self.config.all_guilds(): + await self._update_id( + guild_id, lambda c: forget_user(c, str(user_id)) + ) + + # Storage -------------------------------------------------------- + + async def _load(self, guild: discord.Guild) -> Chart: + return from_data(await self.config.guild(guild).all()) + + async def _update_id( + self, guild_id: int, change: Callable[[Chart], Chart] + ) -> Chart: + """Apply ``change`` to a guild's chart and save the result.""" + lock = self._locks.setdefault(guild_id, asyncio.Lock()) + async with lock: + group = self.config.guild_from_id(guild_id) + chart = change(from_data(await group.all())) + data = to_data(chart) + await group.users.set(data["users"]) + await group.admins.set(data["admins"]) + return chart + + async def _update( + self, guild: discord.Guild, change: Callable[[Chart], Chart] + ) -> Chart: + return await self._update_id(guild.id, change) + + # Permissions ---------------------------------------------------- + + async def _privileged(self, ctx: commands.Context) -> bool: + """Bot owner, server owner, administrators, Red admins/mods.""" + author = ctx.author + if await self.bot.is_owner(author): + return True + if not isinstance(author, discord.Member): + return False + return ( + author.id == author.guild.owner_id + or author.guild_permissions.administrator + or await self.bot.is_mod(author) + ) + + async def _may_manage( + self, ctx: commands.Context, chart: Chart + ) -> bool: + return may_manage( + chart, + str(ctx.author.id), + privileged=await self._privileged(ctx), + ) + + async def _deny(self, ctx: commands.Context) -> None: + await ctx.send( + "Only alignment admins, server admins and mods can " + "do that.", + ephemeral=True, + ) + + async def _confirm(self, ctx: commands.Context, question: str) -> bool: + view = ConfirmView(ctx.author.id, "Yes, do it") + await ctx.send(question, view=view, ephemeral=True) + await view.wait() + return bool(view.confirmed) + + # Pictures ------------------------------------------------------- + + async def _avatar_bytes( + self, chart_cells: tuple[Cell, ...] + ) -> dict[str, bytes]: + people = everyone(chart_cells) + urls = avatar_urls(people) + if self._session is None or self._session.closed: + self._session = aiohttp.ClientSession() + fetched = await fetch_images( + self._session, urls - self._avatars.keys() + ) + self._avatars = remember( + self._avatars, fetched, urls, AVATAR_CACHE_SIZE + ) + return by_user(people, self._avatars) + + async def _send_picture( + self, + ctx: commands.Context, + style: Style, + title: str, + chart_cells: tuple[Cell, ...], + ) -> bool: + """Send the chart as pictures; False without ImageMagick.""" + try: + from .core import render # noqa: PLC0415 + except ImportError: + log.warning("Wand/ImageMagick missing; showing text") + return False + avatars = await self._avatar_bytes(chart_cells) + if style == "image": + png = await asyncio.to_thread( + render.render_chart, chart_cells, avatars + ) + await ctx.send( + f"**{title}**", + file=discord.File( + io.BytesIO(png), "alignment.png" + ), + allowed_mentions=NO_MENTIONS, + ) + return True + tiles = await asyncio.to_thread( + render.render_tiles, chart_cells, avatars + ) + await ctx.send( + view=gallery_view(title, chart_cells), + files=[ + discord.File( + io.BytesIO(png), tile_filename(i, c) + ) + for i, (c, png) in enumerate( + zip(chart_cells, tiles, strict=True), + start=1, + ) + ], + allowed_mentions=NO_MENTIONS, + ) + return True + + async def _send_text( + self, ctx: commands.Context, chart_cells: tuple[Cell, ...] + ) -> None: + for page in pagify(format_text(chart_cells)): + await ctx.send(page, allowed_mentions=NO_MENTIONS) + + # Commands ------------------------------------------------------- + + @commands.guild_only() + # ty can't match Red's Context to hybrid_group's generic one + @commands.hybrid_group( # ty: ignore[invalid-argument-type] + name="alignment", fallback="show", invoke_without_command=True + ) + @app_commands.describe( + style="image: one picture; gallery: nine pictures; text" + ) + async def alignment( + self, ctx: commands.Context, style: Style | None = None + ) -> None: + """Show this server's alignment chart.""" + guild = ctx.guild + if guild is None: + return + chart = await self._load(guild) + if not chart.users: + await ctx.send( + "Nobody is on the chart yet. Use " + f"`{ctx.clean_prefix}alignment set` or " + "`/alignment set`." + ) + return + chosen: Style = ( + style or await self.config.guild(guild).default_style() + ) + chart_cells = cells(chart, member_lookup(guild)) + title = f"{guild.name}: alignment chart" + if chosen != "text": + await ctx.defer() + if await self._send_picture( + ctx, chosen, title, chart_cells + ): + return + await self._send_text(ctx, chart_cells) + + @alignment.command(name="set") + @app_commands.describe( + alignment="Lawful Good, CG, chaotic neutral, ...", + member="Whose alignment to set (leave out for your own)", + ) + async def alignment_set( + self, + ctx: commands.Context, + alignment: str, + member: discord.Member | None = None, + ) -> None: + """Put yourself, or someone else, on the chart.""" + guild = ctx.guild + if guild is None: + return + parsed = parse_alignment(alignment) + if parsed is None: + await ctx.send( + BAD_ALIGNMENT.format(text=alignment), + ephemeral=True, + ) + return + target = member or ctx.author + if not isinstance(target, discord.Member): + return + await self._set(ctx, guild, target, parsed) + + @alignment_set.autocomplete("alignment") + async def _alignment_autocomplete( + self, interaction: discord.Interaction, current: str + ) -> list[app_commands.Choice[str]]: + del interaction + return [ + app_commands.Choice(name=a, value=a) + for a in matching(current) + ] + + async def _set( + self, + ctx: commands.Context, + guild: discord.Guild, + member: discord.Member, + alignment: AlignmentName, + ) -> None: + invoker_id, target_id = str(ctx.author.id), str(member.id) + if not may_set( + await self._load(guild), + invoker_id, + target_id, + privileged=await self._privileged(ctx), + ): + await ctx.send( + f"{member.display_name} is already on the " + "chart; only alignment admins can move them.", + ephemeral=True, + allowed_mentions=NO_MENTIONS, + ) + return + entry = Entry( + alignment, member.display_name, avatar_url(member) + ) + await self._update(guild, lambda c: place(c, target_id, entry)) + who = ( + "Your alignment" + if target_id == invoker_id + else f"Alignment for **{member.display_name}**" + ) + await ctx.send( + f"{who} is now **{alignment}**.", + allowed_mentions=NO_MENTIONS, + ) + + @alignment.command(name="remove") + @app_commands.describe( + user="Who to take off (leave out for yourself; admins only " + "for others)" + ) + async def alignment_remove( + self, ctx: commands.Context, user: discord.User | None = None + ) -> None: + """Take yourself, or someone else, off the chart.""" + guild = ctx.guild + if guild is None: + return + target = user or ctx.author + chart = await self._load(guild) + if not may_remove( + chart, + str(ctx.author.id), + str(target.id), + privileged=await self._privileged(ctx), + ): + await self._deny(ctx) + return + if str(target.id) not in chart.users: + await ctx.send( + "They aren't on the chart.", ephemeral=True + ) + return + await self._update(guild, lambda c: unplace(c, str(target.id))) + await ctx.send( + "Removed from the chart.", + ephemeral=True, + allowed_mentions=NO_MENTIONS, + ) + + @alignment.command(name="prune") + async def alignment_prune(self, ctx: commands.Context) -> None: + """Take everyone who has left the server off the chart.""" + guild = ctx.guild + if guild is None: + return + chart = await self._load(guild) + if not await self._may_manage(ctx, chart): + await self._deny(ctx) + return + gone = absent(chart, member_lookup(guild)) + if not gone: + await ctx.send("Nobody has left.", ephemeral=True) + return + await self._update(guild, lambda c: unplace_all(c, gone)) + await ctx.send( + f"Took {len(gone)} people who left off the chart." + ) + + @alignment.command(name="clear") + async def alignment_clear(self, ctx: commands.Context) -> None: + """Take everyone off the chart (admins stay admins).""" + guild = ctx.guild + if guild is None: + return + chart = await self._load(guild) + if not await self._may_manage(ctx, chart): + await self._deny(ctx) + return + if not await self._confirm( + ctx, + f"Take all {len(chart.users)} people off the chart? " + "Export it first if you might want it back.", + ): + await ctx.send("Left the chart alone.", ephemeral=True) + return + await self._update(guild, clear) + await ctx.send("The chart is empty now.") + + @alignment.command(name="style") + @app_commands.describe(style="How the chart is shown by default") + async def alignment_style( + self, ctx: commands.Context, style: Style + ) -> None: + """Choose how this server's chart is shown by default.""" + guild = ctx.guild + if guild is None: + return + if not await self._may_manage(ctx, await self._load(guild)): + await self._deny(ctx) + return + await self.config.guild(guild).default_style.set(style) + await ctx.send(f"The chart now shows as **{style}**.") + + @alignment.command(name="export") + async def alignment_export(self, ctx: commands.Context) -> None: + """Download this server's chart as YAML.""" + guild = ctx.guild + if guild is None: + return + text = to_yaml(await self._load(guild)) + await ctx.send( + "Here's the chart. `alignment import` takes it back.", + file=discord.File( + io.BytesIO(text.encode()), + f"alignment-{guild.id}.yaml", + ), + ephemeral=True, + ) + + @alignment.command(name="import") + @app_commands.describe(file="A YAML chart from `alignment export`") + async def alignment_import( + self, ctx: commands.Context, file: discord.Attachment + ) -> None: + """Replace the chart with an exported one (admins stay).""" + guild = ctx.guild + if guild is None: + return + if not await self._may_manage(ctx, await self._load(guild)): + await self._deny(ctx) + return + if file.size > MAX_IMPORT_BYTES: + await ctx.send("That file is too big.", ephemeral=True) + return + try: + imported = from_yaml( + (await file.read()).decode("utf-8") + ) + except (UnicodeDecodeError, ChartFormatError) as error: + await ctx.send( + f"I can't read that chart: {error}", + ephemeral=True, + ) + return + if not await self._confirm( + ctx, + f"Replace the chart with the {len(imported.users)} " + "people in that file?", + ): + await ctx.send("Left the chart alone.", ephemeral=True) + return + await self._update(guild, lambda c: replace_users(c, imported)) + await ctx.send( + f"Imported {len(imported.users)} people. People who " + "aren't in this server show as having left." + ) + + # Admins --------------------------------------------------------- + + @alignment.group(name="admin", invoke_without_command=True) + async def alignment_admin(self, ctx: commands.Context) -> None: + """Manage who can move anyone on the chart.""" + await ctx.send_help() + + @alignment_admin.command(name="add") + @app_commands.describe(member="Who may move anyone on the chart") + async def alignment_admin_add( + self, ctx: commands.Context, member: discord.Member + ) -> None: + """Make someone an alignment admin.""" + await self._change_admin(ctx, member, add=True) + + @alignment_admin.command(name="remove") + @app_commands.describe(user="Who should stop being an alignment admin") + async def alignment_admin_remove( + self, ctx: commands.Context, user: discord.User + ) -> None: + """Stop someone being an alignment admin.""" + await self._change_admin(ctx, user, add=False) + + async def _change_admin( + self, + ctx: commands.Context, + user: discord.User | discord.Member, + *, + add: bool, + ) -> None: + guild = ctx.guild + if guild is None: + return + if not await self._may_manage(ctx, await self._load(guild)): + await self._deny(ctx) + return + uid = str(user.id) + await self._update( + guild, + (lambda c: add_admin(c, uid)) + if add + else (lambda c: remove_admin(c, uid)), + ) + state = "is now" if add else "is no longer" + await ctx.send( + f"{user.mention} {state} an alignment admin.", + allowed_mentions=NO_MENTIONS, + ) + + @alignment_admin.command(name="list") + async def alignment_admin_list(self, ctx: commands.Context) -> None: + """List the alignment admins.""" + guild = ctx.guild + if guild is None: + return + admins = (await self._load(guild)).admins + lines = ( + "\n".join(f"- <@{uid}>" for uid in admins) + if admins + else "No alignment admins yet." + ) + await ctx.send( + "Alignment admins (server admins, mods and the " + f"server owner can always manage the chart):\n{lines}", + ephemeral=True, + allowed_mentions=NO_MENTIONS, + ) diff --git a/doge_alignment/core/__init__.py b/doge_alignment/core/__init__.py new file mode 100644 index 0000000..55cd1cf --- /dev/null +++ b/doge_alignment/core/__init__.py @@ -0,0 +1,11 @@ +"""The alignment chart without Discord. + +Everything a front end needs: the chart and its rules (:mod:`.chart`), storage +and YAML formats (:mod:`.storage`), what to show (:mod:`.view`), where to draw +it (:mod:`.layout`) and the drawing itself (:mod:`.render`, ImageMagick through +Wand). The Red cog is one front end, ``python -m doge_alignment`` another; a +web app would be a third. + +Nothing in this package imports discord.py or Red (a test checks), and apart +from :mod:`.render` and :mod:`.fetch` it is pure functions over immutable data. +""" diff --git a/doge_alignment/core/alignments.py b/doge_alignment/core/alignments.py new file mode 100644 index 0000000..c663886 --- /dev/null +++ b/doge_alignment/core/alignments.py @@ -0,0 +1,84 @@ +"""The nine alignments, their place on the 3x3 chart, and parsing them.""" + +import re +from typing import Literal, cast, get_args + +AlignmentName = Literal[ + "Lawful Good", + "Neutral Good", + "Chaotic Good", + "Lawful Neutral", + "True Neutral", + "Chaotic Neutral", + "Lawful Evil", + "Neutral Evil", + "Chaotic Evil", +] + +# The classic chart, row by row: good, neutral, evil; lawful to chaotic +ALIGNMENTS: tuple[AlignmentName, ...] = get_args(AlignmentName) + +_ABBREVIATIONS: dict[str, AlignmentName] = { + "".join(word[0] for word in name.split()).lower(): name + for name in ALIGNMENTS +} + +# Other names people type for the middle square +_NEUTRAL_ALIASES = frozenset({"n", "nn", "neutral", "neutralneutral"}) + + +def is_alignment(value: str) -> bool: + """Whether ``value`` is exactly one of the nine names.""" + return value in ALIGNMENTS + + +def as_alignment(value: str) -> AlignmentName: + """Return ``value`` as an alignment. + + Raises: + ValueError: if it isn't exactly one of the nine names. + + """ + if not is_alignment(value): + msg = f"{value!r} is not an alignment" + raise ValueError(msg) + return cast("AlignmentName", value) + + +def _squash(text: str) -> str: + return re.sub(r"[^a-z]", "", text.lower()) + + +def parse_alignment(text: str) -> AlignmentName | None: + """Read an alignment the way people type it, or return None. + + Takes the full name in any case and spacing (``chaotic-good``), the + two-letter abbreviation (``CG``), and ``neutral``/``N``/``NN`` for + True Neutral. + """ + squashed = _squash(text) + if squashed in _NEUTRAL_ALIASES: + return "True Neutral" + by_name = {_squash(name): name for name in ALIGNMENTS} + return by_name.get(squashed) or _ABBREVIATIONS.get(squashed) + + +def abbreviation(alignment: AlignmentName) -> str: + """Return the two-letter abbreviation, such as ``CG``.""" + return "".join(word[0] for word in alignment.split()) + + +def grid_position(alignment: AlignmentName) -> tuple[int, int]: + """Return ``(row, column)`` of ``alignment`` on the 3x3 chart.""" + return divmod(ALIGNMENTS.index(alignment), 3) + + +def matching(prefix: str) -> tuple[AlignmentName, ...]: + """Return the alignments a partly typed name could mean.""" + wanted = _squash(prefix) + exact = parse_alignment(prefix) + return tuple( + name + for name in ALIGNMENTS + if name == exact or _squash(name).startswith(wanted) + ) diff --git a/doge_alignment/core/chart.py b/doge_alignment/core/chart.py new file mode 100644 index 0000000..f9e2e2e --- /dev/null +++ b/doge_alignment/core/chart.py @@ -0,0 +1,152 @@ +"""A server's chart: who sits where, and who may change it. + +Charts are immutable. Every operation returns a new chart and leaves its +argument alone, so they compose and are trivial to test. +""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field, replace +from types import MappingProxyType + +from .alignments import AlignmentName + + +@dataclass(frozen=True) +class Entry: + """One person's place on the chart. + + ``display_name`` and ``avatar_url`` are a snapshot from when the + alignment was set. Front ends show live ones where they can, and fall + back to these for people who have left. + """ + + alignment: AlignmentName + display_name: str + avatar_url: str | None = None + + +def _frozen(users: Mapping[str, Entry]) -> Mapping[str, Entry]: + return MappingProxyType(dict(users)) + + +@dataclass(frozen=True) +class Chart: + """A chart. User ids are strings, as Red's Config needs.""" + + users: Mapping[str, Entry] = field(default_factory=lambda: _frozen({})) + admins: tuple[str, ...] = () + + +def make_chart( + users: Mapping[str, Entry] | None = None, + admins: Iterable[str] = (), +) -> Chart: + """Return a chart, with ``admins`` de-duplicated in order.""" + return Chart( + users=_frozen(users or {}), + admins=tuple(dict.fromkeys(admins)), + ) + + +def empty_chart() -> Chart: + """Return a chart with nobody on it.""" + return make_chart() + + +def _with_users(chart: Chart, users: Mapping[str, Entry]) -> Chart: + return replace(chart, users=_frozen(users)) + + +def place(chart: Chart, user_id: str, entry: Entry) -> Chart: + """Return ``chart`` with ``user_id`` at ``entry``.""" + return _with_users(chart, {**chart.users, user_id: entry}) + + +def unplace(chart: Chart, user_id: str) -> Chart: + """Return ``chart`` without ``user_id`` on it (admins unchanged).""" + return _with_users( + chart, + {k: v for k, v in chart.users.items() if k != user_id}, + ) + + +def unplace_all(chart: Chart, user_ids: Iterable[str]) -> Chart: + """Return ``chart`` without any of ``user_ids`` on it.""" + gone = frozenset(user_ids) + return _with_users( + chart, + {k: v for k, v in chart.users.items() if k not in gone}, + ) + + +def clear(chart: Chart) -> Chart: + """Return ``chart`` with nobody on it, keeping the admins.""" + return _with_users(chart, {}) + + +def replace_users(chart: Chart, other: Chart) -> Chart: + """Return ``chart`` with ``other``'s people and its own admins.""" + return _with_users(chart, other.users) + + +def add_admin(chart: Chart, user_id: str) -> Chart: + """Return ``chart`` where ``user_id`` is an alignment admin.""" + return make_chart(chart.users, (*chart.admins, user_id)) + + +def remove_admin(chart: Chart, user_id: str) -> Chart: + """Return ``chart`` where ``user_id`` is not an alignment admin.""" + return replace( + chart, admins=tuple(a for a in chart.admins if a != user_id) + ) + + +def forget_user(chart: Chart, user_id: str) -> Chart: + """Return ``chart`` with no trace of ``user_id`` (data deletion).""" + return remove_admin(unplace(chart, user_id), user_id) + + +def is_admin(chart: Chart, user_id: str) -> bool: + """Whether ``user_id`` is on the chart's admin list.""" + return user_id in chart.admins + + +def may_manage(chart: Chart, invoker_id: str, *, privileged: bool) -> bool: + """Whether ``invoker_id`` may change anyone and anything on the chart. + + ``privileged`` is the front end's call: on Discord, the server and bot + owners, administrators, and Red's admin and mod roles. + """ + return privileged or is_admin(chart, invoker_id) + + +def may_set( + chart: Chart, + invoker_id: str, + target_id: str, + *, + privileged: bool, +) -> bool: + """Whether ``invoker_id`` may place ``target_id`` on the chart. + + Anyone may set their own alignment and place someone who isn't on + the chart yet; only chart managers may move someone who already is. + """ + return ( + invoker_id == target_id + or target_id not in chart.users + or may_manage(chart, invoker_id, privileged=privileged) + ) + + +def may_remove( + chart: Chart, + invoker_id: str, + target_id: str, + *, + privileged: bool, +) -> bool: + """Whether ``invoker_id`` may take ``target_id`` off the chart.""" + return invoker_id == target_id or may_manage( + chart, invoker_id, privileged=privileged + ) diff --git a/doge_alignment/core/fetch.py b/doge_alignment/core/fetch.py new file mode 100644 index 0000000..255a5c5 --- /dev/null +++ b/doge_alignment/core/fetch.py @@ -0,0 +1,84 @@ +"""Download avatars over HTTPS with aiohttp. + +Generic: it knows URLs, not Discord. Front ends pass their own session (Red's +or a fresh one), and may keep a cache keyed by URL, since avatar URLs change +when the avatar does. +""" + +import asyncio +from collections.abc import Iterable, Mapping + +import aiohttp + +from .images import sniff +from .view import Person + +MAX_AVATAR_BYTES = 4 * 1024 * 1024 +TIMEOUT = aiohttp.ClientTimeout(total=10) + + +def avatar_urls(people: Iterable[Person]) -> frozenset[str]: + """Return the avatar URLs of ``people``, without duplicates.""" + return frozenset(p.avatar_url for p in people if p.avatar_url) + + +def by_user( + people: Iterable[Person], images: Mapping[str, bytes] +) -> dict[str, bytes]: + """Return avatar bytes keyed by user id, from bytes keyed by URL.""" + return { + p.user_id: images[p.avatar_url] + for p in people + if p.avatar_url and p.avatar_url in images + } + + +def _allowed(url: str) -> bool: + return url.startswith("https://") + + +async def _read_limited(response: aiohttp.ClientResponse) -> bytes | None: + chunks: list[bytes] = [] + size = 0 + async for chunk in response.content.iter_chunked(64 * 1024): + size += len(chunk) + if size > MAX_AVATAR_BYTES: + return None + chunks.append(chunk) + return b"".join(chunks) + + +async def fetch_image(session: aiohttp.ClientSession, url: str) -> bytes | None: + """Return the image at ``url``, or None if it can't be had. + + Only HTTPS, at most :data:`MAX_AVATAR_BYTES`, and only formats + :func:`.images.sniff` accepts. + """ + if not _allowed(url): + return None + try: + async with session.get(url, timeout=TIMEOUT) as response: + if response.status != 200: # noqa: PLR2004 + return None + data = await _read_limited(response) + except (aiohttp.ClientError, TimeoutError): + return None + if data is None or sniff(data) is None: + return None + return data + + +async def fetch_images( + session: aiohttp.ClientSession, + urls: Iterable[str], + concurrency: int = 8, +) -> dict[str, bytes]: + """Return the images at ``urls`` that could be fetched, by URL.""" + limit = asyncio.Semaphore(concurrency) + + async def one(url: str) -> tuple[str, bytes | None]: + async with limit: + return url, await fetch_image(session, url) + + results = await asyncio.gather(*(one(u) for u in set(urls))) + return {url: data for url, data in results if data is not None} diff --git a/doge_alignment/core/images.py b/doge_alignment/core/images.py new file mode 100644 index 0000000..8bd3632 --- /dev/null +++ b/doge_alignment/core/images.py @@ -0,0 +1,18 @@ +"""Recognise the image formats avatars come in, without decoding them.""" + +from typing import Literal + +ImageFormat = Literal["png", "jpeg", "gif", "webp"] + + +def sniff(data: bytes) -> ImageFormat | None: + """Return the format of image ``data``, if it's one we decode.""" + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "png" + if data.startswith(b"\xff\xd8\xff"): + return "jpeg" + if data.startswith((b"GIF87a", b"GIF89a")): + return "gif" + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "webp" + return None diff --git a/doge_alignment/core/layout.py b/doge_alignment/core/layout.py new file mode 100644 index 0000000..852ea5d --- /dev/null +++ b/doge_alignment/core/layout.py @@ -0,0 +1,316 @@ +"""Where everything goes in a chart picture. Pure geometry, no drawing. + +:func:`plan_chart` lays out the 3x3 chart as one picture and +:func:`plan_tile` lays out a single cell as its own square picture, for front +ends that show the nine squares separately (Discord's media gallery). +:mod:`.render` paints the plans. +""" + +import math +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from types import MappingProxyType + +from .alignments import AlignmentName, grid_position +from .view import Cell, Person + +DEFAULT_CELL_COLORS: Mapping[AlignmentName, str] = MappingProxyType( + { + "Lawful Good": "#2f6f8f", + "Neutral Good": "#2f8f6a", + "Chaotic Good": "#5f8f2f", + "Lawful Neutral": "#4a5a8a", + "True Neutral": "#6b6b6b", + "Chaotic Neutral": "#8a7a3a", + "Lawful Evil": "#6a3f8a", + "Neutral Evil": "#8a3f6a", + "Chaotic Evil": "#9a3a2f", + } +) + + +@dataclass(frozen=True) +class Theme: + """Sizes and colours. Sizes are in pixels.""" + + background: str = "#1e1f22" + cell_colors: Mapping[AlignmentName, str] = field( + default_factory=lambda: DEFAULT_CELL_COLORS + ) + text_color: str = "#ffffff" + ring_color: str = "#ffffff" + absent_ring_color: str = "#555555" + placeholder_color: str = "#40444b" + # A TrueType font file; None lets :mod:`.render` find one + font: str | None = None + cell_size: int = 360 + tile_size: int = 512 + gap: int = 12 + margin: int = 16 + padding: int = 12 + corner_radius: int = 18 + label_ratio: float = 0.13 + avatar_gap: int = 8 + max_avatar: int = 128 + min_avatar: int = 36 + # Names go under avatars at least this big + min_named_avatar: int = 56 + ring_ratio: float = 0.05 + + +@dataclass(frozen=True) +class Box: + """A rectangle: top-left corner and size.""" + + x: int + y: int + w: int + h: int + + +@dataclass(frozen=True) +class Slot: + """One person's avatar, and their name under it if there's room.""" + + person: Person + avatar: Box + name: str = "" + name_box: Box | None = None + font_size: int = 0 + + +@dataclass(frozen=True) +class CellPlan: + """One cell: its box, its label, and the avatars in it.""" + + alignment: AlignmentName + box: Box + label_box: Box + label_size: int + slots: tuple[Slot, ...] = () + # "+N" badge for people who didn't fit, and how many + overflow: int = 0 + overflow_box: Box | None = None + + +@dataclass(frozen=True) +class Plan: + """A whole picture.""" + + width: int + height: int + cells: tuple[CellPlan, ...] + + +@dataclass(frozen=True) +class Grid: + """How to arrange avatars in a cell.""" + + columns: int + rows: int + size: int + name_height: int + + +def name_height(size: int) -> int: + """Height of the name line under an avatar of ``size``.""" + return round(min(max(size * 0.2, 12), 20)) + 4 + + +def _fit(count: int, columns: int, area: Box, gap: int, *, names: bool) -> Grid: + rows = math.ceil(count / columns) + by_width = (area.w - (columns - 1) * gap) // columns + by_height = (area.h - (rows - 1) * gap) // rows + if not names: + return Grid(columns, rows, min(by_width, by_height), 0) + # name_height grows with size, so solve by_height - name_height(s) + # for s from the largest name line down + size = min(by_width, by_height - name_height(by_height)) + return Grid(columns, rows, size, name_height(size)) + + +# Average width of a bold character, as a fraction of the font size +CHAR_WIDTH = 0.68 + +# Names are worth this much avatar size +NAMED_BONUS = 1.3 + + +def _score(grid: Grid, theme: Theme) -> tuple[float, int]: + size = min(grid.size, theme.max_avatar) + return (size * (NAMED_BONUS if grid.name_height else 1), -grid.rows) + + +def best_grid(count: int, area: Box, theme: Theme) -> Grid: + """Return the arrangement with the biggest avatars for ``count``. + + Names are shown when avatars can still be at least + ``theme.min_named_avatar`` with them, and preferred unless they + shrink avatars by more than :data:`NAMED_BONUS`. + """ + candidates = [ + grid + for columns in range(1, count + 1) + for grid in ( + _fit( + count, + columns, + area, + theme.avatar_gap, + names=True, + ), + _fit( + count, + columns, + area, + theme.avatar_gap, + names=False, + ), + ) + if grid.name_height == 0 or grid.size >= theme.min_named_avatar + ] + best = max(candidates, key=lambda g: _score(g, theme)) + return replace(best, size=min(best.size, theme.max_avatar)) + + +def capacity(area: Box, theme: Theme) -> int: + """How many smallest avatars fit in ``area``.""" + step = theme.min_avatar + theme.avatar_gap + return ((area.w + theme.avatar_gap) // step) * ( + (area.h + theme.avatar_gap) // step + ) + + +def truncate(text: str, max_chars: int) -> str: + """Shorten ``text`` to ``max_chars``, ending in an ellipsis if cut.""" + if len(text) <= max_chars: + return text + return text[: max(max_chars - 1, 0)] + "…" + + +def _row_boxes(grid: Grid, count: int, area: Box, gap: int) -> list[Box]: + cell_h = grid.size + grid.name_height + block_h = grid.rows * cell_h + (grid.rows - 1) * gap + top = area.y + (area.h - block_h) // 2 + boxes: list[Box] = [] + for row in range(grid.rows): + in_row = min(grid.columns, count - row * grid.columns) + row_w = in_row * grid.size + (in_row - 1) * gap + left = area.x + (area.w - row_w) // 2 + boxes += [ + Box( + left + i * (grid.size + gap), + top + row * (cell_h + gap), + grid.size, + grid.size, + ) + for i in range(in_row) + ] + return boxes + + +def _slot(person: Person, box: Box, grid: Grid, gap: int) -> Slot: + if not grid.name_height: + return Slot(person, box) + font_size = grid.name_height - 4 + width = box.w + gap + # Keep a few pixels between neighbouring names + max_chars = max(int((width - 6) / (font_size * CHAR_WIDTH)), 3) + return Slot( + person, + box, + truncate(person.name, max_chars), + Box(box.x - gap // 2, box.y + box.h, width, grid.name_height), + font_size, + ) + + +def plan_cell(cell: Cell, box: Box, theme: Theme) -> CellPlan: + """Lay out ``cell`` inside ``box``.""" + label_h = round(box.h * theme.label_ratio) + pad = theme.padding + label_box = Box(box.x + pad, box.y + pad, box.w - 2 * pad, label_h) + area = Box( + box.x + pad, + label_box.y + label_h + pad // 2, + box.w - 2 * pad, + box.h - label_h - 2 * pad - pad // 2, + ) + base = CellPlan(cell.alignment, box, label_box, round(label_h * 0.62)) + people = cell.people + if not people: + return base + fits = capacity(area, theme) + overflow = len(people) - fits + 1 if len(people) > fits else 0 + shown = people[: len(people) - overflow] if overflow else people + grid = best_grid(len(shown) + (1 if overflow else 0), area, theme) + boxes = _row_boxes( + grid, + len(shown) + (1 if overflow else 0), + area, + theme.avatar_gap, + ) + return replace( + base, + slots=tuple( + _slot(p, b, grid, theme.avatar_gap) + for p, b in zip(shown, boxes, strict=False) + ), + overflow=overflow, + overflow_box=boxes[-1] if overflow else None, + ) + + +def plan_chart(chart_cells: tuple[Cell, ...], theme: Theme) -> Plan: + """Lay out the nine cells as one picture.""" + step = theme.cell_size + theme.gap + side = 2 * theme.margin + 3 * theme.cell_size + 2 * theme.gap + + def box(cell: Cell) -> Box: + row, column = grid_position(cell.alignment) + return Box( + theme.margin + column * step, + theme.margin + row * step, + theme.cell_size, + theme.cell_size, + ) + + return Plan( + side, + side, + tuple(plan_cell(c, box(c), theme) for c in chart_cells), + ) + + +_PIXEL_FIELDS = ( + "gap", + "margin", + "padding", + "corner_radius", + "avatar_gap", + "max_avatar", + "min_avatar", + "min_named_avatar", +) + + +def scaled(theme: Theme, factor: float) -> Theme: + """Return ``theme`` with every pixel size multiplied by ``factor``.""" + return replace( + theme, + **{ + name: round(getattr(theme, name) * factor) + for name in _PIXEL_FIELDS + }, + ) + + +def plan_tile(cell: Cell, theme: Theme) -> Plan: + """Lay out one cell as a square picture of its own. + + Everything is scaled from ``theme.cell_size`` up to + ``theme.tile_size``, so a tile looks like a big chart cell. + """ + size = theme.tile_size + big = scaled(theme, size / theme.cell_size) + return Plan(size, size, (plan_cell(cell, Box(0, 0, size, size), big),)) diff --git a/doge_alignment/core/render.py b/doge_alignment/core/render.py new file mode 100644 index 0000000..d0b90b2 --- /dev/null +++ b/doge_alignment/core/render.py @@ -0,0 +1,238 @@ +"""Paint layout plans with ImageMagick (through Wand). + +This is the imperative shell around :mod:`.layout`: Wand images are mutable, +so each function here builds its own images and returns PNG bytes, and no +image escapes it. Rendering is CPU-bound; async front ends should run it in a +thread. + +Avatars are passed in as bytes keyed by user id. Only PNG, JPEG, GIF and WebP +are decoded, and always with an explicit decoder, so untrusted bytes never +reach ImageMagick's other coders. +""" + +from collections.abc import Mapping +from dataclasses import replace +from pathlib import Path + +from wand.color import Color +from wand.drawing import Drawing +from wand.image import Image + +from .images import sniff +from .layout import Box, CellPlan, Plan, Slot, Theme, plan_chart, plan_tile +from .view import Cell + +_FONT_CANDIDATES = ( + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf", + "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", +) + + +def find_font(theme: Theme) -> str | None: + """Return the theme's font, or the first bold DejaVu Sans found.""" + if theme.font: + return theme.font + return next((p for p in _FONT_CANDIDATES if Path(p).is_file()), None) + + +def _text( + canvas: Image, + box: Box, + text: str, + size: int, + theme: Theme, +) -> None: + if not text or size <= 0: + return + with Drawing() as draw: + font = find_font(theme) + if font: + draw.font = font + draw.font_size = size + draw.fill_color = Color(theme.text_color) + draw.text_alignment = "center" + baseline = box.y + (box.h + size * 0.7) / 2 + draw.text(int(box.x + box.w / 2), int(baseline), text) + draw(canvas) + + +def _decode(data: bytes | None) -> Image | None: + fmt = sniff(data) if data else None + if data is None or fmt is None: + return None + try: + with Image(blob=data, format=fmt) as loaded: + return Image(image=loaded.sequence[0]) + except Exception: # noqa: BLE001 (ImageMagick raises many types) + return None + + +def _square(img: Image, size: int) -> None: + side = min(img.width, img.height) + img.crop( + left=(img.width - side) // 2, + top=(img.height - side) // 2, + width=side, + height=side, + ) + img.resize(size, size) + + +def _disc_mask(size: int) -> Image: + mask = Image(width=size, height=size, background=Color("transparent")) + with Drawing() as draw: + draw.fill_color = Color("white") + mid = (size - 1) / 2 + draw.circle((mid, mid), (mid, 0)) + draw(mask) + return mask + + +def _placeholder(size: int, text: str, theme: Theme) -> Image: + img = Image( + width=size, + height=size, + background=Color(theme.placeholder_color), + ) + _text(img, Box(0, 0, size, size), text, size // 2, theme) + return img + + +def avatar_disc( + data: bytes | None, + size: int, + *, + present: bool, + fallback_text: str, + theme: Theme, +) -> Image: + """Return ``data`` as a round avatar of ``size`` with a ring. + + Undecodable or missing avatars become ``fallback_text`` on a plain + disc. People who have left are greyed out with a dim ring. The + caller owns (and closes) the returned image. + """ + ring = max(2, round(size * theme.ring_ratio)) + inner = size - 2 * ring + face = _decode(data) or _placeholder(inner, fallback_text, theme) + with face: + _square(face, inner) + if not present: + face.modulate(brightness=60, saturation=0) + face.alpha_channel = "activate" + with _disc_mask(inner) as mask: + face.composite_channel( + "alpha", mask, "copy_alpha", 0, 0 + ) + disc = Image( + width=size, height=size, background=Color("transparent") + ) + with Drawing() as draw: + draw.fill_color = Color( + theme.ring_color + if present + else theme.absent_ring_color + ) + mid = (size - 1) / 2 + draw.circle((mid, mid), (mid, 0)) + draw(disc) + disc.composite(face, left=ring, top=ring) + return disc + + +def _initial(name: str) -> str: + return name.strip()[:1].upper() or "?" + + +def _paint_slot( + canvas: Image, + slot: Slot, + avatars: Mapping[str, bytes], + theme: Theme, +) -> None: + person = slot.person + with avatar_disc( + avatars.get(person.user_id), + slot.avatar.w, + present=person.present, + fallback_text=_initial(person.name), + theme=theme, + ) as disc: + canvas.composite(disc, left=slot.avatar.x, top=slot.avatar.y) + if slot.name_box is not None: + _text(canvas, slot.name_box, slot.name, slot.font_size, theme) + + +def _paint_cell( + canvas: Image, + cell: CellPlan, + avatars: Mapping[str, bytes], + theme: Theme, +) -> None: + box = cell.box + with Drawing() as draw: + draw.fill_color = Color(theme.cell_colors[cell.alignment]) + corners = ( + {"radius": theme.corner_radius} + if theme.corner_radius + else {} + ) + # Wand draws nothing for radius=0, so leave it out + draw.rectangle( + left=box.x, + top=box.y, + width=box.w - 1, + height=box.h - 1, + **corners, + ) + draw(canvas) + _text(canvas, cell.label_box, cell.alignment, cell.label_size, theme) + for slot in cell.slots: + _paint_slot(canvas, slot, avatars, theme) + if cell.overflow_box is not None: + ob = cell.overflow_box + with avatar_disc( + None, + ob.w, + present=True, + fallback_text=f"+{cell.overflow}", + theme=replace(theme, placeholder_color="#202225"), + ) as disc: + canvas.composite(disc, left=ob.x, top=ob.y) + + +def paint(plan: Plan, avatars: Mapping[str, bytes], theme: Theme) -> bytes: + """Return ``plan`` painted as PNG bytes.""" + with Image( + width=plan.width, + height=plan.height, + background=Color(theme.background), + ) as canvas: + for cell in plan.cells: + _paint_cell(canvas, cell, avatars, theme) + canvas.format = "png" + return bytes(canvas.make_blob()) + + +def render_chart( + chart_cells: tuple[Cell, ...], + avatars: Mapping[str, bytes], + theme: Theme | None = None, +) -> bytes: + """Return the whole 3x3 chart as one PNG.""" + theme = theme or Theme() + return paint(plan_chart(chart_cells, theme), avatars, theme) + + +def render_tiles( + chart_cells: tuple[Cell, ...], + avatars: Mapping[str, bytes], + theme: Theme | None = None, +) -> tuple[bytes, ...]: + """Return each cell as its own square PNG, in chart order.""" + square = replace(theme or Theme(), corner_radius=0) + return tuple( + paint(plan_tile(cell, square), avatars, square) + for cell in chart_cells + ) diff --git a/doge_alignment/core/storage.py b/doge_alignment/core/storage.py new file mode 100644 index 0000000..83d472b --- /dev/null +++ b/doge_alignment/core/storage.py @@ -0,0 +1,119 @@ +"""Charts as plain data (for Red's Config or JSON) and as YAML files. + +The YAML format is the one the cog saved before it moved to Config:: + + users: + '111222333': + alignment: Chaotic Good + display_name: EpicUser + avatar_url: https://cdn.discordapp.com/avatars/... + admins: ['444555666'] +""" + +from collections.abc import Mapping +from typing import Any + +import yaml + +from .alignments import parse_alignment +from .chart import Chart, Entry, make_chart + +Data = dict[str, Any] + + +class ChartFormatError(ValueError): + """A YAML chart that can't be read.""" + + +def entry_to_data(entry: Entry) -> Data: + """Return ``entry`` as a plain dict.""" + return { + "alignment": entry.alignment, + "display_name": entry.display_name, + "avatar_url": entry.avatar_url, + } + + +def to_data(chart: Chart) -> Data: + """Return ``chart`` as plain dicts and lists.""" + return { + "users": { + uid: entry_to_data(entry) + for uid, entry in chart.users.items() + }, + "admins": list(chart.admins), + } + + +def entry_from_data(user_id: str, data: object) -> Entry | None: + """Return the entry in ``data``, or None if it isn't one.""" + if not isinstance(data, Mapping): + return None + alignment = parse_alignment(str(data.get("alignment", ""))) + if alignment is None: + return None + name = data.get("display_name") + url = data.get("avatar_url") + return Entry( + alignment=alignment, + display_name=str(name) if name else user_id, + avatar_url=str(url) if url else None, + ) + + +def _mapping(data: object, key: str) -> Mapping[object, object]: + value = data.get(key) if isinstance(data, Mapping) else None + return value if isinstance(value, Mapping) else {} + + +def _list(data: object, key: str) -> list[object]: + value = data.get(key) if isinstance(data, Mapping) else None + return list(value) if isinstance(value, list | tuple) else [] + + +def from_data(data: object) -> Chart: + """Return the chart in ``data``, skipping anything malformed.""" + entries = { + str(uid): entry_from_data(str(uid), raw) + for uid, raw in _mapping(data, "users").items() + } + return make_chart( + {uid: e for uid, e in entries.items() if e is not None}, + (str(a) for a in _list(data, "admins")), + ) + + +def to_yaml(chart: Chart) -> str: + """Return ``chart`` as YAML.""" + return yaml.safe_dump( + to_data(chart), sort_keys=False, allow_unicode=True + ) + + +def from_yaml(text: str) -> Chart: + """Read a YAML chart, strictly. + + Raises: + ChartFormatError: for invalid YAML, a missing ``users`` + mapping, or any entry without a valid alignment. + + """ + try: + data = yaml.safe_load(text) + except yaml.YAMLError as error: + msg = f"not valid YAML: {error}" + raise ChartFormatError(msg) from error + if not isinstance(data, Mapping) or not isinstance( + data.get("users"), Mapping + ): + msg = "expected a mapping with a 'users' mapping in it" + raise ChartFormatError(msg) + bad = sorted( + str(uid) + for uid, raw in data["users"].items() + if entry_from_data(str(uid), raw) is None + ) + if bad: + msg = f"no valid alignment for user(s) {', '.join(bad)}" + raise ChartFormatError(msg) + return from_data(data) diff --git a/doge_alignment/core/view.py b/doge_alignment/core/view.py new file mode 100644 index 0000000..501976f --- /dev/null +++ b/doge_alignment/core/view.py @@ -0,0 +1,116 @@ +"""What to show: the chart's nine cells, with live names where known.""" + +from collections.abc import Callable +from dataclasses import dataclass + +from .alignments import ALIGNMENTS, AlignmentName, abbreviation +from .chart import Chart, Entry + + +@dataclass(frozen=True) +class Profile: + """A person's current name and avatar, from the front end.""" + + name: str + avatar_url: str | None = None + + +# Live profile for a user id, or None if they aren't around any more +Lookup = Callable[[str], Profile | None] + + +@dataclass(frozen=True) +class Person: + """Someone to draw in a cell.""" + + user_id: str + name: str + avatar_url: str | None + present: bool = True + + +@dataclass(frozen=True) +class Cell: + """One square of the chart and the people in it, sorted by name.""" + + alignment: AlignmentName + people: tuple[Person, ...] = () + + +def person(user_id: str, entry: Entry, lookup: Lookup | None) -> Person: + """Return how to show ``user_id``. + + With no ``lookup`` (say, a chart read from a file) everyone counts as + present. Otherwise people the lookup doesn't know have left, and are + shown with the name and avatar saved when they were placed. + """ + live = ( + lookup(user_id) + if lookup + else Profile(entry.display_name, entry.avatar_url) + ) + if live is None: + return Person( + user_id, + entry.display_name, + entry.avatar_url, + present=False, + ) + return Person(user_id, live.name, live.avatar_url) + + +def _sort_key(p: Person) -> tuple[bool, str, str]: + return (not p.present, p.name.casefold(), p.user_id) + + +def _sorted_in( + people: tuple[tuple[AlignmentName, Person], ...], + alignment: AlignmentName, +) -> tuple[Person, ...]: + return tuple( + sorted( + (p for a, p in people if a == alignment), + key=_sort_key, + ) + ) + + +def cells(chart: Chart, lookup: Lookup | None = None) -> tuple[Cell, ...]: + """Return all nine cells in chart order, empty ones included.""" + people = tuple( + (entry.alignment, person(uid, entry, lookup)) + for uid, entry in chart.users.items() + ) + return tuple( + Cell(alignment, _sorted_in(people, alignment)) + for alignment in ALIGNMENTS + ) + + +def absent(chart: Chart, lookup: Lookup) -> tuple[str, ...]: + """Return the ids on ``chart`` that ``lookup`` doesn't know.""" + return tuple(uid for uid in chart.users if lookup(uid) is None) + + +def everyone(chart_cells: tuple[Cell, ...]) -> tuple[Person, ...]: + """Return every person in ``chart_cells``.""" + return tuple(p for cell in chart_cells for p in cell.people) + + +def _label(p: Person) -> str: + return p.name if p.present else f"~~{p.name}~~ (left)" + + +def format_text(chart_cells: tuple[Cell, ...]) -> str: + """Return the chart as Markdown lines, leaving out empty cells.""" + return "\n".join( + f"**{cell.alignment}**: " + + ", ".join(_label(p) for p in cell.people) + for cell in chart_cells + if cell.people + ) + + +def tile_filename(index: int, cell: Cell) -> str: + """Return a file name for a cell's own picture, like ``1-lg.png``.""" + return f"{index}-{abbreviation(cell.alignment).lower()}.png" diff --git a/doge_alignment/doge_alignment.py b/doge_alignment/doge_alignment.py deleted file mode 100644 index 9e524f8..0000000 --- a/doge_alignment/doge_alignment.py +++ /dev/null @@ -1,241 +0,0 @@ -"""Slash commands for a server's alignment chart.""" - -from typing import Literal - -import discord -from redbot.core import Config, app_commands, commands -from redbot.core.bot import Red - -from .chart import ( - ALIGNMENTS, - AlignmentChart, - add_admin, - as_alignment, - forget_user, - format_chart, - may_manage_admins, - may_set, - normalize_chart, - remove_admin, - remove_user_alignment, - set_user_alignment, -) - -RequestType = Literal["discord_deleted_user", "owner", "user", "user_strict"] - -ALIGNMENT_CHOICES = [app_commands.Choice(name=a, value=a) for a in ALIGNMENTS] - - -async def _reply(interaction: discord.Interaction, text: str) -> None: - await interaction.response.send_message(text, ephemeral=True) - - -class AlignmentCog(commands.Cog): - """Keep track of everyone's D&D alignment.""" - - def __init__(self, bot: Red) -> None: - """Create the cog.""" - self.bot = bot - self.config = Config.get_conf( - self, identifier=0xA119E5C4A7, force_registration=True - ) - self.config.register_guild(users={}, admins=[]) - - async def red_delete_data_for_user( - self, *, requester: RequestType, user_id: int - ) -> None: - """Take a user off every chart and every admin list.""" - del requester - for guild_id in await self.config.all_guilds(): - group = self.config.guild_from_id(guild_id) - chart = normalize_chart(await group.all()) - await group.set(forget_user(chart, str(user_id))) - - async def _chart(self, guild: discord.Guild) -> AlignmentChart: - return normalize_chart(await self.config.guild(guild).all()) - - async def _save( - self, guild: discord.Guild, chart: AlignmentChart - ) -> None: - await self.config.guild(guild).set(chart) - - async def _is_bot_owner( - self, user: discord.User | discord.Member - ) -> bool: - return await self.bot.is_owner(user) - - @app_commands.command( - name="alignment_show", - description="Show this server's alignment chart.", - ) - @app_commands.guild_only() - async def alignment_show( - self, interaction: discord.Interaction - ) -> None: - """Show the chart as text.""" - if interaction.guild is None: - return - chart = await self._chart(interaction.guild) - if not chart["users"]: - await _reply(interaction, "No alignments set yet.") - return - await _reply(interaction, format_chart(chart)) - - @app_commands.command( - name="alignment_set", description="Set your alignment." - ) - @app_commands.guild_only() - @app_commands.describe(alignment="Your D&D alignment.") - @app_commands.choices(alignment=ALIGNMENT_CHOICES) - async def alignment_set( - self, - interaction: discord.Interaction, - alignment: app_commands.Choice[str], - ) -> None: - """Put yourself on the chart.""" - await self._set(interaction, alignment.value, None) - - @app_commands.command( - name="alignment_set_other", - description="Set someone's alignment (admins can move anyone).", - ) - @app_commands.guild_only() - @app_commands.describe( - target="Whose alignment to set (blank for your own)", - alignment="The alignment to set", - ) - @app_commands.choices(alignment=ALIGNMENT_CHOICES) - async def alignment_set_other( - self, - interaction: discord.Interaction, - alignment: app_commands.Choice[str], - target: discord.Member | None = None, - ) -> None: - """Place someone on the chart.""" - await self._set(interaction, alignment.value, target) - - async def _set( - self, - interaction: discord.Interaction, - value: str, - target: discord.Member | None, - ) -> None: - guild = interaction.guild - if guild is None: - return - member = target or interaction.user - invoker_id = str(interaction.user.id) - target_id = str(member.id) - chart = await self._chart(guild) - privileged = await self._is_bot_owner(interaction.user) - if not may_set( - chart, invoker_id, target_id, privileged=privileged - ): - await _reply( - interaction, - f"{member.display_name} already has an " - "alignment; only alignment admins can change " - "it.", - ) - return - alignment = as_alignment(value) - await self._save( - guild, - set_user_alignment( - chart, - user_id=target_id, - alignment=alignment, - display_name=member.display_name, - avatar_url=member.display_avatar.url, - ), - ) - who = ( - "Your alignment" - if target_id == invoker_id - else f"Alignment for **{member.display_name}**" - ) - await _reply(interaction, f"{who} set to **{alignment}**.") - - @app_commands.command( - name="alignment_remove", - description="Take yourself off the alignment chart.", - ) - @app_commands.guild_only() - async def alignment_remove( - self, interaction: discord.Interaction - ) -> None: - """Remove your own alignment.""" - if interaction.guild is None: - return - chart = await self._chart(interaction.guild) - await self._save( - interaction.guild, - remove_user_alignment(chart, str(interaction.user.id)), - ) - await _reply(interaction, "Your alignment has been removed.") - - async def _may_manage_admins( - self, interaction: discord.Interaction, chart: AlignmentChart - ) -> bool: - guild = interaction.guild - privileged = ( - guild is not None - and interaction.user.id == guild.owner_id - ) or await self._is_bot_owner(interaction.user) - return may_manage_admins( - chart, str(interaction.user.id), privileged=privileged - ) - - @app_commands.command( - name="alignment_add_admin", - description="Let someone move anyone on the alignment chart.", - ) - @app_commands.guild_only() - async def alignment_add_admin( - self, interaction: discord.Interaction, user: discord.Member - ) -> None: - """Make ``user`` an alignment admin.""" - if interaction.guild is None: - return - chart = await self._chart(interaction.guild) - if not await self._may_manage_admins(interaction, chart): - await _reply( - interaction, - "Only the server owner and alignment admins " - "can change admins.", - ) - return - await self._save( - interaction.guild, add_admin(chart, str(user.id)) - ) - await _reply( - interaction, - f"{user.display_name} is now an alignment admin.", - ) - - @app_commands.command( - name="alignment_remove_admin", - description="Remove someone from the alignment admins.", - ) - @app_commands.guild_only() - async def alignment_remove_admin( - self, interaction: discord.Interaction, user: discord.Member - ) -> None: - """Stop ``user`` being an alignment admin.""" - if interaction.guild is None: - return - chart = await self._chart(interaction.guild) - if not await self._may_manage_admins(interaction, chart): - await _reply( - interaction, - "Only the server owner and alignment admins " - "can change admins.", - ) - return - await self._save( - interaction.guild, remove_admin(chart, str(user.id)) - ) - await _reply( - interaction, - f"{user.display_name} is no longer an alignment admin.", - ) diff --git a/doge_alignment/info.json b/doge_alignment/info.json index 49d0a85..7f27aa6 100644 --- a/doge_alignment/info.json +++ b/doge_alignment/info.json @@ -6,15 +6,18 @@ ], "install_msg": "YES FUCK YEAH WE INSTALLED THIS SHIT.", "name": "doge_alignment", - "short": "D&D alignment chart for your server", - "requirements": [], - "description": "Slash commands to put yourself (and others) on a server's 3x3 D&D alignment chart, with alignment admins who can move anyone.", + "short": "D&D alignment chart for your server, drawn with members' avatars", + "requirements": [ + "Wand>=0.6.13" + ], + "description": "A 3x3 D&D alignment chart per server, drawn as one picture or as a gallery of nine, with members' avatars. Slash and text commands (`alignment`), alignment admins, YAML export and import. Needs ImageMagick (libmagickwand) on the bot's host for pictures; without it the chart is shown as text.", "tags": [ "fun", "alignment", - "dnd" + "dnd", + "image" ], - "end_user_data_statement": "This cog stores your alignment, display name and avatar URL for each server's chart, and whether you are an alignment admin there. /alignment_remove takes you off a chart; Red's data deletion removes you everywhere.", + "end_user_data_statement": "This cog stores your alignment, display name and avatar URL for each server's chart, and whether you are an alignment admin there. `alignment remove` takes you off a chart; Red's data deletion removes you everywhere.", "min_bot_version": "3.5.0", "min_python_version": [ 3, diff --git a/doge_alignment/render.py b/doge_alignment/render.py deleted file mode 100644 index fcbc207..0000000 --- a/doge_alignment/render.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Building blocks for drawing the chart as an image (not wired up yet). - -Uses Wand (ImageMagick). The cog doesn't import this module, so it loads on -hosts without ImageMagick, such as dogebot's Red container. Drawing the chart -is on the TODO list in the repo. -""" - -from typing import Literal - -from wand.color import Color -from wand.drawing import Drawing -from wand.image import Image - -BorderShape = Literal["square", "circle", "rounded"] - - -def solid_color_background( - width: int = 512, - height: int = 512, - color: str = "black", -) -> Image: - """Return a solid colour image.""" - return Image(width=width, height=height, background=Color(color)) - - -def grid_positions( - count: int, - cell_size: tuple[int, int], - gap: int, - columns: int = 3, -) -> list[tuple[int, int]]: - """Return the top-left corner of ``count`` cells in a grid. - - Cells fill left to right, then top to bottom, ``gap`` pixels apart. - """ - width, height = cell_size - return [ - ((i % columns) * (width + gap), (i // columns) * (height + gap)) - for i in range(count) - ] - - -def _mask(size: tuple[int, int], shape: BorderShape) -> Image: - mask_img = Image( - width=size[0], height=size[1], background=Color("transparent") - ) - with Drawing() as mask: - mask.fill_color = Color("white") - if shape == "circle": - mask.circle( - (size[0] // 2, size[1] // 2), - (size[0] // 2, 0), - ) - else: - radius = min(size) // 8 - mask.rectangle( - left=0, - top=0, - width=size[0] - 1, - height=size[1] - 1, - radius=radius, - ) - mask.draw(mask_img) - return mask_img - - -def process_avatar( - img: Image, - size: tuple[int, int], - border: int, - border_color: str, - shape: BorderShape, -) -> Image: - """Return a resized copy of ``img``, cut to ``shape`` and bordered.""" - out = img.clone() - out.resize(size[0], size[1]) - if shape != "square": - out.alpha_channel = "activate" - with _mask(size, shape) as mask_img: - out.composite_channel( - "alpha", mask_img, "copy_alpha", 0, 0 - ) - if border > 0: - out.border(Color(border_color), border, border) - return out diff --git a/doge_alignment/ui.py b/doge_alignment/ui.py new file mode 100644 index 0000000..5512c3c --- /dev/null +++ b/doge_alignment/ui.py @@ -0,0 +1,79 @@ +"""Discord views: the tile gallery and a confirm prompt.""" + +import discord + +from .core.view import Cell, tile_filename + + +def gallery_view( + title: str, chart_cells: tuple[Cell, ...] +) -> discord.ui.LayoutView: + """Return a message layout showing the nine tiles as a 3x3 gallery. + + Discord lays out a nine-item media gallery as three rows of three. The + tiles are attached under :func:`tile_filename` names. + """ + view = discord.ui.LayoutView(timeout=None) + view.add_item(discord.ui.TextDisplay(f"### {title}")) + view.add_item( + discord.ui.MediaGallery( + *( + discord.MediaGalleryItem( + f"attachment://{tile_filename(i, c)}", + description=c.alignment, + ) + for i, c in enumerate(chart_cells, start=1) + ) + ) + ) + return view + + +class ConfirmView(discord.ui.View): + """Yes/no buttons that only ``author_id`` can press.""" + + def __init__(self, author_id: int, confirm_label: str) -> None: + """Create the prompt.""" + super().__init__(timeout=60) + self.author_id = author_id + self.confirmed: bool | None = None + self.confirm.label = confirm_label + + async def interaction_check( + self, interaction: discord.Interaction + ) -> bool: + """Only the person who asked may answer.""" + if interaction.user.id == self.author_id: + return True + await interaction.response.send_message( + "This isn't your prompt.", ephemeral=True + ) + return False + + async def _answer( + self, interaction: discord.Interaction, *, confirmed: bool + ) -> None: + self.confirmed = confirmed + for item in self.children: + if isinstance(item, discord.ui.Button): + item.disabled = True + await interaction.response.edit_message(view=self) + self.stop() + + @discord.ui.button(label="Confirm", style=discord.ButtonStyle.danger) + async def confirm( + self, + interaction: discord.Interaction, + _button: discord.ui.Button["ConfirmView"], + ) -> None: + """Go ahead.""" + await self._answer(interaction, confirmed=True) + + @discord.ui.button(label="Cancel", style=discord.ButtonStyle.secondary) + async def cancel( + self, + interaction: discord.Interaction, + _button: discord.ui.Button["ConfirmView"], + ) -> None: + """Don't.""" + await self._answer(interaction, confirmed=False) diff --git a/pyproject.toml b/pyproject.toml index 4b0d786..1a3da17 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ requires-python = ">=3.11" dependencies = [ # The Red that dogebot runs; cogs get discord.py, PyYAML etc. from it "red-discordbot==3.5.24", - # doge_alignment/render.py (chart image, not wired up yet; needs ImageMagick) + # doge_alignment pictures (needs ImageMagick's libmagickwand) "wand>=0.6.13", ] diff --git a/tests/alignment_helpers.py b/tests/alignment_helpers.py new file mode 100644 index 0000000..53d859a --- /dev/null +++ b/tests/alignment_helpers.py @@ -0,0 +1,24 @@ +"""Shared builders for the alignment tests.""" + +from doge_alignment.core.alignments import AlignmentName +from doge_alignment.core.chart import ( + Chart, + Entry, + add_admin, + empty_chart, + place, +) + + +def chart_with( + *users: tuple[str, AlignmentName], admins: tuple[str, ...] = () +) -> Chart: + """Return a chart with ``(user id, alignment)`` pairs on it.""" + chart = empty_chart() + for user_id, alignment in users: + chart = place( + chart, user_id, Entry(alignment, f"user{user_id}") + ) + for admin in admins: + chart = add_admin(chart, admin) + return chart diff --git a/tests/test_alignment_alignments.py b/tests/test_alignment_alignments.py new file mode 100644 index 0000000..29d3e86 --- /dev/null +++ b/tests/test_alignment_alignments.py @@ -0,0 +1,74 @@ +"""The nine alignments and how people type them.""" + +import pytest + +from doge_alignment.core.alignments import ( + ALIGNMENTS, + abbreviation, + as_alignment, + grid_position, + matching, + parse_alignment, +) + + +def test_nine_alignments_in_chart_order() -> None: + """The classic 3x3: good row first, lawful column first.""" + assert len(ALIGNMENTS) == 9 + assert ALIGNMENTS[0] == "Lawful Good" + assert ALIGNMENTS[4] == "True Neutral" + assert ALIGNMENTS[-1] == "Chaotic Evil" + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("Lawful Good", "Lawful Good"), + ("chaotic-good", "Chaotic Good"), + (" CHAOTIC_neutral ", "Chaotic Neutral"), + ("ce", "Chaotic Evil"), + ("LN", "Lawful Neutral"), + ("tn", "True Neutral"), + ("neutral", "True Neutral"), + ("NN", "True Neutral"), + ("n", "True Neutral"), + ("ne", "Neutral Evil"), + ], +) +def test_parse_alignment_accepts_common_spellings( + text: str, expected: str +) -> None: + """Full names in any case or spacing, and abbreviations.""" + assert parse_alignment(text) == expected + + +@pytest.mark.parametrize("text", ["", "chaotic", "good", "xx", "lawful bad"]) +def test_parse_alignment_rejects_others(text: str) -> None: + """Half an alignment isn't one.""" + assert parse_alignment(text) is None + + +def test_as_alignment_is_strict() -> None: + """as_alignment only takes the exact names.""" + assert as_alignment("Neutral Good") == "Neutral Good" + with pytest.raises(ValueError, match="not an alignment"): + as_alignment("ng") + + +def test_grid_position_and_abbreviation() -> None: + """Rows are good/neutral/evil, columns lawful/neutral/chaotic.""" + assert grid_position("Lawful Good") == (0, 0) + assert grid_position("Chaotic Neutral") == (1, 2) + assert grid_position("Neutral Evil") == (2, 1) + assert [abbreviation(a) for a in ALIGNMENTS[:3]] == ["LG", "NG", "CG"] + + +def test_matching_for_autocomplete() -> None: + """Prefixes narrow the list; abbreviations find their alignment.""" + assert matching("") == ALIGNMENTS + assert matching("chaotic") == ( + "Chaotic Good", + "Chaotic Neutral", + "Chaotic Evil", + ) + assert matching("cg") == ("Chaotic Good",) diff --git a/tests/test_alignment_chart.py b/tests/test_alignment_chart.py index 9c6c7dc..cf7c1e5 100644 --- a/tests/test_alignment_chart.py +++ b/tests/test_alignment_chart.py @@ -1,150 +1,112 @@ -"""The alignment chart's rules, as pure functions.""" +"""The chart's rules: immutable updates and permissions.""" + +import dataclasses import pytest +from alignment_helpers import chart_with -from doge_alignment.chart import ( - ALIGNMENTS, - AlignmentChart, +from doge_alignment.core.chart import ( + Entry, add_admin, - as_alignment, + clear, empty_chart, forget_user, - format_chart, - may_manage_admins, + make_chart, + may_manage, + may_remove, may_set, - normalize_chart, + place, remove_admin, - remove_user_alignment, - set_user_alignment, + replace_users, + unplace, + unplace_all, ) -def chart_with( - *users: tuple[str, str], admins: tuple[str, ...] = () -) -> AlignmentChart: - """Return a chart with ``(user id, alignment)`` pairs on it.""" - chart = empty_chart() - for user_id, alignment in users: - chart = set_user_alignment( - chart, - user_id, - as_alignment(alignment), - f"user{user_id}", - ) - for admin in admins: - chart = add_admin(chart, admin) - return chart +def test_place_returns_new_chart_and_keeps_admins() -> None: + """Placing someone neither mutates nor drops the admin list.""" + before = chart_with(("1", "Lawful Good"), admins=("9",)) + after = place(before, "2", Entry("Chaotic Evil", "two")) + assert set(before.users) == {"1"} + assert set(after.users) == {"1", "2"} + assert after.admins == ("9",) -def test_nine_alignments_in_chart_order() -> None: - """The chart is the classic 3x3, good row first.""" - assert len(ALIGNMENTS) == 9 - assert ALIGNMENTS[0] == "Lawful Good" - assert ALIGNMENTS[4] == "True Neutral" - assert ALIGNMENTS[-1] == "Chaotic Evil" +def test_charts_are_immutable() -> None: + """Neither the chart nor its user mapping can be changed in place.""" + chart = chart_with(("1", "Lawful Good")) + with pytest.raises(dataclasses.FrozenInstanceError): + chart.admins = ("x",) # ty: ignore[invalid-assignment] + with pytest.raises(TypeError): + chart.users["2"] = Entry("True Neutral", "x") # ty: ignore[invalid-assignment] -def test_set_keeps_admins_and_original() -> None: - """Regression: setting an alignment used to drop the admin list.""" - chart = chart_with(admins=("1",)) - updated = set_user_alignment(chart, "2", "Lawful Good", "Tester") - assert updated["admins"] == ["1"] - assert updated["users"]["2"]["alignment"] == "Lawful Good" - assert chart["users"] == {} - - -def test_remove_keeps_admins_and_original() -> None: - """Regression: removing an alignment used to drop the admin list.""" - chart = chart_with(("2", "Chaotic Evil"), admins=("1",)) - updated = remove_user_alignment(chart, "2") - assert updated == {"users": {}, "admins": ["1"]} - assert "2" in chart["users"] - - -def test_admins_are_unique_and_removable() -> None: - """Adding twice keeps one entry; removing a non-admin is harmless.""" - chart = add_admin(add_admin(empty_chart(), "1"), "1") - assert chart["admins"] == ["1"] - assert remove_admin(chart, "1")["admins"] == [] - assert remove_admin(chart, "9")["admins"] == ["1"] - - -def test_forget_user_removes_everything() -> None: - """Data deletion takes the user off the chart and the admin list.""" +def test_unplace_keeps_admins_and_others() -> None: + """Removing one person leaves everyone and everything else.""" chart = chart_with( - ("1", "True Neutral"), ("2", "Lawful Good"), admins=("1",) + ("1", "Lawful Good"), ("2", "True Neutral"), admins=("1",) ) - assert forget_user(chart, "1") == { - "users": {"2": chart["users"]["2"]}, - "admins": [], - } + after = unplace(chart, "1") + assert set(after.users) == {"2"} + assert after.admins == ("1",) + assert unplace(after, "404") == after -@pytest.mark.parametrize( - ("invoker", "target", "privileged", "allowed"), - [ - ("1", "1", False, True), # yourself, even if already set - ("1", "3", False, True), # someone not on the chart yet - ("1", "2", False, False), # someone already on it - ("9", "2", False, True), # ...unless you're an alignment admin - ("1", "2", True, True), # ...or the bot owner - ], -) -def test_may_set( - invoker: str, target: str, *, privileged: bool, allowed: bool -) -> None: - """Only admins can move people who are already on the chart.""" +def test_unplace_all_and_clear() -> None: + """Bulk removal, and clearing, keep the admins.""" chart = chart_with( - ("1", "Lawful Good"), ("2", "Chaotic Evil"), admins=("9",) - ) - assert may_set(chart, invoker, target, privileged=privileged) is allowed - - -def test_may_manage_admins() -> None: - """Admins and privileged users manage admins; nobody else.""" - chart = chart_with(admins=("9",)) - assert may_manage_admins(chart, "9", privileged=False) - assert may_manage_admins(chart, "1", privileged=True) - assert not may_manage_admins(chart, "1", privileged=False) - - -def test_format_chart_in_chart_order() -> None: - """Rows follow the chart, names are sorted, empty cells are skipped.""" - chart = chart_with( - ("2", "Chaotic Evil"), ("1", "Lawful Good"), - ("3", "Lawful Good"), + ("2", "True Neutral"), + ("3", "Chaotic Evil"), + admins=("5",), ) - assert format_chart(chart) == ( - "**Lawful Good**: user1, user3\n**Chaotic Evil**: user2" - ) - with pytest.raises(ValueError, match="empty"): - format_chart(empty_chart()) + assert set(unplace_all(chart, ("1", "3")).users) == {"2"} + cleared = clear(chart) + assert not cleared.users + assert cleared.admins == ("5",) -def test_normalize_chart_repairs_stored_data() -> None: - """Missing keys, int ids and unknown alignments are cleaned up.""" - assert normalize_chart(None) == empty_chart() - assert normalize_chart({"users": None}) == empty_chart() - chart = normalize_chart( - { - "users": { - 1: { - "alignment": "Lawful Good", - "display_name": "a", - "avatar_url": None, - }, - 2: {"alignment": "Lawful Awesome"}, - }, - "admins": [5], - } - ) - assert list(chart["users"]) == ["1"] - assert chart["admins"] == ["5"] +def test_admins_are_unique_and_ordered() -> None: + """Adding an admin twice keeps one entry; removing is idempotent.""" + chart = add_admin(add_admin(add_admin(empty_chart(), "a"), "b"), "a") + assert chart.admins == ("a", "b") + assert remove_admin(remove_admin(chart, "a"), "a").admins == ("b",) + assert make_chart(admins=["x", "x", "y"]).admins == ("x", "y") -def test_as_alignment_rejects_others() -> None: - """Only the nine alignments are accepted.""" - assert as_alignment("True Neutral") == "True Neutral" - with pytest.raises(ValueError, match="not an alignment"): - as_alignment("Lawful Awesome") +def test_forget_user_removes_every_trace() -> None: + """Data deletion takes the user off the chart and the admin list.""" + chart = chart_with(("1", "Lawful Good"), ("2", "Lawful Evil")) + after = forget_user(add_admin(chart, "1"), "1") + assert set(after.users) == {"2"} + assert after.admins == () + + +def test_replace_users_keeps_own_admins() -> None: + """Importing a chart brings its people, not its admins.""" + ours = chart_with(("1", "Lawful Good"), admins=("a",)) + theirs = chart_with(("2", "Chaotic Good"), admins=("b",)) + merged = replace_users(ours, theirs) + assert set(merged.users) == {"2"} + assert merged.admins == ("a",) + + +def test_may_set_rules() -> None: + """Self and newcomers are free; moving others needs a manager.""" + chart = chart_with(("1", "Lawful Good"), admins=("9",)) + assert may_set(chart, "1", "1", privileged=False) + assert may_set(chart, "2", "3", privileged=False) + assert not may_set(chart, "2", "1", privileged=False) + assert may_set(chart, "9", "1", privileged=False) + assert may_set(chart, "2", "1", privileged=True) + + +def test_may_remove_and_manage() -> None: + """Anyone may leave; removing others and managing need privileges.""" + chart = chart_with(("1", "Lawful Good"), admins=("9",)) + assert may_remove(chart, "1", "1", privileged=False) + assert not may_remove(chart, "2", "1", privileged=False) + assert may_remove(chart, "9", "1", privileged=False) + assert may_manage(chart, "9", privileged=False) + assert not may_manage(chart, "2", privileged=False) + assert may_manage(chart, "2", privileged=True) diff --git a/tests/test_alignment_cli.py b/tests/test_alignment_cli.py new file mode 100644 index 0000000..aebef2f --- /dev/null +++ b/tests/test_alignment_cli.py @@ -0,0 +1,66 @@ +"""``python -m doge_alignment`` on an exported chart.""" + +from pathlib import Path + +import pytest +from alignment_helpers import chart_with + +from doge_alignment.cli import main +from doge_alignment.core.storage import to_yaml + + +@pytest.fixture +def chart_file(tmp_path: Path) -> Path: + """Write a small exported chart.""" + path = tmp_path / "chart.yaml" + path.write_text( + to_yaml(chart_with(("1", "Lawful Good"), ("2", "Chaotic Evil"))) + ) + return path + + +def test_text(chart_file: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Text mode prints the chart.""" + assert main(["text", str(chart_file)]) == 0 + assert capsys.readouterr().out.splitlines() == [ + "**Lawful Good**: user1", + "**Chaotic Evil**: user2", + ] + + +def test_bad_file_is_a_usage_error(tmp_path: Path) -> None: + """Unreadable charts exit with argparse's usage status.""" + bad = tmp_path / "bad.yaml" + bad.write_text("users: [") + with pytest.raises(SystemExit) as exit_info: + main(["text", str(bad)]) + assert exit_info.value.code == 2 + + +def test_image_and_tiles(chart_file: Path, tmp_path: Path) -> None: + """Image and tile modes write PNGs (needs ImageMagick).""" + pytest.importorskip("wand.image", reason="needs ImageMagick") + out = tmp_path / "chart.png" + assert ( + main(["image", str(chart_file), "-o", str(out), "--no-avatars"]) + == 0 + ) + assert out.read_bytes().startswith(b"\x89PNG") + tiles = tmp_path / "tiles" + assert ( + main( + [ + "tiles", + str(chart_file), + "-o", + str(tiles), + "--no-avatars", + ] + ) + == 0 + ) + assert sorted(p.name for p in tiles.iterdir())[:2] == [ + "1-lg.png", + "2-ng.png", + ] + assert len(list(tiles.iterdir())) == 9 diff --git a/tests/test_alignment_cog.py b/tests/test_alignment_cog.py index fe716a0..89a3668 100644 --- a/tests/test_alignment_cog.py +++ b/tests/test_alignment_cog.py @@ -1,13 +1,21 @@ -"""The cog stores charts in Red's Config and deletes user data.""" +"""The Discord glue: Config storage, data deletion, caching, views.""" +from collections import OrderedDict from collections.abc import Iterator +from types import SimpleNamespace +from typing import cast +import discord import pytest +from alignment_helpers import chart_with from redbot.core import Config from redbot.core.bot import Red -from doge_alignment.chart import add_admin, empty_chart, set_user_alignment -from doge_alignment.doge_alignment import AlignmentCog +from doge_alignment.cog import AlignmentCog, member_lookup, remember +from doge_alignment.core.chart import Entry, add_admin, place +from doge_alignment.core.storage import from_data, to_data +from doge_alignment.core.view import Profile, cells +from doge_alignment.ui import gallery_view @pytest.fixture @@ -15,41 +23,121 @@ def cog(red: Red, config: Config) -> Iterator[AlignmentCog]: """Return an AlignmentCog on Red's test Config backend.""" cog = AlignmentCog.__new__(AlignmentCog) cog.bot = red - config.register_guild(users={}, admins=[]) + config.register_guild(users={}, admins=[], default_style="image") cog.config = config + cog._locks = {} yield cog +async def test_update_saves_and_keeps_other_settings(cog: AlignmentCog) -> None: + """Updates write the chart without touching the style setting.""" + group = cog.config.guild_from_id(1) + await group.default_style.set("gallery") + chart = await cog._update_id( + 1, + lambda c: add_admin( + place(c, "5", Entry("Lawful Good", "e")), "5" + ), + ) + assert from_data(await group.all()) == chart + assert await group.default_style() == "gallery" + + async def test_delete_data_for_user_clears_every_guild( cog: AlignmentCog, ) -> None: """Red's data deletion removes the user from charts and admin lists.""" - chart = add_admin( - set_user_alignment( - set_user_alignment( - empty_chart(), "1", "Lawful Good", "a" - ), - "2", - "Chaotic Evil", - "b", - ), - "1", + chart = chart_with( + ("1", "Lawful Good"), ("2", "Chaotic Evil"), admins=("1",) ) for guild_id in (100, 200): - await cog.config.guild_from_id(guild_id).set(chart) + await cog._update_id(guild_id, lambda _c: chart) await cog.red_delete_data_for_user(requester="user", user_id=1) for guild_id in (100, 200): - stored = await cog.config.guild_from_id(guild_id).all() - assert list(stored["users"]) == ["2"] - assert stored["admins"] == [] + stored = from_data( + await cog.config.guild_from_id(guild_id).all() + ) + assert list(stored.users) == ["2"] + assert stored.admins == () -async def test_saved_chart_round_trips(cog: AlignmentCog) -> None: - """What the cog saves is what it reads back.""" - chart = add_admin( - set_user_alignment(empty_chart(), "7", "True Neutral", "n"), "7" +def test_saved_data_is_plain() -> None: + """Config gets plain dicts and lists, not dataclasses.""" + data = to_data(chart_with(("1", "True Neutral"), admins=("1",))) + assert data == { + "users": { + "1": { + "alignment": "True Neutral", + "display_name": "user1", + "avatar_url": None, + } + }, + "admins": ["1"], + } + + +def test_remember_is_an_lru() -> None: + """New and used URLs stay; the least recently used go first.""" + cache = OrderedDict([("a", b"1"), ("b", b"2")]) + after = remember(cache, {"c": b"3"}, frozenset({"a"}), limit=2) + assert list(after) == ["c", "a"] + assert list(cache) == ["a", "b"] + + +def test_member_lookup() -> None: + """Members give live profiles; strangers give None.""" + avatar = SimpleNamespace( + replace=lambda **_kw: SimpleNamespace(url="https://cdn/a.png") ) - await cog.config.guild_from_id(300).set(chart) - assert await cog.config.guild_from_id(300).all() == chart + member = SimpleNamespace(display_name="Alice", display_avatar=avatar) + guild = SimpleNamespace(get_member=lambda i: member if i == 1 else None) + lookup = member_lookup(cast("discord.Guild", guild)) + assert lookup("1") == Profile("Alice", "https://cdn/a.png") + assert lookup("2") is None + + +def test_gallery_view_has_nine_tiles() -> None: + """The gallery points at the nine attached tiles, in order.""" + view = gallery_view("Chart", cells(chart_with())) + gallery = next( + item + for item in view.children + if isinstance(item, discord.ui.MediaGallery) + ) + urls = [item.media.url for item in gallery.items] + assert len(urls) == 9 + assert urls[0] == "attachment://1-lg.png" + assert urls[8] == "attachment://9-ce.png" + + +async def test_slash_commands_are_valid(red: Red) -> None: + """discord.py builds the /alignment payload Discord would get.""" + cog = AlignmentCog(red) + tree = discord.app_commands.CommandTree( + discord.Client(intents=discord.Intents.none()) + ) + group = cog.alignment.app_command + assert group is not None + payload = group.to_dict(tree) + options = {o["name"]: o for o in payload["options"]} + assert set(options) == { + "show", + "set", + "remove", + "prune", + "clear", + "style", + "export", + "import", + "admin", + } + set_options = [o["name"] for o in options["set"]["options"]] + assert set_options == ["alignment", "member"] + assert options["set"]["options"][0]["autocomplete"] is True + styles = options["show"]["options"][0]["choices"] + assert [c["value"] for c in styles] == ["image", "gallery", "text"] + admin = [o["name"] for o in options["admin"]["options"]] + assert admin == ["add", "remove", "list"] + await cog.cog_unload() diff --git a/tests/test_alignment_fetch.py b/tests/test_alignment_fetch.py new file mode 100644 index 0000000..8bdb594 --- /dev/null +++ b/tests/test_alignment_fetch.py @@ -0,0 +1,93 @@ +"""Avatar downloads: limits, formats, and whole bodies.""" + +from collections.abc import AsyncIterator + +import aiohttp +import pytest +from aiohttp import web +from aiohttp.test_utils import BaseTestServer, TestServer + +from doge_alignment.core import fetch +from doge_alignment.core.view import Person + +PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 300_000 + + +async def _png(_request: web.Request) -> web.StreamResponse: + # Sent in pieces, so a single read() would come back short + response = web.StreamResponse() + await response.prepare(_request) + for i in range(0, len(PNG), 1000): + await response.write(PNG[i : i + 1000]) + return response + + +async def _svg(_request: web.Request) -> web.Response: + return web.Response(body=b"", content_type="image/svg+xml") + + +async def _missing(_request: web.Request) -> web.Response: + return web.Response(status=404) + + +@pytest.fixture +async def server() -> AsyncIterator[BaseTestServer]: + """Serve test images over plain HTTP.""" + app = web.Application() + app.router.add_get("/a.png", _png) + app.router.add_get("/a.svg", _svg) + app.router.add_get("/missing.png", _missing) + async with TestServer(app) as test_server: + yield test_server + + +async def test_fetch_reads_whole_body_and_checks_format( + server: BaseTestServer, monkeypatch: pytest.MonkeyPatch +) -> None: + """Chunked bodies arrive whole; non-images and errors are None.""" + monkeypatch.setattr(fetch, "_allowed", lambda _url: True) + async with aiohttp.ClientSession() as session: + images = await fetch.fetch_images( + session, + [ + str(server.make_url("/a.png")), + str(server.make_url("/a.svg")), + str(server.make_url("/missing.png")), + ], + ) + assert list(images.values()) == [PNG] + + +async def test_fetch_enforces_size_limit( + server: BaseTestServer, monkeypatch: pytest.MonkeyPatch +) -> None: + """Bodies over the limit are dropped.""" + monkeypatch.setattr(fetch, "_allowed", lambda _url: True) + monkeypatch.setattr(fetch, "MAX_AVATAR_BYTES", 1000) + async with aiohttp.ClientSession() as session: + url = str(server.make_url("/a.png")) + assert await fetch.fetch_image(session, url) is None + + +async def test_only_https() -> None: + """Plain HTTP and other schemes are refused before connecting.""" + async with aiohttp.ClientSession() as session: + assert ( + await fetch.fetch_image(session, "http://x/a.png") + is None + ) + assert await fetch.fetch_image(session, "file:///etc") is None + + +def test_urls_and_by_user() -> None: + """URLs are de-duplicated and mapped back to users.""" + people = ( + Person("1", "a", "https://x/1.png"), + Person("2", "b", "https://x/1.png"), + Person("3", "c", None), + ) + assert fetch.avatar_urls(people) == {"https://x/1.png"} + assert fetch.by_user(people, {"https://x/1.png": b"img"}) == { + "1": b"img", + "2": b"img", + } diff --git a/tests/test_alignment_isolation.py b/tests/test_alignment_isolation.py new file mode 100644 index 0000000..e39fde5 --- /dev/null +++ b/tests/test_alignment_isolation.py @@ -0,0 +1,40 @@ +"""The core and the command line work without Discord or Red.""" + +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +MODULES = ( + "doge_alignment", + "doge_alignment.cli", + "doge_alignment.core.alignments", + "doge_alignment.core.chart", + "doge_alignment.core.fetch", + "doge_alignment.core.layout", + "doge_alignment.core.storage", + "doge_alignment.core.view", +) + +CHECK = f""" +import importlib, sys +for name in {MODULES!r}: + importlib.import_module(name) +banned = ("discord", "redbot") +leaked = sorted(m for m in sys.modules if m.split(".")[0] in banned) +print(leaked) +sys.exit(1 if leaked else 0) +""" + + +def test_core_imports_neither_discord_nor_red() -> None: + """Importing the core (and the CLI) never loads discord.py or Red.""" + result = subprocess.run( # noqa: S603 + [sys.executable, "-c", CHECK], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_alignment_layout.py b/tests/test_alignment_layout.py new file mode 100644 index 0000000..167bd52 --- /dev/null +++ b/tests/test_alignment_layout.py @@ -0,0 +1,118 @@ +"""Pure layout: avatars fit their cells and never overlap.""" + +import itertools + +import pytest +from alignment_helpers import chart_with + +from doge_alignment.core.alignments import ALIGNMENTS +from doge_alignment.core.layout import ( + Box, + Theme, + best_grid, + capacity, + plan_cell, + plan_chart, + plan_tile, + scaled, + truncate, +) +from doge_alignment.core.view import Cell, Person, cells + + +def people(n: int) -> tuple[Person, ...]: + """Return ``n`` people named p0, p1, ...""" + return tuple(Person(str(i), f"p{i}", None) for i in range(n)) + + +def inside(inner: Box, outer: Box) -> bool: + """Whether ``inner`` lies within ``outer``.""" + return ( + outer.x <= inner.x + and outer.y <= inner.y + and inner.x + inner.w <= outer.x + outer.w + and inner.y + inner.h <= outer.y + outer.h + ) + + +def overlap(a: Box, b: Box) -> bool: + """Whether two boxes overlap.""" + return ( + a.x < b.x + b.w + and b.x < a.x + a.w + and a.y < b.y + b.h + and b.y < a.y + a.h + ) + + +@pytest.mark.parametrize("count", [1, 2, 3, 5, 9, 14, 40]) +def test_avatars_fit_and_do_not_overlap(count: int) -> None: + """Every avatar is inside its cell, below the label, apart.""" + theme = Theme() + box = Box(100, 50, theme.cell_size, theme.cell_size) + plan = plan_cell(Cell("True Neutral", people(count)), box, theme) + assert len(plan.slots) == count + assert plan.overflow == 0 + for slot in plan.slots: + assert inside(slot.avatar, box) + assert slot.avatar.y >= plan.label_box.y + plan.label_box.h + assert theme.min_avatar <= slot.avatar.w <= theme.max_avatar + for a, b in itertools.combinations(plan.slots, 2): + assert not overlap(a.avatar, b.avatar) + + +def test_names_only_when_avatars_are_big_enough() -> None: + """Few people get names; crowds don't.""" + theme = Theme() + box = Box(0, 0, theme.cell_size, theme.cell_size) + few = plan_cell(Cell("Lawful Good", people(3)), box, theme) + crowd = plan_cell(Cell("Lawful Good", people(40)), box, theme) + assert all(s.name_box is not None for s in few.slots) + assert all(s.name_box is None for s in crowd.slots) + + +def test_overflow_badge_when_too_many() -> None: + """Past capacity, the last slot becomes a +N badge.""" + theme = Theme() + box = Box(0, 0, theme.cell_size, theme.cell_size) + plan = plan_cell(Cell("Chaotic Evil", people(500)), box, theme) + assert plan.overflow_box is not None + assert len(plan.slots) + plan.overflow == 500 + assert len(plan.slots) + 1 <= capacity( + Box(0, 0, theme.cell_size, theme.cell_size), theme + ) + + +def test_best_grid_prefers_bigger_avatars() -> None: + """Two people side by side beat two stacked in a wide area.""" + grid = best_grid(2, Box(0, 0, 400, 150), Theme()) + assert (grid.columns, grid.rows) == (2, 1) + + +def test_chart_plan_is_a_3x3_square() -> None: + """Cells sit in chart order on a square picture.""" + theme = Theme() + plan = plan_chart(cells(chart_with()), theme) + assert plan.width == plan.height == 2 * 16 + 3 * 360 + 2 * 12 + xs = sorted({c.box.x for c in plan.cells}) + ys = sorted({c.box.y for c in plan.cells}) + assert len(xs) == len(ys) == 3 + assert [c.alignment for c in plan.cells] == list(ALIGNMENTS) + assert plan.cells[5].box.x == xs[2] + assert plan.cells[5].box.y == ys[1] + + +def test_tile_is_a_scaled_cell() -> None: + """A tile fills its picture and scales sizes up.""" + theme = Theme() + plan = plan_tile(Cell("Lawful Good", people(1)), theme) + assert (plan.width, plan.height) == (theme.tile_size,) * 2 + (cell,) = plan.cells + assert cell.slots[0].avatar.w > theme.max_avatar + assert scaled(theme, 2).max_avatar == theme.max_avatar * 2 + + +def test_truncate() -> None: + """Long names end in an ellipsis at the limit.""" + assert truncate("short", 10) == "short" + assert truncate("a very long name", 6) == "a ver…" diff --git a/tests/test_alignment_render.py b/tests/test_alignment_render.py index 597a949..711e134 100644 --- a/tests/test_alignment_render.py +++ b/tests/test_alignment_render.py @@ -1,41 +1,94 @@ -"""The image helpers for the (future) chart picture.""" +"""Painting with ImageMagick (skipped where Wand can't load it).""" -from typing import get_args +import io import pytest +from alignment_helpers import chart_with -pytest.importorskip("wand.image", reason="needs ImageMagick") +from doge_alignment.core.images import sniff +from doge_alignment.core.layout import Theme +from doge_alignment.core.view import Profile, cells -from doge_alignment.render import ( # noqa: E402 - BorderShape, - grid_positions, - process_avatar, - solid_color_background, +render = pytest.importorskip( + "doge_alignment.core.render", reason="needs ImageMagick" ) +wand_image = pytest.importorskip("wand.image") +wand_color = pytest.importorskip("wand.color") -def test_grid_positions_fill_rows_of_three() -> None: - """Cells go left to right, then down, with gaps between them.""" - assert grid_positions(4, (100, 50), gap=10) == [ - (0, 0), - (110, 0), - (220, 0), - (0, 60), - ] +def png(color: str, width: int = 40, height: int = 30) -> bytes: + """Return a solid PNG.""" + with wand_image.Image( + width=width, height=height, background=wand_color.Color(color) + ) as img: + img.format = "png" + return bytes(img.make_blob()) -@pytest.mark.parametrize("shape", get_args(BorderShape)) -def test_process_avatar_size_and_border(shape: BorderShape) -> None: - """Avatars are resized, shaped and bordered on a copy.""" - with solid_color_background(300, 200, "blue") as original: - out = process_avatar(original, (64, 64), 4, "green", shape) - assert out.size == (72, 72) - assert original.size == (300, 200) +def load(data: bytes): # noqa: ANN201 (Wand is untyped) + """Open PNG bytes.""" + return wand_image.Image(blob=data, format="png") -def test_circle_has_transparent_corners() -> None: - """Outside the circle is see-through, inside is not.""" - with solid_color_background(64, 64, "red") as img: - out = process_avatar(img, (64, 64), 0, "black", "circle") - assert out[0, 0].alpha == 0 - assert out[32, 32].alpha == 1 +def test_sniff() -> None: + """Only the four avatar formats are recognised.""" + assert sniff(png("red")) == "png" + assert sniff(b"\xff\xd8\xff\xe0rest") == "jpeg" + assert sniff(b"GIF89a...") == "gif" + assert sniff(b"RIFF\0\0\0\0WEBPVP8 ") == "webp" + assert sniff(b"") is None + + +def test_avatar_disc_is_round() -> None: + """Corners are transparent, the middle is the avatar.""" + theme = Theme() + with render.avatar_disc( + png("red", 300, 200), + 64, + present=True, + fallback_text="?", + theme=theme, + ) as disc: + assert disc.size == (64, 64) + assert disc[0, 0].alpha == 0 + assert disc[63, 63].alpha == 0 + middle = disc[32, 32] + assert middle.red > 0.9 + assert middle.green < 0.1 + + +def test_absent_people_are_grey() -> None: + """Someone who left is drawn without colour.""" + with render.avatar_disc( + png("red"), 64, present=False, fallback_text="?", theme=Theme() + ) as disc: + middle = disc[32, 32] + assert middle.red == pytest.approx(middle.green, abs=0.02) + + +def test_bad_bytes_fall_back_to_placeholder() -> None: + """Non-images (here an SVG) are never decoded.""" + theme = Theme() + with render.avatar_disc( + b"", 64, present=True, fallback_text="A", theme=theme + ) as disc: + assert disc[32, 4].alpha == 1 + + +def test_render_chart_and_tiles() -> None: + """One square PNG for the chart, nine for the tiles.""" + chart = chart_with(("1", "Lawful Good"), ("2", "Chaotic Evil")) + chart_cells = cells(chart, {"1": Profile("one")}.get) + avatars = {"1": png("blue")} + theme = Theme() + with load(render.render_chart(chart_cells, avatars, theme)) as img: + side = 2 * theme.margin + 3 * theme.cell_size + 2 * theme.gap + assert img.size == (side, side) + tiles = render.render_tiles(chart_cells, avatars, theme) + assert len(tiles) == 9 + with load(tiles[0]) as tile: + assert tile.size == (theme.tile_size, theme.tile_size) + # Tiles are the cell colour edge to edge + corner = tile[0, 0] + assert (corner.red, corner.green, corner.blue) != (0, 0, 0) + assert all(io.BytesIO(t).read(8) == b"\x89PNG\r\n\x1a\n" for t in tiles) diff --git a/tests/test_alignment_storage.py b/tests/test_alignment_storage.py new file mode 100644 index 0000000..91e7c2c --- /dev/null +++ b/tests/test_alignment_storage.py @@ -0,0 +1,85 @@ +"""Charts to and from Config data and YAML.""" + +import pytest +from alignment_helpers import chart_with + +from doge_alignment.core.chart import Entry, empty_chart, place +from doge_alignment.core.storage import ( + ChartFormatError, + from_data, + from_yaml, + to_data, + to_yaml, +) + +# The format the cog saved before it moved to Config +OLD_YAML = """ +users: + '111222333': + alignment: Chaotic Good + display_name: EpicUser + avatar_url: https://cdn.discordapp.com/avatars/111222333/avatar.png +""" + + +def test_data_round_trip() -> None: + """What goes into Config comes back out the same.""" + chart = place( + chart_with(("1", "Lawful Good"), admins=("1", "2")), + "3", + Entry("Neutral Evil", "three", "https://example.com/a.png"), + ) + assert from_data(to_data(chart)) == chart + + +def test_from_data_skips_malformed() -> None: + """Bad entries are dropped; ids become strings.""" + chart = from_data( + { + "users": { + 1: {"alignment": "cg", "display_name": "a"}, + "2": {"alignment": "nope"}, + "3": "not a dict", + "4": {"alignment": "Lawful Evil"}, + }, + "admins": [5], + } + ) + assert set(chart.users) == {"1", "4"} + assert chart.users["1"].alignment == "Chaotic Good" + assert chart.users["4"].display_name == "4" + assert chart.admins == ("5",) + assert from_data(None) == empty_chart() + assert from_data({"users": [], "admins": "x"}) == empty_chart() + + +def test_yaml_round_trip() -> None: + """Export then import gives the same chart.""" + chart = chart_with( + ("1", "Lawful Good"), ("2", "True Neutral"), admins=("1",) + ) + assert from_yaml(to_yaml(chart)) == chart + + +def test_reads_the_old_yaml_format() -> None: + """Files from the old cog still import.""" + chart = from_yaml(OLD_YAML) + entry = chart.users["111222333"] + assert entry.alignment == "Chaotic Good" + assert entry.display_name == "EpicUser" + assert chart.admins == () + + +@pytest.mark.parametrize( + ("text", "message"), + [ + ("users: [", "not valid YAML"), + ("- a list", "'users' mapping"), + ("admins: []", "'users' mapping"), + ("users:\n '1': {alignment: bad}", "user\\(s\\) 1"), + ], +) +def test_from_yaml_is_strict(text: str, message: str) -> None: + """Imports fail loudly instead of silently dropping people.""" + with pytest.raises(ChartFormatError, match=message): + from_yaml(text) diff --git a/tests/test_alignment_view.py b/tests/test_alignment_view.py new file mode 100644 index 0000000..908d4a3 --- /dev/null +++ b/tests/test_alignment_view.py @@ -0,0 +1,70 @@ +"""What gets shown: cells, live names, people who left, text.""" + +from alignment_helpers import chart_with + +from doge_alignment.core.alignments import ALIGNMENTS +from doge_alignment.core.chart import Entry, place +from doge_alignment.core.view import ( + Profile, + absent, + cells, + everyone, + format_text, + tile_filename, +) + + +def test_nine_cells_in_order_even_when_empty() -> None: + """Every alignment gets a cell, in chart order.""" + result = cells(chart_with(("1", "Chaotic Evil"))) + assert tuple(c.alignment for c in result) == ALIGNMENTS + assert [len(c.people) for c in result] == [0] * 8 + [1] + + +def test_live_profiles_win_and_absent_people_are_marked() -> None: + """Live names replace saved ones; unknown people have left.""" + chart = place( + chart_with(("1", "Lawful Good")), + "2", + Entry("Lawful Good", "old name", "https://x/old.png"), + ) + live = {"1": Profile("Alice", "https://x/a.png")} + (good, *_) = cells(chart, live.get) + assert [(p.name, p.present) for p in good.people] == [ + ("Alice", True), + ("old name", False), + ] + assert good.people[1].avatar_url == "https://x/old.png" + assert absent(chart, live.get) == ("2",) + + +def test_without_lookup_everyone_is_present() -> None: + """Charts from files have nobody to look up.""" + result = cells(chart_with(("1", "True Neutral"))) + assert all(p.present for p in everyone(result)) + + +def test_people_sorted_by_name_case_insensitively() -> None: + """Within a cell, present people come first, then by name.""" + chart = chart_with(("1", "True Neutral"), ("2", "True Neutral")) + chart = place(chart, "3", Entry("True Neutral", "Bob")) + names = {"1": Profile("carol"), "3": Profile("Bob")} + middle = cells(chart, names.get)[4] + assert [p.name for p in middle.people] == ["Bob", "carol", "user2"] + + +def test_format_text_skips_empty_cells_and_marks_leavers() -> None: + """Text lists only cells with people, in chart order.""" + chart = chart_with(("1", "Chaotic Evil"), ("2", "Lawful Good")) + text = format_text(cells(chart, {"1": Profile("Eve")}.get)) + assert text.splitlines() == [ + "**Lawful Good**: ~~user2~~ (left)", + "**Chaotic Evil**: Eve", + ] + + +def test_tile_filenames() -> None: + """Tiles are numbered in chart order with the abbreviation.""" + result = cells(chart_with()) + assert tile_filename(1, result[0]) == "1-lg.png" + assert tile_filename(9, result[8]) == "9-ce.png"