Author SHA1 Message Date
nocodeandClaude Opus 5 b9bc3b934b chore(changelog): regenerate from the commit history
CI / quality (pull_request) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:36 +02:00
nocodeandClaude Opus 5 566af4db70 docs(web): document my tasks, the search and the status page
Adds the chapter the three tools were missing, and points the monitoring
guide at /api/status rather than /api/health, which answers a narrower
question than an operator usually means.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:35 +02:00
nocodeandClaude Opus 5 a1e1de7734 feat(web): publish a public status page at /status
Checking whether the service is up required an account, so the answer
lived where the people asking could not reach it.

The page is rendered on the server with no script at all and refreshes
through a meta tag: a status page that needs a working browser is
useless at the moment it is read. Two rules follow from it being public.
A repository the forge does not list as public keeps its environment
visible but loses its name, and the banner always states the worst true
thing — a failed deployment forbids the green headline even while the
bot answers. WEB_PUBLIC_STATUS=false removes page and route together.

/api/status gives the same in JSON, which is what a monitor should watch
rather than /api/health — the latter only says the process is alive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:26 +02:00
nocodeandClaude Opus 5 9acb523510 feat(web): search the whole panel from one place
Finding anything meant knowing which tab it lived in — fine once you
have learned the panel, hopeless before. ⌘K now covers cards,
repositories, issues, wiki pages and members at once.

Pages are matched in the browser, so the palette answers before it has
asked the server and stays useful while the forge is down. Each remote
source is queried independently and a source that fails is simply absent
from the results, rather than taking the others with it. Issues come
from one organization-wide request: per repository, the palette could
not afford them on every keystroke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:04 +02:00
nocodeandClaude Opus 5 fcc82d82d6 feat(projects): gather the cards one member carries
A board answers "where does the work stand". Nobody opens a dashboard to
ask that first: they ask what is on them today, and once the work is
spread over several boards no single board can answer it.

The cards assigned to a member are now listed on a page of their own,
grouped by deadline, with a counter on the sidebar entry — a page you
have to open to know whether it needs you is a page you stop opening.
The column travels with each card, so finishing one from the list is a
single move rather than a detour through its board.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:45:03 +02:00
nocodeandClaude Opus 5 d2256e2211 refactor(web): extract the build marker into its own module
The version and the interface build date were computed inside the route
file, where two copies of the same comment had already drifted apart. The
status page needs the same answer, and a second copy would eventually
give a different one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:43:41 +02:00
nocodeandClaude Opus 5 e3ce266225 docs(ops): correct the deployment path for a panel without a shell
Pterodactyl's console is the process stdin, not a terminal, so the previous
instructions could not be followed even with full panel rights. The chapter
now covers both cases: a real shell where one exists, and otherwise the
dashboard's own command deploy, which runs inside the container and needs no
console at all.

It also starts by checking the commands land on the filesystem the bot
reads — a pull in the wrong place reports success and changes nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:11:51 +02:00
nocodeandClaude Opus 5 1643fcb591 docs(ops): document deployment, CI, monitoring and backups
Four independent procedures, each opening with the failure it prevents —
most of them ones this project actually hit: a front-end older than its API
after a partial upload, a broken card move that no test ran before it
shipped, an evening spent asking whether the site was down, and a database
that came back empty after a rebuild.

The CI workflow ships with them. It leaves out `format:check`, which would
fail on CRLF files that predate the Prettier configuration; normalising them
deserves a commit of its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:08:52 +02:00
nocodeandClaude Opus 5 1c21f6ff53 feat(projects): pull Gitea issues onto any board
The import only existed on a repository board and always landed in the first
column. The organization board is exactly where issues from several
repositories belong together, so the button now lives on every board and
asks which repository, which column, and whether closed issues come too.

An issue already on the board is skipped rather than duplicated, so the
button survives being pressed twice — which the tests check against a
stand-in forge, along with the due date and labels carried over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 14:03:06 +02:00
nocodeandClaude Opus 5 8869c74b7b fix(wiki): render the public pages on the server
The documentation was assembled in the browser, so a client that runs no
script saw an empty shell — including whoever fetches the terms and privacy
links before approving an application, which is exactly what those pages are
for.

The wiki is now delivered as finished HTML, carries no script at all, and
declares itself indexable, unlike the panel. Search works through a plain
query string, an unknown page answers 404 rather than a blank page, and both
legal pages are linked from the footer of every page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:31:27 +02:00
nocodeandClaude Opus 5 3d0e21d7cb feat(wiki): serve the legal pages at /terms-of-service and /privacy-policy
Discord, and most platforms, ask for a terms URL and a privacy URL in a
form field; pasting a `/wiki/...` address there reads like an afterthought.
Both pages now answer at the root, while everything else stays under
`/wiki/`.

The API states each page's address instead of leaving the front to rebuild
it, so there is one place that decides. Existing pages are renamed rather
than recreated, keeping whatever has already been written in them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:25:59 +02:00
nocodeandClaude Opus 5 e1b9a5cc77 feat(projects): add the board interface
Drag and drop between columns, cards carrying an assignee, a due date,
labels and a linked issue whose state shows on the card. An overloaded
column says so in its header rather than blocking the drop.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:09 +02:00
nocodeandClaude Opus 5 901ca56959 feat(projects): add a Kanban board per repository and one for the organization
Boards live in SQLite rather than in Gitea, whose project API is not stable
across versions: a board that stops working whenever the forge hiccups is
worse than no board, and this one has hiccupped already.

A card can still point at an issue — `owner/repo#12` — and its real state is
resolved when the forge answers, one request per repository rather than per
card. Open issues can also be imported in bulk, skipping those already on
the board.

Columns follow the ones the README describes, and carry an optional card
limit which warns rather than refuses: stopping someone mid-gesture to
enforce a convention is not what a limit is for.

Moving a card rebuilds the order explicitly — take the column without it,
insert at the wanted rank, renumber — because fractional positions get the
same-column case wrong, as the tests showed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 b793298cbf test(web): lock the sidebar highlighting behind tests
It has been reported twice and fixed twice by reading the code, which is how
it came back. The decision is now a module of its own — the shell only asks
it which entry is current — and twelve cases pin it down: a detail page, a
query string, every spelling of the home route, and the original regression
where home stayed lit everywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 3f4a5709cf fix(web): stop caching the interface modules
Modules cache independently, so a browser could revalidate one and keep an
older copy of another — leaving a page running one version of itself and a
different version of its helpers. That surfaces as an error inside a
feature, which is nothing like what it is, and no reload short of clearing
the site data reliably fixes it.

A dashboard is a handful of small files read by one person at a time: the
bandwidth caching saves is worth less than the failure it causes. They are
now fetched fresh.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 c031b4d9e2 fix(web): keep the stack when a view fails
Views caught their errors and showed only the message, so nothing said which
module or which line had failed — neither in the console, which never saw
the error, nor on the page.

The stack is now logged and offered on the page behind a disclosure, because
opening the developer console is not always an option on a self-hosted
panel.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 92c27aed9f fix(web): read the interface build date instead of freezing it at startup
The marker was captured once at import, while the front-end is served from
disk on every request. Uploading new files therefore left it announcing the
old build until the next restart — the exact confusion it was added to
prevent.

It is now read from disk, cached ten seconds so a health check does not walk
the tree each time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:08 +02:00
nocodeandClaude Opus 5 75d1e53205 fix(web): stop the settings page breaking on an unexpected payload
Every list the page walks was read straight off the response, so a single
missing field took the whole view down with `undefined.map` — which reads as
a broken feature rather than as what it is, a page and an API disagreeing on
the shape of the data.

The page now normalises what it receives: absent lists render empty, an enum
without options falls back to a text field, and settings that arrive without
sections are shown under one heading instead of not at all.

Errors of that family also say so, and point at the reload that fixes them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 95b51ab428 feat(web): open a repository from anywhere on its row
The cards on the repository page already opened as a whole, but the tables
on the organisation and overview pages still only linked the name, so the
same object behaved differently depending on where it was listed.

A table row can now carry a destination. Controls inside it keep their own
behaviour, the row is reachable with the keyboard, and only the empty space
navigates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 539b1506f4 fix(web): give static assets a validator caches can check
The front-end was served with `no-cache` but no `ETag` and no
`Last-Modified`, so a cache had nothing to revalidate against and could keep
handing out modules older than the API they talk to — which surfaces as a
cryptic error in a view rather than as anything resembling a stale cache.

Assets now carry both, and an unchanged file answers 304.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 3bd290cba6 fix(web): say when the dashboard is disabled
`WEB_ENABLED` not being `true` produced no output at all, so a missing site
looked exactly like a broken one and there was nothing in the console to
tell the two apart.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 afcd0e55bc fix(web): say out loud when the dashboard cannot listen
A failed `listen` only produced a generic line the bot then carried on past,
so the site was simply absent with nothing explaining why — and inside a
container a bind on an unpublished port succeeds while staying unreachable,
which looks identical to a crash from the browser.

The error now names the address, the port and the actual cause, and a
successful bind on `0.0.0.0` reminds that the port still has to be published
by the host.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 40032ec091 fix(config): warn when a public address is announced but only loopback is bound
`WEB_HOST=127.0.0.1` is the right default behind a reverse proxy on the same
machine, and the wrong one inside a container or on a hosting panel, where
the process has to bind the allocation. The guidance only mentioned the
first case, so a `.env` written from the wizard could leave the dashboard
listening where nothing could reach it — every request timing out with
nothing saying why.

The wizard now flags the contradiction between a loopback bind and a public
URL, and both the help text and `.env.example` name the container case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00
nocodeandClaude Opus 5 5660235f3d docs(web): document the wiki, the settings and the command publishing
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 e5b7303a01 feat(wiki): add the reading site and its editor
The renderer escapes HTML before any transformation and drops
`javascript:` links. Pages are written by the team, but a renderer that
relies on that is one mistake away from being a hole.

The editor previews as you type: legal pages are long, and writing Markdown
blind is how broken tables end up published.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 c76c0b96eb feat(wiki): serve a public documentation written from the panel
Pages live in SQLite and are read without a session: documentation nobody
can reach without an account is not documentation. Drafts answer 404 even
when their address is guessed, and the site never falls back to the
dashboard shell, which would send a visitor to a login screen.

The wiki ships with terms of use and a privacy policy written against the
revised Swiss LPD, describing table by table what this codebase actually
stores. Both are marked protected: they can be rewritten, not deleted, and
a deleted one comes back on the next start — a bot that processes personal
data must always be able to show its notice.

The bracketed details still have to be completed and the whole reviewed;
this is a starting point written from the schema, not legal advice.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 621f3e404b style(web): adopt the official FWS mark and its palette
The placeholder mark was an Arch-blue chevron. The site now carries the FWS
logo — cyan ring on dark navy — and its accent colour follows, so the
dashboard and the brand no longer disagree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 e397abcfcd fix(web): make the whole repository card open the repository
Only the name was a link, so most of a rectangle that reacts to the pointer
led nowhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:06 +02:00
nocodeandClaude Opus 5 262274473a feat(web): publish the slash commands from the panel
Registering the commands was the one routine step that still needed shell
access on the host, which is awkward when the bot runs behind a hosting
panel. Guild commands take effect immediately, so the button says what it
did as soon as it returns.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 b42fb1065a feat(voice): take back the generated channels the database forgot
A voice channel outlives the process that made it. A restored backup, a
wiped `data/` folder or a redeployment shipping a fresh database all leave
real channels behind that nothing manages any more: they are never cleaned
up, and their owner can no longer rename or lock them.

At startup the bot now reclaims the channels sitting in a trigger's own
category and named after its template — a channel created by hand is never
touched. Those still in use go back to whoever is inside; the empty ones are
leftovers and are removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 406b5af3ea feat(settings): make the server settings real, and widen them
The dashboard offered seven switches that nothing read: they promised a
behaviour the bot did not have, which is worse than offering nothing.

Every setting is now declared once, with its type, its bounds and its
explanation, and the services read it: the welcome message and its wording,
the automatic role, departure notices, the private notice sent to a
sanctioned member, the default mute duration, how much history a ban erases,
whether a closed ticket is deleted or archived, and an optional role mention
on the Gitea notifications.

A test walks the sources and fails when a declared key is read nowhere, so
the list cannot drift back into decoration.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:05 +02:00
nocodeandClaude Opus 5 d439b1b3e8 feat(web): make deploying reachable from where it is looked for
The « Déployer » button only existed on the row of an already created
target, so an empty list was a dead end whose only way out sat in the page
header. The empty state now carries the action that fills it.

A release also gains its own deploy button: wanting to ship a given version
is the moment people look for it, and sending them to another page to retype
the tag was needless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:47:47 +02:00
nocodeandClaude Opus 5 a44ff0cb52 fix(web): pin the sidebar highlight to the route, and name the build
The highlight compared hrefs, which a trailing slash or a query string in the
hash was enough to defeat, and it only ran once the view had loaded. Each
link now carries the route it stands for and the highlight is applied as soon
as the sidebar exists.

The footer also states the running version and the date of the newest
interface file. Deployments that ship an archive make it easy to look at a
stale copy and wonder why a fix is missing; the page can now say so.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:47:46 +02:00
nocodeandClaude Opus 5 2083133c7a docs(web): document the live updates
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 5481e79dc4 feat(web): refresh the pages as the events arrive
One `EventSource` for the whole dashboard, held in a single slot: a view that
re-renders itself would otherwise register a second listener each time and
double the work on every event.

A refresh landing under someone's fingers is worse than data a few seconds
old, so it waits while a dialog is open or a field has focus, a burst of
writes collapses into one reload, and a background tab closes its stream.
The Discord page stays off the tick because listing members calls the
Discord API. When the stream cannot be established a timer takes over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 df89cc5893 feat(web): push live updates to the dashboard
Reading a page and wondering whether it is still true is a poor way to watch
a deployment, and polling every page on a timer costs far more than it
returns.

The server keeps one `text/event-stream` per open tab and publishes on it:
a write once it has actually succeeded, tagged with the page it concerns, a
deployment when it starts and when it ends, an incoming Gitea webhook, plus
a tick and a heartbeat that stops proxies closing an idle stream.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:39:59 +02:00
nocodeandClaude Opus 5 9c6297e00e fix(web): always offer the bootstrap token on the sign-in page
The field only appeared when a token was already configured, which hid the
one way back into the configuration exactly when Discord sign-in is broken
or not set up yet. It is now always present, and says how to obtain a token
when none is available.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:16 +02:00
nocodeandClaude Opus 5 ff15dfe92f fix(web): let a deploy target be created without a reachable Gitea
The « Nouvelle cible » button was hidden whenever the repository list came
back empty, and a Gitea answering 403 took the whole page down with it — so
a forge problem removed every way to set up a deployment, including webhook
and shell targets that never talk to Gitea at all.

The list is now a convenience: its failure is reported as a warning and the
repository falls back to a free-text field.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:16 +02:00
nocodeandClaude Opus 5 a0428e0549 fix(web): keep the sidebar in step with the page being shown
Navigating only swapped the main area, so the highlighted entry stayed on
whichever page the shell was built with and nothing on screen said where you
were. The highlight is now refreshed on every navigation, carries
`aria-current` for screen readers and an inset marker that reads at a glance,
and the browser tab takes the page name.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:34:09 +02:00
nocodeandClaude Opus 5 20ff701430 fix(web): derive the OAuth2 redirect from the address actually used
`WEB_PUBLIC_URL` was the only source of the `redirect_uri`, so a hosting
panel or a proxy publishing the dashboard on another port produced a link
Discord refuses, with nothing on screen pointing at the port mismatch.

The browser's own origin is what Discord compares against, so the redirect
now comes from the request, honouring `X-Forwarded-Host` and
`X-Forwarded-Proto` when a proxy sits in front. `WEB_PUBLIC_URL` stays as
the fallback for links built outside a request, and the sign-in page prints
the exact value to declare in the portal.

The `Secure` cookie flag follows the same rule: announcing HTTPS in the
configuration while serving plain HTTP made the browser drop the session.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:12:44 +02:00
nocodeandClaude Opus 5 e63d6aa18e docs(web): document the dashboard and the configuration wizard
Both READMEs gain the same section and the same variables, as the
organisation requires them to stay in sync.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 bd7fdea275 test(web): cover the router, configuration, auth, deployments and server
The schema test compares the declared variables against `.env.example`, so
the two cannot drift apart. The server tests drive the real handler over a
loopback socket rather than a mock, which is what caught the health probe
missing from bootstrap mode and the deployments recorded under the wrong
guild.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 06a9be0cba feat(web): serve the dashboard and its interface
The front-end is plain JavaScript served as is: no build step to run before
the bot starts, and no second toolchain to keep alive. A simple/advanced
switch hides the technical panels without ever standing in for a permission.

`npm run setup` starts the wizard alone, because the bot refuses to boot
without a token and the `.env` has to be writable from somewhere. When the
webhook and the dashboard share a port, a single HTTP server is started.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00
nocodeandClaude Opus 5 bf92badb05 feat(web): expose the dashboard API
One module per domain, each route declaring the minimum access level the
server enforces before the handler runs. Irreversible actions ask for the
exact name to be typed back, and every write lands in `event_logs` with its
author so the history says who did what.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 611129b23c feat(web): run and record release deployments
Three kinds of target, ordered by how much they trust the caller: a signed
webhook runs nothing locally, a Gitea Action delegates to the forge, and a
shell command executes arbitrary code on the bot host — hence the double
lock of an environment flag plus the Owner level on that last one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 efaaca35dd feat(web): read, validate and write the .env configuration
Every variable is described once, with its explanation and the steps to
obtain it. The form, the validation and the generated file all derive from
that description, so adding a variable to the bot means touching one file.

The previous file is backed up before being replaced, and an empty secret
means "keep the current value" so a token cannot be wiped by accident.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 e03b184d68 feat(web): add the HTTP layer and Discord-backed sessions
Visitors sign in with Discord and inherit the very same access levels as the
slash commands, so there is no second permission model to keep in sync.

Writes require a header a cross-site form cannot forge, on top of the
`SameSite=Lax` cookie, and a bootstrap token opens the configuration wizard
alone for the case where no Discord application exists yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 5abe713279 feat(database): store dashboard sessions, deploy targets and deployments
Sessions and API tokens keep only a hash of the value handed to the client,
so a database dump cannot be replayed. A deployment denormalises its target
name so the history survives the deletion of that target.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00
nocodeandClaude Opus 5 4b0737a512 feat(gitea): add an organization and repository administration client
`gitea-client.js` stays focused on the single repository the slash commands
talk to. The dashboard addresses any repository of the organization, so its
endpoints live apart instead of bloating the command path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:12 +02:00
nocodeandClaude Opus 5 e4534d4d50 feat(config): declare the web dashboard environment variables
The dashboard is off by default and listens on the loopback interface: it
must be an explicit decision to expose it, not a side effect of upgrading.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:12 +02:00
nocodeandClaude Opus 5 92405ac618 fix(notifications): apply the channel overrides set from Discord
`/notify set` stores the types listed in `NOTIFICATION_TYPES` (`releases`,
`commits`, `pull_requests`) while the webhook handler looks them up under the
Gitea event names (`release`, `push`, `pull_request`), so an override chosen
from Discord was never found and the environment default always won.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:07 +02:00
BlackAngelTV 2ccb462e35 Merge pull request 'refactor(all): uniformisation' (#144) from build/project-structure into main
Reviewed-on: #144
2026-09-23 16:31:05 +00:00
BlackAngelTV 50665c8edd refactor(all): uniformisation 2026-09-23 18:25:28 +02:00
BlackAngelTV 865f2eb91b Merge pull request 'Build/project structure' (#142) from build/project-structure into main
Reviewed-on: #142
2026-09-23 12:31:21 +00:00
178 changed files with 31007 additions and 10215 deletions

No files matched your search

+9 -9
View File
@@ -1,9 +1,9 @@
root = true root = true
[*] [*]
charset = utf-8 charset = utf-8
end_of_line = lf end_of_line = lf
indent_style = space indent_style = space
indent_size = 2 indent_size = 2
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
+113 -82
View File
@@ -1,82 +1,113 @@
# ============================================================================= # =============================================================================
# FWS-Bot — environment configuration example # FWS-Bot — environment configuration example
# Copy this file to `.env` and fill in the values. Never commit `.env`. # Copy this file to `.env` and fill in the values. Never commit `.env`.
# ============================================================================= # =============================================================================
# --- Runtime ----------------------------------------------------------------- # --- Runtime -----------------------------------------------------------------
# development | production | test # development | production | test
NODE_ENV=development NODE_ENV=development
# debug | info | warn | error # debug | info | warn | error
LOG_LEVEL=info LOG_LEVEL=info
LOG_DIR=./logs LOG_DIR=./logs
# Number of days functional/technical logs are kept (M11-T08) # Number of days functional/technical logs are kept (M11-T08)
LOG_RETENTION_DAYS=30 LOG_RETENTION_DAYS=30
# --- Discord application (M2-T01) ------------------------------------------- # --- Discord application (M2-T01) -------------------------------------------
# Developer Portal > Bot > Token # Developer Portal > Bot > Token
DISCORD_TOKEN= DISCORD_TOKEN=
# Developer Portal > General Information > Application ID # Developer Portal > General Information > Application ID
DISCORD_CLIENT_ID= DISCORD_CLIENT_ID=
# FWS server ID (slash commands are registered on this guild) # FWS server ID (slash commands are registered on this guild)
DISCORD_GUILD_ID= DISCORD_GUILD_ID=
# --- FWS roles (M3-T01) — Discord role IDs ---------------------------------- # --- FWS roles (M3-T01) — Discord role IDs ----------------------------------
ROLE_OWNER_ID= ROLE_OWNER_ID=
ROLE_DEV_ID= ROLE_DEV_ID=
ROLE_STAFF_ID= ROLE_STAFF_ID=
# Role given to new members on join (M7-T03) # Role given to new members on join (M7-T03)
ROLE_MEMBER_ID= ROLE_MEMBER_ID=
# --- Discord channels (M0-T04 / M9-T01) — channel IDs ----------------------- # --- Discord channels (M0-T04 / M9-T01) — channel IDs -----------------------
CHANNEL_WELCOME_ID= CHANNEL_WELCOME_ID=
CHANNEL_RULES_ID= CHANNEL_RULES_ID=
CHANNEL_ANNOUNCEMENTS_ID= CHANNEL_ANNOUNCEMENTS_ID=
CHANNEL_LOGS_ID= CHANNEL_LOGS_ID=
CHANNEL_MOD_LOGS_ID= CHANNEL_MOD_LOGS_ID=
CHANNEL_TICKETS_LOGS_ID= CHANNEL_TICKETS_LOGS_ID=
CHANNEL_NOTIF_ISSUES_ID= CHANNEL_NOTIF_ISSUES_ID=
CHANNEL_NOTIF_PULL_REQUESTS_ID= CHANNEL_NOTIF_PULL_REQUESTS_ID=
CHANNEL_NOTIF_COMMITS_ID= CHANNEL_NOTIF_COMMITS_ID=
CHANNEL_NOTIF_RELEASES_ID= CHANNEL_NOTIF_RELEASES_ID=
CHANNEL_NOTIF_ERRORS_ID= CHANNEL_NOTIF_ERRORS_ID=
# Category under which private ticket channels are created (M6) # Category under which private ticket channels are created (M6)
CATEGORY_TICKETS_ID= CATEGORY_TICKETS_ID=
# --- Salons vocaux temporaires (M14) ---------------------------------------- # --- Salons vocaux temporaires (M14) ----------------------------------------
# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire # Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire
CHANNEL_VOICE_TRIGGER_ID= CHANNEL_VOICE_TRIGGER_ID=
# Catégorie d'accueil des salons vocaux créés (facultatif) # Catégorie d'accueil des salons vocaux créés (facultatif)
CATEGORY_VOICE_ID= CATEGORY_VOICE_ID=
# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat) # Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat)
VOICE_EMPTY_GRACE_MS=5000 VOICE_EMPTY_GRACE_MS=5000
# --- Statuts du bot (M15) ----------------------------------------------------- # --- Statuts du bot (M15) -----------------------------------------------------
# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval) # Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval)
BOT_STATUS_INTERVAL_SECONDS=60 BOT_STATUS_INTERVAL_SECONDS=60
# --- Gitea (M5-T01) ---------------------------------------------------------- # --- Gitea (M5-T01) ----------------------------------------------------------
GITEA_URL=https://gitea.nocode-var.tech GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it. # Token with least privilege (read:repository, write:issue). Never log it.
GITEA_TOKEN= GITEA_TOKEN=
GITEA_OWNER=FWS GITEA_OWNER=FWS
GITEA_REPO=FWS-Arch GITEA_REPO=FWS-Arch
GITEA_TIMEOUT_MS=10000 GITEA_TIMEOUT_MS=10000
GITEA_MAX_RETRIES=2 GITEA_MAX_RETRIES=2
# --- Gitea webhooks (M9-T02) ------------------------------------------------- # --- Gitea webhooks (M9-T02) -------------------------------------------------
WEBHOOK_ENABLED=false WEBHOOK_ENABLED=false
WEBHOOK_HOST=0.0.0.0 WEBHOOK_HOST=0.0.0.0
WEBHOOK_PORT=3000 WEBHOOK_PORT=3000
WEBHOOK_PATH=/webhooks/gitea WEBHOOK_PATH=/webhooks/gitea
# Shared secret configured in Gitea > Settings > Webhooks # Shared secret configured in Gitea > Settings > Webhooks
GITEA_WEBHOOK_SECRET= GITEA_WEBHOOK_SECRET=
# --- SQLite (M1-T05) --------------------------------------------------------- # --- Tableau de bord web (M16) -----------------------------------------------
DATABASE_PATH=./data/fws-bot.sqlite # Site d'administration servi par le bot : `npm run setup` pour l'assistant .env,
BACKUP_DIR=./data/backups # puis http://WEB_HOST:WEB_PORT une fois le bot démarré.
WEB_ENABLED=false
# --- FWS links (M0-T06 / M4-T04) --------------------------------------------- # 127.0.0.1 derrière un reverse proxy installé sur la même machine.
FWS_WEBSITE_URL= # 0.0.0.0 dans un conteneur ou sur un panel d'hébergement (Pterodactyl, Docker) :
FWS_DOCS_URL= # sinon le site n'écoute que sur la boucle locale et reste injoignable.
FWS_DISCORD_INVITE_URL= WEB_HOST=127.0.0.1
FWS_ARCH_REPO_URL= WEB_PORT=3080
# URL publique du tableau de bord, utilisée pour la redirection OAuth2 Discord.
# Doit correspondre exactement à une redirection déclarée dans le Developer Portal.
WEB_PUBLIC_URL=http://localhost:3080
# Clé de signature des cookies de session (64 caractères hex).
# Générer avec : node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
WEB_SESSION_SECRET=
WEB_SESSION_TTL_HOURS=12
# Developer Portal > OAuth2 > Client Secret. Requis pour la connexion au tableau de bord.
DISCORD_CLIENT_SECRET=
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
# À vider une fois le .env rempli.
WEB_SETUP_TOKEN=
# Publie /status : bot en ligne, derniers déploiements, dernières releases.
# Les dépôts privés n'y apparaissent jamais par leur nom.
WEB_PUBLIC_STATUS=true
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
WEB_ALLOW_COMMAND_DEPLOYS=false
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
WEB_ALLOW_RESTART=false
WEB_DEPLOY_TIMEOUT_MS=900000
WEB_RATE_LIMIT_PER_MINUTE=240
# --- SQLite (M1-T05) ---------------------------------------------------------
DATABASE_PATH=./data/fws-bot.sqlite
BACKUP_DIR=./data/backups
# --- FWS links (M0-T06 / M4-T04) ---------------------------------------------
FWS_WEBSITE_URL=
FWS_DOCS_URL=
FWS_DISCORD_INVITE_URL=
FWS_ARCH_REPO_URL=
+35
View File
@@ -0,0 +1,35 @@
name: CI
# Lint and tests on every push and every pull request. `format:check` is
# deliberately absent: the repository still holds CRLF files that predate the
# Prettier configuration, so the step would fail on untouched code. Normalise
# the line endings in a commit of their own, then add it here.
on:
push:
branches: [main]
pull_request:
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- name: Installer les dépendances
run: npm ci
- name: Lint
run: npm run lint
- name: Tests
run: npm test
# The changelog is generated from the commit history, so a stale one is
# a real defect rather than a formatting detail.
- name: Changelog à jour
run: npm run changelog:check
+52 -52
View File
@@ -1,52 +1,52 @@
# Dependencies # Dependencies
node_modules/ node_modules/
# Environment and secrets # Environment and secrets
.env .env
.env.* .env.*
!.env.example !.env.example
# Development assistant data (never committed) # Development assistant data (never committed)
.freebuff/ .freebuff/
.cursor/ .cursor/
# SQLite databases and backups # SQLite databases and backups
data/* data/*
!data/.gitkeep !data/.gitkeep
*.sqlite *.sqlite
*.sqlite3 *.sqlite3
*.db *.db
*.db-journal *.db-journal
*-wal *-wal
*-shm *-shm
# Logs # Logs
logs/* logs/*
!logs/.gitkeep !logs/.gitkeep
*.log *.log
npm-debug.log* npm-debug.log*
# Build and coverage # Build and coverage
dist/ dist/
build/ build/
coverage/ coverage/
.cache/ .cache/
# Compiled artefacts of the other toolchains used across FWS projects # Compiled artefacts of the other toolchains used across FWS projects
target/ target/
__pycache__/ __pycache__/
*.pyc *.pyc
*.pyo *.pyo
*.o *.o
*.so *.so
*.exe *.exe
*.dll *.dll
# Editors and OS # Editors and OS
# `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions # `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions
# shared by the project. Everything else in the folder is personal. # shared by the project. Everything else in the folder is personal.
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
.idea/ .idea/
.DS_Store .DS_Store
Thumbs.db Thumbs.db
+5 -5
View File
@@ -1,5 +1,5 @@
node_modules/ node_modules/
data/ data/
logs/ logs/
package-lock.json package-lock.json
README.md README.md
+6 -6
View File
@@ -1,6 +1,6 @@
{ {
"singleQuote": true, "singleQuote": true,
"trailingComma": "all", "trailingComma": "all",
"printWidth": 110, "printWidth": 110,
"semi": true "semi": true
} }
+53
View File
@@ -7,6 +7,30 @@ The project follows [Semantic Versioning](https://semver.org/).
## [Unreleased] ## [Unreleased]
### Features ### Features
- **web:** _(feat)_ publish a public status page at /status ([a1e1de7])
- **web:** _(feat)_ search the whole panel from one place ([9acb523])
- **projects:** _(feat)_ gather the cards one member carries ([fcc82d8])
- **projects:** _(feat)_ pull Gitea issues onto any board ([1c21f6f])
- **wiki:** _(feat)_ serve the legal pages at /terms-of-service and /privacy-policy ([3d0e21d])
- **projects:** _(feat)_ add the board interface ([e1b9a5c])
- **projects:** _(feat)_ add a Kanban board per repository and one for the organization ([901ca56])
- **web:** _(feat)_ open a repository from anywhere on its row ([95b51ab])
- **wiki:** _(feat)_ add the reading site and its editor ([e5b7303])
- **wiki:** _(feat)_ serve a public documentation written from the panel ([c76c0b9])
- **web:** _(feat)_ publish the slash commands from the panel ([2622744])
- **voice:** _(feat)_ take back the generated channels the database forgot ([b42fb10])
- **settings:** _(feat)_ make the server settings real, and widen them ([406b5af])
- **web:** _(feat)_ make deploying reachable from where it is looked for ([d439b1b])
- **web:** _(feat)_ refresh the pages as the events arrive ([5481e79])
- **web:** _(feat)_ push live updates to the dashboard ([df89cc5])
- **web:** _(feat)_ serve the dashboard and its interface ([06a9be0])
- **web:** _(feat)_ expose the dashboard API ([bf92bad])
- **web:** _(feat)_ run and record release deployments ([611129b])
- **web:** _(feat)_ read, validate and write the .env configuration ([efaaca3])
- **web:** _(feat)_ add the HTTP layer and Discord-backed sessions ([e03b184])
- **database:** _(feat)_ store dashboard sessions, deploy targets and deployments ([5abe713])
- **gitea:** _(feat)_ add an organization and repository administration client ([4b0737a])
- **config:** _(feat)_ declare the web dashboard environment variables ([e4534d4])
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a]) - **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269]) - **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea]) - **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
@@ -66,7 +90,36 @@ The project follows [Semantic Versioning](https://semver.org/).
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe]) - **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
- **config:** _(feat)_ load and expose environment settings ([d1388b6]) - **config:** _(feat)_ load and expose environment settings ([d1388b6])
### Bug Fixes
- **wiki:** _(fix)_ render the public pages on the server ([8869c74])
- **web:** _(fix)_ stop caching the interface modules ([3f4a570])
- **web:** _(fix)_ keep the stack when a view fails ([c031b4d])
- **web:** _(fix)_ read the interface build date instead of freezing it at startup ([92c27ae])
- **web:** _(fix)_ stop the settings page breaking on an unexpected payload ([75d1e53])
- **web:** _(fix)_ give static assets a validator caches can check ([539b150])
- **web:** _(fix)_ say when the dashboard is disabled ([3bd290c])
- **web:** _(fix)_ say out loud when the dashboard cannot listen ([afcd0e5])
- **config:** _(fix)_ warn when a public address is announced but only loopback is bound ([40032ec])
- **web:** _(fix)_ make the whole repository card open the repository ([e397abc])
- **web:** _(fix)_ pin the sidebar highlight to the route, and name the build ([a44ff0c])
- **web:** _(fix)_ always offer the bootstrap token on the sign-in page ([9c6297e])
- **web:** _(fix)_ let a deploy target be created without a reachable Gitea ([ff15dfe])
- **web:** _(fix)_ keep the sidebar in step with the page being shown ([a0428e0])
- **web:** _(fix)_ derive the OAuth2 redirect from the address actually used ([20ff701])
- **notifications:** _(fix)_ apply the channel overrides set from Discord ([92405ac])
### Other changes ### Other changes
- **web:** _(docs)_ document my tasks, the search and the status page ([566af4d])
- **web:** _(refactor)_ extract the build marker into its own module ([d2256e2])
- **ops:** _(docs)_ correct the deployment path for a panel without a shell ([e3ce266])
- **ops:** _(docs)_ document deployment, CI, monitoring and backups ([1643fcb])
- **web:** _(test)_ lock the sidebar highlighting behind tests ([b793298])
- **web:** _(docs)_ document the wiki, the settings and the command publishing ([5660235])
- **web:** _(style)_ adopt the official FWS mark and its palette ([621f3e4])
- **web:** _(docs)_ document the live updates ([2083133])
- **web:** _(docs)_ document the dashboard and the configuration wizard ([e63d6aa])
- **web:** _(test)_ cover the router, configuration, auth, deployments and server ([bd7fdea])
- **all:** _(refactor)_ uniformisation ([50665c8])
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb]) - **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41]) - **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2]) - **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
+540 -473
View File
File diff suppressed because it is too large. Load diff
+545 -473
View File
File diff suppressed because it is too large. Load diff
+112 -88
View File
@@ -1,88 +1,112 @@
# Architecture — FWS-Bot # Architecture — FWS-Bot
Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler). Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler).
## Arborescence ## Arborescence
```text ```text
fws-discordbot/ fws-discordbot/
├── .env.example # Modèle de configuration (sans secret) ├── .env.example # Modèle de configuration (sans secret)
├── assets/screenshots/ # Captures référencées dans la documentation ├── assets/screenshots/ # Captures référencées dans la documentation
├── data/ # Base SQLite et sauvegardes (ignoré par git) ├── data/ # Base SQLite et sauvegardes (ignoré par git)
├── docs/ # Documentation technique ├── docs/ # Documentation technique
├── logs/ # Logs techniques journaliers (ignoré par git) ├── logs/ # Logs techniques journaliers (ignoré par git)
├── scripts/ ├── scripts/
│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur │ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur
│ └── init-database.js # Crée la base et applique les migrations │ ├── init-database.js # Crée la base et applique les migrations
├── src/ │ └── setup-server.js # Assistant de configuration du .env, sans Discord
│ ├── index.js # Point d'entrée ├── src/
│ ├── config/ │ ├── index.js # Point d'entrée
│ │ ├── env.js # Lecture et validation des variables d'environnement │ ├── config/
│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets │ │ ├── env.js # Lecture et validation des variables d'environnement
│ ├── core/ │ │ ├── guild-settings.js # Réglages modifiables depuis le panel, et leur schéma
│ │ ├── client.js # Client Discord et intents │ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets
│ │ ├── command-loader.js # Chargement automatique de src/commands/** │ ├── core/
│ │ ├── event-loader.js # Chargement automatique de src/events/* │ │ ├── client.js # Client Discord et intents
│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie │ │ ├── command-loader.js # Chargement automatique de src/commands/**
│ │ ├── logger.js # Logs JSON avec masquage des secrets │ │ ├── event-loader.js # Chargement automatique de src/events/*
│ │ └── errors.js # Erreurs typées (utilisateur, permission, API) │ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie
│ ├── commands/<catégorie>/<commande>.js │ │ ├── logger.js # Logs JSON avec masquage des secrets
│ ├── events/ # Un fichier par événement Discord │ │ └── errors.js # Erreurs typées (utilisateur, permission, API)
│ ├── services/ # Logique métier et intégrations (Gitea, notifications…) │ ├── commands/<catégorie>/<commande>.js
│ ├── database/ │ ├── events/ # Un fichier par événement Discord
│ │ ├── index.js # Connexion et migrations │ ├── services/ # Logique métier et intégrations (Gitea, notifications…)
│ │ ├── migrations/ # Fichiers SQL numérotés │ ├── database/
│ │ └── repositories/ # Accès aux tables │ │ ├── index.js # Connexion et migrations
│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea │ │ ├── migrations/ # Fichiers SQL numérotés
│ ├── ui/ # Embeds et boutons standardisés │ │ └── repositories/ # Accès aux tables
│ └── utils/ # Retry, cooldown… │ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea
└── tests/ # Tests node:test │ ├── web/ # Tableau de bord : serveur, API, front (voir web-dashboard.md)
``` │ │ ├── server.js # Serveur HTTP, répartition et erreurs
│ │ ├── router.js # Routeur minimal `/api/x/:param`
## Contrat d'une commande │ │ ├── auth/ # OAuth2 Discord, sessions, contrôle d'accès
│ │ ├── api/ # Un module par domaine exposé
```js │ │ ├── services/ # Schéma du .env, écriture du fichier, déploiements
export const access = ACCESS_LEVELS.STAFF; // niveau minimum │ │ ├── public/ # Front JavaScript natif, servi tel quel
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel │ │ └── public/wiki.* # Site de documentation public, servi sans session
export const data = new SlashCommandBuilder()...; │ ├── ui/ # Embeds et boutons standardisés
export async function execute(interaction) {} │ └── utils/ # Retry, cooldown…
``` └── tests/ # Tests node:test
```
Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique.
## Contrat d'une commande
## Contrat d'un événement
```js
```js export const access = ACCESS_LEVELS.STAFF; // niveau minimum
export const name = Events.GuildMemberAdd; export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel
export const once = false; // optionnel export const data = new SlashCommandBuilder()...;
export async function execute(client, ...args) {} export async function execute(interaction) {}
``` ```
## Intents Discord Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique.
| Intent | Usage | Privilégié | ## Contrat d'un événement
| ----------------- | -------------------------------- | ----------------------------------- |
| `Guilds` | Commandes, salons, rôles | Non | ```js
| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) | export const name = Events.GuildMemberAdd;
| `GuildModeration` | Événements de ban | Non | export const once = false; // optionnel
| `GuildMessages` | `/clear`, salons de tickets | Non | export async function execute(client, ...args) {}
```
`MessageContent` n'est pas demandé.
## Tableau de bord web
## Lancement local
Le bot sert un site d'administration (organisation, dépôts, releases, déploiements, configuration). Il réutilise les niveaux d'accès des commandes, déduits des rôles Discord, et ne démarre que si `WEB_ENABLED=true`.
```bash
npm install Aucune dépendance ajoutée : `node:http`, `node:sqlite`, `node:crypto`, et un front sans étape de build. Quand `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP sert le site et la route des webhooks.
cp .env.example .env # puis remplir les valeurs
npm run db:init Une route se déclare avec son niveau minimum, appliqué par le serveur avant l'appel :
npm run deploy:commands
npm run dev ```js
``` router.get('/api/repositories/:owner/:repo', handler, { access: ACCESS_LEVELS.STAFF });
```
## Qualité
Détail complet : [`web-dashboard.md`](web-dashboard.md).
| Commande | Rôle |
| ---------------------- | ----------------- | ## Intents Discord
| `npm run lint` | ESLint |
| `npm run format:check` | Prettier | | Intent | Usage | Privilégié |
| `npm test` | Tests `node:test` | | ----------------- | -------------------------------- | ----------------------------------- |
| `Guilds` | Commandes, salons, rôles | Non |
| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) |
| `GuildModeration` | Événements de ban | Non |
| `GuildMessages` | `/clear`, salons de tickets | Non |
`MessageContent` n'est pas demandé.
## Lancement local
```bash
npm install
npm run setup # assistant de configuration du .env, ou copier .env.example à la main
npm run db:init
npm run deploy:commands
npm run dev
```
## Qualité
| Commande | Rôle |
| ---------------------- | ----------------- |
| `npm run lint` | ESLint |
| `npm run format:check` | Prettier |
| `npm test` | Tests `node:test` |
+305
View File
@@ -0,0 +1,305 @@
# Exploitation
Comment déployer, vérifier, surveiller et sauvegarder FWS-Bot en production. Écrit pour un hébergement de type panel (Pterodactyl), qui est le cas actuel.
Les quatre chapitres sont indépendants et classés par valeur décroissante.
---
## 1. Déployer sans archive
**Le problème qu'on résout.** Téléverser un zip laisse régulièrement une copie partielle : le front plus ancien que l'API, un module oublié, une page qui plante sans raison apparente. Trois symptômes pour une seule cause, et aucun moyen simple de savoir laquelle.
Un déploiement reproductible supprime toute la famille.
> **L'onglet « Console » de Pterodactyl n'est pas un terminal** : c'est l'entrée/sortie du processus en cours. On n'y lance pas de commande shell, même avec tous les droits du panel. Si tu disposes d'un vrai shell ailleurs, suis le point 1.0 ; sinon, tout se fait depuis le tableau de bord, à partir du point 1.1.
### 1.0 Si tu as un accès shell
Assure-toi d'abord d'être **sur le bon système de fichiers** — celui que le bot lit. Un `git pull` au mauvais endroit ne produit aucune erreur et ne change rien, ce qui est le plus trompeur des résultats :
```bash
cd /home/container
ls package.json src/index.js .env && echo "bon endroit"
```
Si cette commande échoue, ton shell ne voit pas le conteneur du bot : passe au point 1.1.
Sinon, l'amorçage se fait directement :
```bash
cp .env .env.sauvegarde && tar czf data-sauvegarde.tgz data/
git init
git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git
git fetch origin main
git reset --hard origin/main
npm ci --omit=dev
```
Puis saute au point 1.3 pour déclarer la cible de production, qui te permettra de déployer d'un clic depuis le tableau de bord plutôt que de revenir ici à chaque fois.
> ⚠️ Ne lance **jamais** `git clean -fd` dans ce dossier : il effacerait `.env` et la base.
### 1.1 Autoriser l'exécution de commandes
**Tableau de bord → Configuration .env → Tableau de bord web** (niveau Owner) :
| Variable | Valeur |
| --------------------------- | ------ |
| `WEB_ALLOW_COMMAND_DEPLOYS` | `true` |
| `WEB_ALLOW_RESTART` | `true` |
Enregistre, puis redémarre le bot depuis le panel. Ces deux valeurs ne sont lues qu'au démarrage.
> Elles permettent d'exécuter une commande sur la machine du bot depuis un navigateur — une exécution de code arbitraire. Réservées au niveau Owner, désactivées par défaut. N'ouvre l'accès Owner qu'à des personnes de confiance.
### 1.2 Amorcer le clone sans shell
Si le point 1.0 ne s'applique pas : le dossier du conteneur contient aujourd'hui une archive décompressée, pas un dépôt. On le convertit avec une cible jetable, exécutée par le bot lui-même.
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| --------------------- | -------------------------------- |
| Nom | `amorçage` |
| Dépôt | `FWS/fws-discordbot` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | voir ci-dessous |
```bash
git init && git remote add origin https://gitea.nocode-var.tech/FWS/fws-discordbot.git && git fetch origin main && git reset --hard origin/main
```
Clique **Déployer**, puis lis le journal dans l'historique. Deux cas d'échec :
- **`git: not found`** — l'image du conteneur n'a pas git. Utilise la variante sans git du point 1.5.
- **authentification refusée** — le dépôt est privé. Remplace l'URL par `https://<utilisateur>:<jeton>@gitea.nocode-var.tech/FWS/fws-discordbot.git`. Le jeton est alors stocké dans la configuration de la cible, en base : utilise un jeton dédié, en lecture seule.
`git reset --hard` écrase les fichiers **suivis**. Ton `.env` et ton dossier `data/` sont ignorés par git, donc intacts.
> ⚠️ N'ajoute **jamais** `git clean -fd` à cette commande : elle effacerait `.env` et la base.
Supprime ensuite la cible `amorçage` : elle ne sert qu'une fois.
### 1.3 Déclarer la cible de production
**Déploiements → Nouvelle cible**
| Champ | Valeur |
| ----------------------- | ---------------------------------------------------------------------------- |
| Nom | `production` |
| Dépôt | `FWS/fws-discordbot` |
| Environnement | `production` |
| Type | Commande shell sur l'hôte du bot |
| Répertoire de travail | `/home/container` |
| Commande | `git fetch origin main && git reset --hard origin/main && npm ci --omit=dev` |
| Déploiement automatique | à activer si tu veux qu'une release publiée déploie seule |
### 1.4 Le cycle courant
1. **Déploiements → Déployer** sur `production`. Le journal complet est conservé, réussite comme échec.
2. **Paramètres → Redémarrer le bot** — le code n'est relu qu'au démarrage.
Contrôle, depuis n'importe où :
```bash
curl -s http://node01.zi-host.ch:25571/api/health
```
`buildAt` doit refléter ton dernier commit. C'est le seul indicateur fiable de ce qui tourne réellement.
### 1.5 Si le conteneur n'a pas git
Gitea sert une archive de n'importe quelle branche. La commande devient :
```bash
curl -sL -H "Authorization: token TON_JETON" https://gitea.nocode-var.tech/api/v1/repos/FWS/fws-discordbot/archive/main.tar.gz | tar xz --strip-components=1 && npm ci --omit=dev
```
Moins bien que git — pas d'historique, pas de moyen de savoir ce qui a changé — mais reproductible, et suffisant pour supprimer le téléversement à la main.
### Ce qu'il faut savoir
- `npm ci --omit=dev` n'installe ni ESLint, ni Prettier, ni de quoi lancer les tests. C'est voulu : ils tournent en intégration continue (chapitre 2), pas en production.
- Si ton egg Pterodactyl réinstalle les fichiers au démarrage, il écrasera le clone. Vérifie l'option _Auto-update / Reinstall on boot_ et désactive-la.
- Les migrations de base s'appliquent toutes seules au démarrage : rien à lancer.
- Tout ce chapitre reste faisable en **SFTP** si tu préfères : le panel en donne les identifiants, et un client comme FileZilla remplace le téléversement par zip. Mais tu restes exposé à la copie partielle, que le déploiement par commande supprime.
---
## 2. Faire tourner les tests avant de déployer
**Le problème qu'on résout.** 301 tests et un lint existent, et ne tournent jamais avant une mise en production. Un déplacement de cartes cassé est passé inaperçu jusqu'à ce qu'un test l'attrape — après coup.
Le fichier de workflow est déjà dans le dépôt : [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml). Il reste à donner un exécuteur à Gitea.
### 2.1 Activer Actions sur l'instance
Côté administration Gitea, dans `app.ini` :
```ini
[actions]
ENABLED = true
```
Puis redémarrer Gitea. Si l'instance ne t'appartient pas, c'est à demander à son administration.
### 2.2 Enregistrer un exécuteur
**Dépôt → Settings → Actions → Runners → Create new runner** te donne un jeton d'enregistrement.
Sur une machine qui a Docker et qui joint ton Gitea — ton poste, un VPS, ou le nœud lui-même :
```bash
curl -sL -o act_runner \
https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64
chmod +x act_runner
./act_runner register --no-interactive \
--instance https://gitea.nocode-var.tech \
--token <JETON_DENREGISTREMENT> \
--name fws-runner \
--labels ubuntu-latest:docker://node:22-bookworm
./act_runner daemon
```
Sans Docker, remplace l'étiquette par `ubuntu-latest:host` — les tâches s'exécutent alors directement sur la machine, qui doit avoir Node 22.
Pour qu'il survive à un redémarrage, place-le en service systemd ou en conteneur `--restart=always`.
### 2.3 Vérifier
Pousse une branche : l'onglet **Actions** du dépôt montre le résultat, et la pull request affiche son état.
### Pourquoi `format:check` n'est pas dans le workflow
Le dépôt contient encore des fichiers en CRLF antérieurs à la configuration Prettier. L'étape échouerait sur du code que personne n'a touché.
Pour l'ajouter : normalise les fins de ligne dans un commit dédié (`refactor(all): normalise les fins de ligne`), puis ajoute l'étape. Tant que ce n'est pas fait, l'absence est volontaire.
---
## 3. Savoir que le bot est tombé
**Le problème qu'on résout.** Une soirée passée à chercher pourquoi le site ne répondait plus, alors qu'une sonde aurait répondu en trente secondes.
Le bot expose déjà tout ce qu'il faut :
```json
GET /api/health
{ "status": "ok", "version": "0.1.0", "buildAt": "…", "uptimeMs": 106470 }
```
### 3.1 Surveiller depuis l'extérieur
Un bot ne peut pas signaler sa propre mort : il faut une sonde **externe**. [Uptime Kuma](https://github.com/louislam/uptime-kuma) est léger et sait écrire sur Discord.
```bash
docker run -d --restart=always -p 3001:3001 \
-v uptime-kuma:/app/data --name uptime-kuma louislam/uptime-kuma:1
```
Puis, dans son interface :
| Réglage | Valeur |
| ------------ | ------------------------------------------- |
| Type | HTTP(s) - Keyword |
| URL | `http://node01.zi-host.ch:25571/api/health` |
| Mot-clé | `"status":"ok"` |
| Intervalle | 60 s |
| Notification | Webhook Discord vers ton salon de logs |
> **Surveille l'origine, pas le domaine public.** Cloudflare renvoie un challenge à toute requête non-navigateur : une sonde sur `https://fws-bot.laxacube.ch` signalerait une panne permanente qui n'existe pas.
Le mot-clé compte : une page qui répond `200` mais sans `"status":"ok"` n'est pas un bot en bonne santé.
### 3.2 Une page que les autres peuvent lire
`/status` répond sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue côté serveur, sans JavaScript, et se rafraîchit toute seule.
C’est l’adresse à donner à la communauté quand quelqu’un demande « c’est en panne ou c’est moi ? ».
`/api/status` en donne la version JSON. Elle vaut mieux que `/api/health` pour une sonde qui affiche un tableau de bord :
```json
GET /api/status
{ "bot": { "online": true, "pingMs": 42, "version": "0.1.0" },
"environments": [ { "environment": "production", "status": "success", "tone": "ok" } ],
"releases": [ … ] }
```
`WEB_PUBLIC_STATUS=false` désactive les deux. Un dépôt privé n’apparaît jamais par son nom sur la page publique.
### 3.3 Ce que le bot surveille déjà lui-même
- Chaque déploiement, réussi ou non, est annoncé sur Discord et consigné avec son journal.
- Les erreurs d'appel Gitea partent dans le salon `errors`.
- **Paramètres → Tester la connexion** vérifie Discord et Gitea à la demande.
Ça couvre les pannes partielles. Ça ne couvre pas un processus mort — d'où le point 3.1.
---
## 4. Sauvegarder hors du conteneur
**Le problème qu'on résout.** Le bouton _Sauvegarder la base_ écrit dans `data/backups`, **à l'intérieur du conteneur**. Une reconstruction efface les deux. C'est déjà arrivé : les salons vocaux orphelins venaient d'une base repartie de zéro.
### 4.1 Sauvegardes du panel (le plus simple)
Pterodactyl sait archiver le serveur entier, hors conteneur.
**Panel → Schedules → Create schedule**
| Réglage | Valeur |
| ------- | ----------------------- |
| Nom | Sauvegarde hebdomadaire |
| Cron | `0 4 * * 1` (lundi 4 h) |
| Tâche | _Create backup_ |
Les archives apparaissent dans l'onglet **Backups**, avec téléchargement. Vérifie la limite d'archives de ton offre.
### 4.2 Instantané cohérent de la base
Une archive de fichiers peut attraper la base en cours d'écriture. Le bot, lui, produit une copie cohérente (`VACUUM INTO`), même journal WAL actif.
Crée un jeton dans **Paramètres → Jetons d'API** (niveau Owner), puis, depuis une machine qui tourne en permanence :
```bash
# Chaque nuit à 3 h
0 3 * * * curl -sS -X POST -H "Authorization: Bearer fws_…" \
http://node01.zi-host.ch:25571/api/settings/backup
```
Le fichier atterrit dans `BACKUP_DIR`, que la sauvegarde du panel emporte ensuite.
### 4.3 Vraiment hors site
Une sauvegarde chez le même hébergeur ne protège pas d'un incident chez lui. Depuis une machine qui a l'accès SFTP du panel :
```bash
rclone sync sftp-panel:/home/container/data backblaze:fws-bot-backups \
--backup-dir backblaze:fws-bot-backups/anciens/$(date +%F)
```
### 4.4 Tester la restauration
Une sauvegarde jamais restaurée n'est pas une sauvegarde. Une fois :
```bash
cp fws-bot-2026-09-24.sqlite /tmp/test.sqlite
DATABASE_PATH=/tmp/test.sqlite npm run db:init
```
La commande doit se terminer sans erreur et appliquer les migrations.
---
## Dans quel ordre
1. **Chapitre 1** — supprime une famille entière de pannes, ne demande que de la configuration.
2. **Chapitre 2** — évite de découvrir un bug en production.
3. **Chapitre 4** — protège ce qui n'est pas remplaçable.
4. **Chapitre 3** — utile, mais vient après ce qui empêche les pannes plutôt que ce qui les signale.
+297
View File
@@ -0,0 +1,297 @@
# Tableau de bord web
Le bot sert lui-même un site d'administration : pilotage de l'organisation Gitea et de ses dépôts, gestion du serveur Discord, pipeline de releases et de déploiements, et un assistant qui écrit le fichier `.env` pas à pas.
Aucune dépendance supplémentaire : `node:http` pour le serveur, `node:sqlite` pour les sessions, `node:crypto` pour les signatures, et un front en JavaScript natif servi tel quel (pas d'étape de build).
## 1. Démarrer
### Première installation, sans `.env`
Le bot refuse de démarrer sans `DISCORD_TOKEN`. L'assistant de configuration se lance donc seul :
```bash
npm install
npm run setup
```
La console affiche l'URL et un jeton d'amorçage à usage unique. Ouvre l'URL, colle le jeton, déroule l'assistant, enregistre. Puis :
```bash
npm run db:init
npm run deploy:commands
npm run dev
```
### Site complet, bot configuré
Mets `WEB_ENABLED=true` dans le `.env`, puis `npm start`. Le site écoute sur `WEB_HOST:WEB_PORT` (par défaut `127.0.0.1:3080`).
Pour que les membres puissent se connecter avec Discord :
1. Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.
2. Toujours dans **OAuth2 → Redirects**, ajoute `<WEB_PUBLIC_URL>/auth/callback`, à l'identique.
3. Génère `WEB_SESSION_SECRET` (l'assistant a un bouton pour ça).
## 2. Qui a accès à quoi
Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles Discord. Se connecter demande au minimum le niveau **Staff**.
| Niveau | Peut |
| --------- | --------------------------------------------------------------------------------------------------------- |
| **Staff** | Tout consulter, créer des issues, commenter, modérer, clôturer des tickets, publier une annonce |
| **Dev** | En plus : modifier les dépôts, merger, gérer branches et releases, lancer un déploiement, gérer les rôles |
| **Owner** | En plus : supprimer un dépôt, gérer collaborateurs et webhooks, jetons d'API, sauvegardes, `.env` |
Un membre sans rôle Staff, Dev ou Owner ne peut pas ouvrir le site. Le propriétaire du serveur Discord est toujours Owner.
### Modes Simple et Avancé
Le commutateur en bas de la barre latérale masque ou révèle les panneaux techniques (identifiants bruts, journaux, réglages fins, colonnes secondaires). Le mode est retenu par navigateur, et n'a aucun effet sur les droits réels : le serveur vérifie chaque appel de son côté.
## 3. Les pages
| Page | Contenu |
| ---------------------- | ----------------------------------------------------------------------------------------------- |
| **Vue d'ensemble** | État du bot, du serveur Discord, de l'organisation, activité, derniers événements |
| **Mes tâches** | Les cartes qui te sont assignées, tous tableaux confondus, la plus urgente en premier |
| **Organisation** | Identité Gitea, membres, équipes, inventaire des dépôts, création de dépôt |
| **Dépôts** | Un dépôt en détail : issues, PR, commits, branches, collaborateurs, webhooks, Actions, réglages |
| **Releases** | Publier une version, générer ses notes depuis les commits, suivre les déploiements déclenchés |
| **Déploiements** | Cibles de déploiement et historique complet, avec le journal de chaque exécution |
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
| **Paramètres** | Comportement du bot, connexions, sessions, jetons d'API, maintenance |
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
## 4. Assistant de configuration
Le fichier `src/web/services/env-schema.js` décrit **chaque** variable : libellé, explication, type, valeur par défaut, marche à suivre pour l'obtenir. L'assistant, la validation et le `.env` généré en découlent tous. Ajouter une variable au bot, c'est l'ajouter là et nulle part ailleurs.
L'assistant :
- explique chaque étape (où cliquer dans le Developer Portal, quelles portées cocher dans Gitea) ;
- valide au fil de la frappe et signale les combinaisons douteuses (webhooks sans secret, site exposé sans HTTPS) ;
- génère les secrets aléatoires sur demande ;
- teste le token Discord et le jeton Gitea **avant** d'écrire quoi que ce soit ;
- montre un aperçu du fichier et la liste des changements en attente ;
- sauvegarde l'ancien `.env` en `.env.bak-<horodatage>` puis écrit le nouveau en `chmod 600` ;
- conserve les variables qu'il ne connaît pas plutôt que de les perdre.
Un secret laissé vide signifie « garde la valeur actuelle » : impossible d'effacer un token par inadvertance. Les secrets ne repartent jamais vers le navigateur — seul leur statut (renseigné ou non) est envoyé.
Les valeurs du `.env` ne sont lues qu'au démarrage : l'assistant indique quelles modifications demandent un redémarrage.
## 5. Releases et déploiements
### Publier
Depuis la page **Releases** : choisis le dépôt, le tag et la branche cible. Le bouton **Générer les notes** lit les commits depuis la release précédente et les regroupe comme `scripts/generate-changelog.js` : nouveautés, corrections, performance, autres changements, avec un bloc « changements incompatibles » pour les commits marqués `!` ou `BREAKING CHANGE`.
Publier une release non brouillon annonce la version dans le salon `releases` et déclenche les cibles marquées « déploiement automatique ».
### Cibles de déploiement
| Type | Ce qui se passe | Risque |
| ----------------- | ----------------------------------------------------------------------- | ---------------------------------------- |
| **Webhook** | POST JSON signé HMAC-SHA256 vers ton serveur, en-tête `X-FWS-Signature` | Faible — rien ne s'exécute chez le bot |
| **Gitea Actions** | Déclenche un workflow `workflow_dispatch` | Faible |
| **Commande** | Exécute une commande shell sur la machine du bot | **Élevé** — exécution de code arbitraire |
Les cibles « commande » sont doublement verrouillées : `WEB_ALLOW_COMMAND_DEPLOYS=true` **et** niveau Owner. Elles restent désactivées par défaut.
Corps envoyé à un webhook :
```json
{
"deploymentId": 12,
"repository": "FWS/FWS-Arch",
"environment": "production",
"target": "production-web",
"ref": "main",
"releaseTag": "v1.2.0",
"triggeredBy": "123456789012345678",
"source": "web"
}
```
Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en hexadécimal, comparé en temps constant.
Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec).
## 6. Mise à jour automatique
Les pages suivent le bot en direct : aucun rafraîchissement manuel n'est nécessaire.
Le serveur tient un flux `text/event-stream` sur `GET /api/events`, un par onglet ouvert. Il y publie :
- **chaque écriture réussie** de l'API, étiquetée selon la page concernée (`deployments`, `gitea`, `discord`, `community`, `settings`) — une écriture rejetée ne déclenche rien ;
- **l'avancement des déploiements**, au démarrage puis à l'arrivée du résultat ;
- **les webhooks Gitea** reçus, dès qu'ils sont validés ;
- un **tick** toutes les 15 secondes, et un battement de cœur toutes les 25 secondes qui empêche les proxys de fermer un flux inactif.
Côté navigateur, un seul `EventSource` sert tout le tableau de bord, et chaque page ne réagit qu'aux sujets qui la concernent. L'indicateur en bas de la barre latérale dit où en est la connexion.
Trois garde-fous, parce qu'un rafraîchissement qui tombe au mauvais moment est pire qu'une donnée un peu vieille :
- rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus — le rafraîchissement est rejoué ensuite ;
- une rafale d'écritures ne produit qu'un seul rechargement ;
- l'onglet en arrière-plan ferme son flux et le rouvre au retour.
Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — un rafraîchissement périodique prend le relais automatiquement, et l'indicateur passe en orange. La page Serveur Discord est volontairement hors du tick : lister les membres appelle l'API Discord, elle ne se rafraîchit que sur un vrai changement.
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
## 7. Trouver et suivre son travail
### Mes tâches
**Tableau de bord → Mes tâches** rassemble les cartes qui te sont assignées sur **tous** les tableaux, groupées par échéance : en retard, pour aujourd’hui, cette semaine, plus tard, sans date. Les cartes terminées sont repliées en bas.
- Le bouton rond à gauche d’une carte la déplace dans la colonne « terminé » de son tableau, sans quitter la page.
- Le compteur de la barre latérale indique le nombre de cartes ouvertes, en rouge dès qu’une est en retard.
- Le sélecteur en haut à droite permet de regarder la charge d’un autre membre, quand plusieurs personnes portent des cartes.
Une carte n’apparaît ici que si elle a un **assigné**. C’est le seul champ qui compte pour cette page.
### Recherche globale
**⌘K** (ou **Ctrl+K**, ou la barre « Rechercher ») ouvre une recherche unique sur :
| Source | Où elle mène | D’où elle vient |
| ----------- | -------------------------------------- | ------------------------- |
| Pages | L’onglet correspondant | Le navigateur, sans appel |
| Cartes | Le tableau qui la porte | La base locale |
| Dépôts | La fiche du dépôt | Gitea, en cache 60 s |
| Issues / PR | Gitea, dans un onglet | Gitea |
| Wiki | La page publique | La base locale |
| Membres | L’onglet Discord, recherche préremplie | Le cache du bot |
Les pages sont filtrées dans le navigateur : la palette répond avant même d’avoir interrogé le serveur, et reste utile si Gitea ne répond pas. Une source qui échoue est simplement absente des résultats.
Les flèches naviguent, **Entrée** ouvre, **Échap** ferme. Une page à laquelle tu n’as pas accès n’apparaît jamais dans les résultats.
### Page de statut publique
**`/status`** est lisible sans compte : état du bot, latence Discord, dernier déploiement par environnement, dernières releases. Elle est rendue **côté serveur, sans une seule ligne de JavaScript**, et s’actualise par une balise `meta refresh` — une page de statut qui a besoin d’un navigateur moderne pour dire qu’il y a une panne est une page inutile au moment où elle sert.
Deux garde-fous, parce que la page est publique :
- Un dépôt que Gitea ne liste pas comme public apparaît **sans son nom** : l’environnement reste visible, le dépôt non.
- La bannière annonce toujours le pire état vrai. Un déploiement en échec empêche l’en-tête vert, même si le bot répond.
`WEB_PUBLIC_STATUS=false` la désactive entièrement ; `/status` renvoie alors 404, comme `/api/status`.
`/api/status` donne la même chose en JSON, sans session : c’est ce qu’une sonde de supervision doit interroger, plutôt que `/api/health` qui ne dit que « le processus vit ».
## 8. Wiki public
Le bot sert une documentation publique sur **`/wiki`**, lisible sans compte, écrite depuis **Tableau de bord → Wiki**.
- Les pages sont rédigées en Markdown, avec un aperçu en direct dans l'éditeur.
- Une page reste en **brouillon** tant qu'elle n'est pas publiée ; un brouillon renvoie 404 même si on devine son adresse.
- Les pages sont regroupées par **catégorie** et ordonnées par **position**.
- La recherche porte sur les titres, les résumés et le contenu des pages publiées.
Le rendu Markdown échappe le HTML **avant** toute transformation et refuse les liens `javascript:`. Les pages sont écrites par l'équipe, mais un moteur qui compte là-dessus est à une erreur près d'être une faille.
### Pages légales
Au premier démarrage, trois pages sont créées : un accueil et deux pages **protégées** — **Conditions d'utilisation** et **Politique de confidentialité**. Elles sont modifiables mais pas supprimables : un bot qui traite des données personnelles doit pouvoir montrer ses conditions.
La politique de confidentialité est rédigée selon la **LPD suisse révisée** (RS 235.1, en vigueur depuis le 1ᵉʳ septembre 2023) et décrit ce que ce code stocke réellement, table par table. Les mentions entre crochets — responsable du traitement, adresse, hébergeur — doivent être complétées, et l'ensemble relu par une personne compétente avant publication.
Une page supprimée par erreur est recréée au démarrage suivant ; une page réécrite ne l'est jamais.
## 9. Réglages du serveur
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
## 10. Publier les commandes slash
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
## 11. Jetons d'API
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
```bash
curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview
```
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
## 12. Sécurité
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
- **Écritures.** Toute requête autre qu'une lecture exige l'en-tête `X-Requested-With: fws-dashboard`, que le navigateur ne peut pas forger depuis un autre site, plus une vérification de l'origine.
- **En-têtes.** CSP restreinte à `self`, `X-Frame-Options: DENY`, `nosniff`, aucune ressource tierce.
- **Limitation de débit.** `WEB_RATE_LIMIT_PER_MINUTE` requêtes par adresse IP et par minute.
- **Secrets.** Jamais renvoyés au navigateur, jamais écrits dans les logs (`maskSecrets`).
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
## 13. Fonctionnement interne
```text
src/web/
├── server.js # Serveur HTTP, répartition, gestion des erreurs, limitation de débit
├── router.js # Routeur : motifs `/api/x/:param`, 404 et 405
├── http.js # Réponses JSON, corps, cookies, fichiers statiques, en-têtes de sécurité
├── setup-state.js # Jeton d'amorçage de l'assistant
├── auth/
│ ├── discord-oauth.js # Flux OAuth2 et calcul du niveau d'accès
│ ├── session.js # Sessions signées, jetons d'API, protection anti-CSRF
│ ├── guard.js # Contrôle d'accès par route
│ └── routes.js # /auth/login, /auth/callback, /api/me
├── api/ # Un module par domaine fonctionnel
├── services/
│ ├── env-schema.js # Description documentée de chaque variable
│ ├── env-file.js # Lecture, rendu, sauvegarde et écriture du .env
│ ├── deploy-service.js # Exécution des déploiements et notifications
│ ├── build-info.js # Version et date de l’interface réellement servie
│ ├── wiki-seed.js # Pages créées au premier démarrage, adresses publiques
│ ├── wiki-render.js # Wiki rendu côté serveur
│ ├── status-service.js # Instantané public : bot, déploiements, releases
│ └── status-render.js # Page /status rendue côté serveur, sans script
└── public/ # Front servi tel quel (aucun build)
├── index.html
├── styles.css
├── app.js # Shell, navigation, routage par fragment
├── core/ # dom.js, api.js, ui.js, live.js, nav.js, palette.js
└── views/ # Une vue par page
```
Une route se déclare ainsi :
```js
router.get(
'/api/repositories/:owner/:repo',
async ({ params, query, body, actor, context }) => {
return { fullName: `${params.owner}/${params.repo}` };
},
{ access: ACCESS_LEVELS.STAFF },
);
```
Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le corps JSON, puis sérialise la valeur retournée. Une `HttpError` fixe le code ; une `UserFacingError` devient un 400 ; toute autre erreur est journalisée et remplacée par un message générique.
### Partage de port avec les webhooks
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
## 14. Dépannage
| Symptôme | Cause probable |
| ---------------------------------------------- | ------------------------------------------------------------------------------- |
| `state-mismatch` à la connexion | Cookies bloqués, ou plus de 10 minutes entre le clic et le retour |
| `exchange-failed` | L'URL de redirection du portail ne correspond pas exactement à `WEB_PUBLIC_URL` |
| `insufficient-level` | Le compte n'a ni rôle Staff, ni Dev, ni Owner sur le serveur |
| Déconnexion à chaque redémarrage | `WEB_SESSION_SECRET` n'est pas défini |
| « Gitea n'est pas configuré » | `GITEA_URL` ou `GITEA_TOKEN` manquant — teste le jeton depuis les paramètres |
| Onglet Actions vide | Gitea Actions désactivé sur le dépôt, ou Gitea antérieur à 1.20 |
| Les modifications du `.env` restent sans effet | Le fichier n'est lu qu'au démarrage : redémarre le bot |
+26 -21
View File
@@ -1,21 +1,26 @@
import js from '@eslint/js'; import js from '@eslint/js';
import prettier from 'eslint-config-prettier'; import prettier from 'eslint-config-prettier';
import globals from 'globals'; import globals from 'globals';
export default [ export default [
{ ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] }, { ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] },
js.configs.recommended, js.configs.recommended,
{ {
languageOptions: { languageOptions: {
ecmaVersion: 'latest', ecmaVersion: 'latest',
sourceType: 'module', sourceType: 'module',
globals: globals.node, globals: globals.node,
}, },
rules: { rules: {
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'prefer-const': 'error', 'prefer-const': 'error',
eqeqeq: ['error', 'always'], eqeqeq: ['error', 'always'],
}, },
}, },
prettier, {
]; // The dashboard front-end runs in the browser, not in Node (M16-T11).
files: ['src/web/public/**/*.js'],
languageOptions: { globals: globals.browser },
},
prettier,
];
+1443 -1443
View File
File diff suppressed because it is too large. Load diff
+35 -34
View File
@@ -1,34 +1,35 @@
{ {
"name": "fws-discordbot", "name": "fws-discordbot",
"version": "0.1.0", "version": "0.1.0",
"description": "FWS-Bot — Discord bot for the FWS open source organization", "description": "FWS-Bot — Discord bot for the FWS open source organization",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "src/index.js", "main": "src/index.js",
"engines": { "engines": {
"node": ">=22.13.0" "node": ">=22.13.0"
}, },
"scripts": { "scripts": {
"start": "node src/index.js", "start": "node src/index.js",
"dev": "node --watch src/index.js", "dev": "node --watch src/index.js",
"deploy:commands": "node scripts/deploy-commands.js", "setup": "node scripts/setup-server.js",
"db:init": "node scripts/init-database.js", "deploy:commands": "node scripts/deploy-commands.js",
"changelog": "node scripts/generate-changelog.js", "db:init": "node scripts/init-database.js",
"changelog:check": "node scripts/generate-changelog.js --check", "changelog": "node scripts/generate-changelog.js",
"lint": "eslint .", "changelog:check": "node scripts/generate-changelog.js --check",
"lint:fix": "eslint . --fix", "lint": "eslint .",
"format": "prettier --write .", "lint:fix": "eslint . --fix",
"format:check": "prettier --check .", "format": "prettier --write .",
"test": "node --test tests/" "format:check": "prettier --check .",
}, "test": "node --test tests/"
"dependencies": { },
"discord.js": "^14.21.0" "dependencies": {
}, "discord.js": "^14.21.0"
"devDependencies": { },
"@eslint/js": "^9.30.0", "devDependencies": {
"eslint": "^9.30.0", "@eslint/js": "^9.30.0",
"eslint-config-prettier": "^10.1.5", "eslint": "^9.30.0",
"globals": "^16.3.0", "eslint-config-prettier": "^10.1.5",
"prettier": "^3.6.2" "globals": "^16.3.0",
} "prettier": "^3.6.2"
} }
}
+13 -13
View File
@@ -1,13 +1,13 @@
import { REST, Routes } from 'discord.js'; import { REST, Routes } from 'discord.js';
import { assertRequiredEnv, env } from '../src/config/env.js'; import { assertRequiredEnv, env } from '../src/config/env.js';
import { loadCommands } from '../src/core/command-loader.js'; import { loadCommands } from '../src/core/command-loader.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']); assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
const body = (await loadCommands()).map((command) => command.data.toJSON()); const body = (await loadCommands()).map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token); const rest = new REST().setToken(env.discord.token);
// Guild commands update instantly, which suits a single-server bot (M2-T05). // Guild commands update instantly, which suits a single-server bot (M2-T05).
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body }); await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body });
console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`); console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`);
+172 -172
View File
@@ -1,172 +1,172 @@
#!/usr/bin/env node #!/usr/bin/env node
import { execFileSync } from 'node:child_process'; import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs'; import { readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
/** /**
* Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions * Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions
* require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are * require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are
* grouped under "Other changes". The file is generated, so run this script instead of editing it. * grouped under "Other changes". The file is generated, so run this script instead of editing it.
* *
* Usage: node scripts/generate-changelog.js [--check] * Usage: node scripts/generate-changelog.js [--check]
* --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests) * --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests)
*/ */
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const changelogPath = path.join(rootDir, 'CHANGELOG.md'); const changelogPath = path.join(rootDir, 'CHANGELOG.md');
const checkOnly = process.argv.includes('--check'); const checkOnly = process.argv.includes('--check');
/** Section order and titles; anything else falls into "Other changes". */ /** Section order and titles; anything else falls into "Other changes". */
const SECTIONS = [ const SECTIONS = [
{ title: 'Features', test: (type) => type === 'feat' }, { title: 'Features', test: (type) => type === 'feat' },
{ title: 'Bug Fixes', test: (type) => type === 'fix' }, { title: 'Bug Fixes', test: (type) => type === 'fix' },
{ title: 'Performance', test: (type) => type === 'perf' }, { title: 'Performance', test: (type) => type === 'perf' },
{ {
title: 'Other changes', title: 'Other changes',
test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf', test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf',
}, },
]; ];
const OTHER_LABELS = { const OTHER_LABELS = {
build: 'build', build: 'build',
chore: 'chore', chore: 'chore',
ci: 'ci', ci: 'ci',
docs: 'docs', docs: 'docs',
refactor: 'refactor', refactor: 'refactor',
revert: 'revert', revert: 'revert',
style: 'style', style: 'style',
test: 'test', test: 'test',
}; };
const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' }); const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' });
function readCommits() { function readCommits() {
// One record per commit, fields separated by unit separators so bodies stay readable. // One record per commit, fields separated by unit separators so bodies stay readable.
const raw = git([ const raw = git([
'log', 'log',
'--no-merges', '--no-merges',
'--date=short', '--date=short',
'--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e', '--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e',
// A commit that only rewrites the changelog must not appear in it, otherwise `--check` // A commit that only rewrites the changelog must not appear in it, otherwise `--check`
// could never be green once that file is committed. // could never be green once that file is committed.
'--', '--',
'.', '.',
':(exclude)CHANGELOG.md', ':(exclude)CHANGELOG.md',
]); ]);
return raw return raw
.split('\x1e') .split('\x1e')
.map((record) => record.trim()) .map((record) => record.trim())
.filter(Boolean) .filter(Boolean)
.map((record) => { .map((record) => {
const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f'); const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f');
const match = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/.exec( const match = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/.exec(
subject.trim(), subject.trim(),
); );
const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body); const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body);
return { return {
hash, hash,
date, date,
subject: subject.trim(), subject: subject.trim(),
type: match?.groups.type ?? 'other', type: match?.groups.type ?? 'other',
scope: match?.groups.scope ?? null, scope: match?.groups.scope ?? null,
description: match?.groups.description ?? subject.trim(), description: match?.groups.description ?? subject.trim(),
breaking, breaking,
tags: decoration tags: decoration
.split(',') .split(',')
.map((ref) => ref.trim().replace(/^tag: /, '')) .map((ref) => ref.trim().replace(/^tag: /, ''))
.filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)), .filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)),
}; };
}); });
} }
function entryLine(commit) { function entryLine(commit) {
const scope = commit.scope ? `**${commit.scope}:** ` : ''; const scope = commit.scope ? `**${commit.scope}:** ` : '';
const breaking = commit.breaking ? '**BREAKING** ' : ''; const breaking = commit.breaking ? '**BREAKING** ' : '';
const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `; const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `;
const detail = commit.type === 'other' ? commit.subject : commit.description; const detail = commit.type === 'other' ? commit.subject : commit.description;
return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`; return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`;
} }
/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */ /** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */
function groupByRelease(commits) { function groupByRelease(commits) {
const releases = []; const releases = [];
let current = { title: 'Unreleased', date: null, commits: [] }; let current = { title: 'Unreleased', date: null, commits: [] };
for (const commit of commits) { for (const commit of commits) {
current.commits.push(commit); current.commits.push(commit);
for (const tag of commit.tags) { for (const tag of commit.tags) {
releases.push({ title: tag, date: commit.date, commits: current.commits }); releases.push({ title: tag, date: commit.date, commits: current.commits });
current = { title: 'Unreleased', date: null, commits: [] }; current = { title: 'Unreleased', date: null, commits: [] };
} }
} }
if (current.commits.length > 0) releases.push(current); if (current.commits.length > 0) releases.push(current);
return releases; return releases;
} }
function renderRelease(release) { function renderRelease(release) {
const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`; const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`;
const lines = [heading]; const lines = [heading];
for (const section of SECTIONS) { for (const section of SECTIONS) {
const entries = release.commits.filter((commit) => section.test(commit.type)); const entries = release.commits.filter((commit) => section.test(commit.type));
if (entries.length === 0) continue; if (entries.length === 0) continue;
lines.push('', `### ${section.title}`, ...entries.map(entryLine)); lines.push('', `### ${section.title}`, ...entries.map(entryLine));
} }
if (release.commits.length === 0) lines.push('', '_Nothing yet._'); if (release.commits.length === 0) lines.push('', '_Nothing yet._');
return lines.join('\n'); return lines.join('\n');
} }
/** SemVer hint from the commits since the last release: breaking > feature > fix. */ /** SemVer hint from the commits since the last release: breaking > feature > fix. */
function suggestVersion(commits) { function suggestVersion(commits) {
const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version; const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version;
const [major, minor, patch] = version.split('.').map(Number); const [major, minor, patch] = version.split('.').map(Number);
const breaking = commits.some((commit) => commit.breaking); const breaking = commits.some((commit) => commit.breaking);
const feature = commits.some((commit) => commit.type === 'feat'); const feature = commits.some((commit) => commit.type === 'feat');
// SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor. // SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor.
if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`; if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`;
if (breaking) return `${major + 1}.0.0`; if (breaking) return `${major + 1}.0.0`;
if (feature) return `${major}.${minor + 1}.0`; if (feature) return `${major}.${minor + 1}.0`;
return `${major}.${minor}.${patch + 1}`; return `${major}.${minor}.${patch + 1}`;
} }
function buildChangelog(commits) { function buildChangelog(commits) {
const releases = groupByRelease(commits); const releases = groupByRelease(commits);
return [ return [
'# Changelog', '# Changelog',
'', '',
'All notable changes to this project are documented in this file. It is **generated from the', 'All notable changes to this project are documented in this file. It is **generated from the',
'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.', 'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.',
'The project follows [Semantic Versioning](https://semver.org/).', 'The project follows [Semantic Versioning](https://semver.org/).',
'', '',
releases.map(renderRelease).join('\n\n'), releases.map(renderRelease).join('\n\n'),
'', '',
].join('\n'); ].join('\n');
} }
const commits = readCommits(); const commits = readCommits();
const content = buildChangelog(commits); const content = buildChangelog(commits);
const unreleased = commits.filter((commit) => !commit.tags.length); const unreleased = commits.filter((commit) => !commit.tags.length);
const previous = (() => { const previous = (() => {
try { try {
return readFileSync(changelogPath, 'utf8'); return readFileSync(changelogPath, 'utf8');
} catch { } catch {
return null; return null;
} }
})(); })();
if (checkOnly) { if (checkOnly) {
if (previous !== content) { if (previous !== content) {
console.error('CHANGELOG.md is out of date: run `npm run changelog`.'); console.error('CHANGELOG.md is out of date: run `npm run changelog`.');
process.exit(1); process.exit(1);
} }
console.log('CHANGELOG.md is up to date.'); console.log('CHANGELOG.md is up to date.');
process.exit(0); process.exit(0);
} }
writeFileSync(changelogPath, content); writeFileSync(changelogPath, content);
console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`); console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`);
console.log(`Suggested next version: ${suggestVersion(unreleased)}`); console.log(`Suggested next version: ${suggestVersion(unreleased)}`);
+7 -7
View File
@@ -1,7 +1,7 @@
import { env } from '../src/config/env.js'; import { env } from '../src/config/env.js';
import { closeDatabase, initDatabase } from '../src/database/index.js'; import { closeDatabase, initDatabase } from '../src/database/index.js';
initDatabase(); initDatabase();
closeDatabase(); closeDatabase();
console.log(`Database ready at ${env.database.path}`); console.log(`Database ready at ${env.database.path}`);
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
import { env } from '../src/config/env.js';
import { logger } from '../src/core/logger.js';
import { initDatabase } from '../src/database/index.js';
import { startWebServer } from '../src/web/server.js';
import { generateRuntimeSetupToken, hasSetupToken } from '../src/web/setup-state.js';
/**
* Starts the configuration wizard alone, without connecting to Discord (M16-T09).
*
* This is the entry point for a fresh clone: the bot itself refuses to start
* without `DISCORD_TOKEN`, so the `.env` has to be writable from somewhere else.
*
* Usage: npm run setup
*/
// The wizard stores its session in SQLite, so the database must exist.
initDatabase();
const token = env.web.setupToken || generateRuntimeSetupToken();
const url =
env.web.publicUrl || `http://${env.web.host === '0.0.0.0' ? 'localhost' : env.web.host}:${env.web.port}`;
const server = startWebServer({ client: null, setupOnly: true });
logger.info('Configuration wizard started');
console.log(`
┌──────────────────────────────────────────────────────────────────────┐
│ Assistant de configuration FWS-Bot │
└──────────────────────────────────────────────────────────────────────┘
Ouvre ${url}/#/setup
Jeton ${token}
${env.web.setupToken ? 'Ce jeton vient de WEB_SETUP_TOKEN.' : 'Ce jeton est temporaire : il change à chaque lancement.'}
Une fois le .env enregistré : Ctrl+C, puis npm run db:init,
npm run deploy:commands et npm run dev.
`);
if (!hasSetupToken()) logger.warn('No setup token available, the wizard cannot be opened');
const shutdown = () => {
server.close();
process.exit(0);
};
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
+107 -107
View File
@@ -1,107 +1,107 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { parseChoices } from '../../services/polls/poll-service.js'; import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed, bullets } from '../../ui/embeds.js'; import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
const EIGHT_BALL_ANSWERS = Object.freeze([ const EIGHT_BALL_ANSWERS = Object.freeze([
'Oui, sans aucun doute.', 'Oui, sans aucun doute.',
'Compte là-dessus et bois de l’eau.', 'Compte là-dessus et bois de l’eau.',
'Les signes disent que oui.', 'Les signes disent que oui.',
'Impossible de le prédire pour le moment.', 'Impossible de le prédire pour le moment.',
'Concentre-toi et redemande.', 'Concentre-toi et redemande.',
'Ma réponse est non.', 'Ma réponse est non.',
'Très probablement.', 'Très probablement.',
'Mes sources disent non.', 'Mes sources disent non.',
'La réponse est floue, réessaie.', 'La réponse est floue, réessaie.',
'Absolument !', 'Absolument !',
'Pas dans un avenir proche.', 'Pas dans un avenir proche.',
'Oui, mais fais attention à toi.', 'Oui, mais fais attention à toi.',
]); ]);
const pick = (list) => list[Math.floor(Math.random() * list.length)]; const pick = (list) => list[Math.floor(Math.random() * list.length)];
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('fun') .setName('fun')
.setDescription('Commandes de divertissement') .setDescription('Commandes de divertissement')
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face')) .addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('dice') .setName('dice')
.setDescription('Lancer un dé') .setDescription('Lancer un dé')
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('sides') .setName('sides')
.setDescription('Nombre de faces (6 par défaut)') .setDescription('Nombre de faces (6 par défaut)')
.setMinValue(2) .setMinValue(2)
.setMaxValue(1000), .setMaxValue(1000),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('8ball') .setName('8ball')
.setDescription('Poser une question à la boule magique') .setDescription('Poser une question à la boule magique')
.addStringOption((option) => .addStringOption((option) =>
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300), option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('choose') .setName('choose')
.setDescription('Choisir au hasard parmi plusieurs options') .setDescription('Choisir au hasard parmi plusieurs options')
.addStringOption((option) => .addStringOption((option) =>
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true), option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
), ),
); );
/** Lightweight, stateless fun commands (M10-T07). */ /** Lightweight, stateless fun commands (M10-T07). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'coinflip') { if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']); const result = pick(['Pile', 'Face']);
await interaction.reply({ await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)], embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)],
}); });
return; return;
} }
if (subcommand === 'dice') { if (subcommand === 'dice') {
const sides = interaction.options.getInteger('sides') ?? 6; const sides = interaction.options.getInteger('sides') ?? 6;
const roll = 1 + Math.floor(Math.random() * sides); const roll = 1 + Math.floor(Math.random() * sides);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
baseEmbed(COLORS.info) baseEmbed(COLORS.info)
.setTitle(`🎲 Lancer de dé (d${sides})`) .setTitle(`🎲 Lancer de dé (d${sides})`)
.setDescription(`Tu obtiens **${roll}** !`), .setDescription(`Tu obtiens **${roll}** !`),
], ],
}); });
return; return;
} }
if (subcommand === '8ball') { if (subcommand === '8ball') {
const question = interaction.options.getString('question', true); const question = interaction.options.getString('question', true);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
baseEmbed(COLORS.info) baseEmbed(COLORS.info)
.setTitle('🎱 Boule magique') .setTitle('🎱 Boule magique')
.addFields( .addFields(
{ name: 'Question', value: question }, { name: 'Question', value: question },
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) }, { name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
), ),
], ],
}); });
return; return;
} }
const options = parseChoices(interaction.options.getString('options', true)); const options = parseChoices(interaction.options.getString('options', true));
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
baseEmbed(COLORS.info) baseEmbed(COLORS.info)
.setTitle('🎯 Choix aléatoire') .setTitle('🎯 Choix aléatoire')
.addFields({ name: 'Options', value: bullets(options) }) .addFields({ name: 'Options', value: bullets(options) })
.setDescription(`Je choisis : **${pick(options)}**`), .setDescription(`Je choisis : **${pick(options)}**`),
], ],
}); });
} }
+62 -62
View File
@@ -1,62 +1,62 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js'; import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('poll') .setName('poll')
.setDescription('Sondages') .setDescription('Sondages')
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('create') .setName('create')
.setDescription('Créer un sondage') .setDescription('Créer un sondage')
.addStringOption((option) => .addStringOption((option) =>
option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200), option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200),
) )
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('choices') .setName('choices')
.setDescription('Propositions séparées par des « ; » (2 à 10)') .setDescription('Propositions séparées par des « ; » (2 à 10)')
.setRequired(true), .setRequired(true),
) )
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('minutes') .setName('minutes')
.setDescription('Durée avant fermeture automatique, en minutes') .setDescription('Durée avant fermeture automatique, en minutes')
.setMinValue(1) .setMinValue(1)
.setMaxValue(10_080), .setMaxValue(10_080),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('close') .setName('close')
.setDescription('Fermer un sondage') .setDescription('Fermer un sondage')
.addIntegerOption((option) => .addIntegerOption((option) =>
option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true), option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true),
), ),
); );
/** Polls are published in the current channel and voted with buttons (M10). */ /** Polls are published in the current channel and voted with buttons (M10). */
export async function execute(interaction) { export async function execute(interaction) {
if (interaction.options.getSubcommand() === 'close') { if (interaction.options.getSubcommand() === 'close') {
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true)); const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
await interaction.reply({ embeds: [buildPollEmbed(poll)] }); await interaction.reply({ embeds: [buildPollEmbed(poll)] });
return; return;
} }
const question = interaction.options.getString('question', true); const question = interaction.options.getString('question', true);
const choicesInput = interaction.options.getString('choices', true); const choicesInput = interaction.options.getString('choices', true);
const minutes = interaction.options.getInteger('minutes'); const minutes = interaction.options.getInteger('minutes');
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const pollId = await createPoll(interaction, { question, choicesInput, minutes }); const pollId = await createPoll(interaction, { question, choicesInput, minutes });
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
successEmbed( successEmbed(
`Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`, `Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`,
), ),
], ],
}); });
} }
+116 -116
View File
@@ -1,116 +1,116 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { countByAction } from '../../database/repositories/moderation-repository.js'; import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js'; import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { baseEmbed, errorEmbed } from '../../ui/embeds.js'; import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
const log = createLogger('stats'); const log = createLogger('stats');
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('stats') .setName('stats')
.setDescription('Statistiques publiques') .setDescription('Statistiques publiques')
.addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord')) .addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord'))
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea')) .addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch')); .addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
const discordStatsEmbed = (interaction) => { const discordStatsEmbed = (interaction) => {
const guild = interaction.guild; const guild = interaction.guild;
return baseEmbed() return baseEmbed()
.setTitle(`📊 Statistiques — ${guild.name}`) .setTitle(`📊 Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 })) .setThumbnail(guild.iconURL({ size: 128 }))
.addFields( .addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true }, { name: 'Membres', value: String(guild.memberCount), inline: true },
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true }, { name: 'Salons', value: String(guild.channels.cache.size), inline: true },
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true }, { name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true }, { name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true }, { name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true }, { name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
); );
}; };
async function giteaStatsEmbed() { async function giteaStatsEmbed() {
const [issues, pulls, commits, releases] = await Promise.all([ const [issues, pulls, commits, releases] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'), gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'), gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5), gitea.listCommits(5),
gitea.listReleases(1), gitea.listReleases(1),
]); ]);
const latestCommits = asList(commits) const latestCommits = asList(commits)
.slice(0, 5) .slice(0, 5)
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`) .map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
.join('\n'); .join('\n');
const release = asList(releases)[0]; const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité Gitea') .setTitle('📈 Activité Gitea')
.setURL(repositoryUrl()) .setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent pour le moment.') .setDescription(latestCommits || 'Aucun commit récent pour le moment.')
.addFields( .addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
); );
if (release) if (release)
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true }); embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
return embed; return embed;
} }
/** Community activity stored locally, independent from Gitea availability (M11). */ /** Community activity stored locally, independent from Gitea availability (M11). */
function fwsStatsEmbed(interaction) { function fwsStatsEmbed(interaction) {
const actions = countByAction(interaction.guildId); const actions = countByAction(interaction.guildId);
const total = actions.reduce((sum, row) => sum + row.count, 0); const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea) return baseEmbed(COLORS.gitea)
.setTitle('📈 Indicateurs FWS') .setTitle('📈 Indicateurs FWS')
.addFields( .addFields(
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true }, { name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true }, { name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
{ name: 'Actions de modération', value: String(total), inline: true }, { name: 'Actions de modération', value: String(total), inline: true },
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' }, { name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
) )
.setFooter({ text: 'Statistiques locales · FWS-Bot' }); .setFooter({ text: 'Statistiques locales · FWS-Bot' });
} }
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */ /** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
await interaction.deferReply(); await interaction.deferReply();
if (subcommand === 'discord') { if (subcommand === 'discord') {
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] }); await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
return; return;
} }
if (subcommand === 'fws') { if (subcommand === 'fws') {
try { try {
const releases = asList(await gitea.listReleases(1)); const releases = asList(await gitea.listReleases(1));
const embed = fwsStatsEmbed(interaction); const embed = fwsStatsEmbed(interaction);
if (releases[0]) if (releases[0])
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' }); embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} catch (error) { } catch (error) {
log.warn('Gitea unavailable while building /stats fws', error); log.warn('Gitea unavailable while building /stats fws', error);
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] }); await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
} }
return; return;
} }
try { try {
await interaction.editReply({ embeds: [await giteaStatsEmbed()] }); await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
} catch (error) { } catch (error) {
log.error('Could not read Gitea stats', error); log.error('Could not read Gitea stats', error);
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
errorEmbed( errorEmbed(
'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.', 'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.',
), ),
], ],
}); });
} }
} }
+238 -238
View File
@@ -1,238 +1,238 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js'; import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js'; import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js'; import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js'; import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js'; import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js'; import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws'); const log = createLogger('fws');
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('fws') .setName('fws')
.setDescription('Informations sur FWS et FWS Arch') .setDescription('Informations sur FWS et FWS Arch')
.addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch')) .addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch'))
.addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch')) .addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch'))
.addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets')) .addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets'))
.addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles')) .addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('changelog') .setName('changelog')
.setDescription('Nouveautés d’une version') .setDescription('Nouveautés d’une version')
.addStringOption((option) => .addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'), option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'),
), ),
); );
const officialLinks = () => [ const officialLinks = () => [
{ label: 'Site', url: env.links.website }, { label: 'Site', url: env.links.website },
{ label: 'Documentation', url: env.links.docs }, { label: 'Documentation', url: env.links.docs },
{ label: 'Dépôt FWS Arch', url: env.links.archRepo }, { label: 'Dépôt FWS Arch', url: env.links.archRepo },
{ label: 'Gitea', url: env.gitea.url }, { label: 'Gitea', url: env.gitea.url },
{ label: 'Discord', url: env.links.discordInvite }, { label: 'Discord', url: env.links.discordInvite },
]; ];
/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */ /** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
function readSetting(guildId, key, fallback = null) { function readSetting(guildId, key, fallback = null) {
try { try {
return getSetting(guildId, key, fallback); return getSetting(guildId, key, fallback);
} catch (error) { } catch (error) {
log.debug(`Could not read setting ${key}`, error); log.debug(`Could not read setting ${key}`, error);
return fallback; return fallback;
} }
} }
const DEFAULT_PRESENTATION = const DEFAULT_PRESENTATION =
'FWS est une organisation open source multi-projets.\n' + 'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale."; "**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
async function latestRelease() { async function latestRelease() {
try { try {
return await gitea.getLatestRelease(); return await gitea.getLatestRelease();
} catch { } catch {
return asList(await gitea.listReleases(1))[0] ?? null; return asList(await gitea.listReleases(1))[0] ?? null;
} }
} }
async function showInfo(interaction) { async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION); const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION; const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({ await interaction.reply({
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)], embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()), components: linkButtons(officialLinks()),
}); });
} }
async function showVersion(interaction) { async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null); const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) { if (!isGiteaConfigured()) {
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
fallback fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: errorEmbed( : errorEmbed(
'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.', 'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.',
), ),
], ],
}); });
return; return;
} }
await interaction.deferReply(); await interaction.deferReply();
try { try {
const release = await latestRelease(); const release = await latestRelease();
if (!release) { if (!release) {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
fallback fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`) ? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'), : infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
], ],
}); });
return; return;
} }
await interaction.editReply({ await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })], embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [], components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
}); });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
async function showStatus(interaction) { async function showStatus(interaction) {
await interaction.deferReply(); await interaction.deferReply();
const giteaConfigured = isGiteaConfigured(); const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured const giteaReachable = giteaConfigured
? await gitea ? await gitea
.listReleases(1) .listReleases(1)
.then(() => true) .then(() => true)
.catch(() => false) .catch(() => false)
: false; : false;
let openTickets = null; let openTickets = null;
try { try {
openTickets = countOpenTickets(interaction.guildId); openTickets = countOpenTickets(interaction.guildId);
} catch (error) { } catch (error) {
log.warn('Database unavailable while building /fws status', error); log.warn('Database unavailable while building /fws status', error);
} }
const uptime = Math.floor(process.uptime()); const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info) const embed = baseEmbed(COLORS.info)
.setTitle('🩺 État des services') .setTitle('🩺 État des services')
.addFields( .addFields(
{ {
name: 'API Gitea', name: 'API Gitea',
value: !giteaConfigured value: !giteaConfigured
? '⚙️ Pas encore configurée' ? '⚙️ Pas encore configurée'
: giteaReachable : giteaReachable
? `✅ En ligne — ${repositoryUrl()}` ? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable pour le moment', : '❌ Injoignable pour le moment',
inline: false, inline: false,
}, },
{ {
name: 'Webhooks Gitea', name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)', value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false, inline: false,
}, },
{ {
name: 'Base SQLite', name: 'Base SQLite',
value: value:
openTickets === null openTickets === null
? '❌ Indisponible pour le moment' ? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`, : `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false, inline: false,
}, },
{ {
name: 'Discord', name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`, value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false, inline: false,
}, },
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` }, { name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
); );
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} }
async function showChangelog(interaction) { async function showChangelog(interaction) {
const version = interaction.options.getString('version'); const version = interaction.options.getString('version');
if (!isGiteaConfigured()) { if (!isGiteaConfigured()) {
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
errorEmbed( errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.', 'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
), ),
], ],
}); });
return; return;
} }
await interaction.deferReply(); await interaction.deferReply();
try { try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease(); const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) { if (!release) {
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
infoEmbed( infoEmbed(
'📜 Changelog', '📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`, `Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
), ),
], ],
}); });
return; return;
} }
await interaction.editReply({ await interaction.editReply({
embeds: [releaseEmbed(release)], embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [], components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
}); });
} catch (error) { } catch (error) {
if (version) { if (version) {
log.warn(`Release ${version} not found`, error); log.warn(`Release ${version} not found`, error);
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
infoEmbed( infoEmbed(
'📜 Changelog', '📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`, `Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
), ),
], ],
}); });
return; return;
} }
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
/** Static presentation plus live data from Gitea (M4). */ /** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) { export async function execute(interaction) {
switch (interaction.options.getSubcommand()) { switch (interaction.options.getSubcommand()) {
case 'info': case 'info':
await showInfo(interaction); await showInfo(interaction);
return; return;
case 'links': case 'links':
await interaction.reply({ await interaction.reply({
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')], embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()), components: linkButtons(officialLinks()),
}); });
return; return;
case 'version': case 'version':
await showVersion(interaction); await showVersion(interaction);
return; return;
case 'status': case 'status':
await showStatus(interaction); await showStatus(interaction);
return; return;
case 'changelog': case 'changelog':
await showChangelog(interaction); await showChangelog(interaction);
return; return;
default: default:
return; return;
} }
} }
+25 -25
View File
@@ -1,25 +1,25 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js'; import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed, bullets } from '../../ui/embeds.js'; import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('help') .setName('help')
.setDescription('Affiche les commandes accessibles selon ton rôle'); .setDescription('Affiche les commandes accessibles selon ton rôle');
export async function execute(interaction) { export async function execute(interaction) {
const level = getAccessLevel(interaction.member); const level = getAccessLevel(interaction.member);
const lines = interaction.client.commands const lines = interaction.client.commands
.filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level) .filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level)
.map((command) => `\`/${command.data.name}\` — ${command.data.description}`) .map((command) => `\`/${command.data.name}\` — ${command.data.description}`)
.sort(); .sort();
const embed = baseEmbed() const embed = baseEmbed()
.setTitle('🤖 Tes commandes') .setTitle('🤖 Tes commandes')
.setDescription( .setDescription(
`Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`, `Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`,
); );
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
} }
+153 -153
View File
@@ -1,153 +1,153 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { import {
addBotStatus, addBotStatus,
applyBotStatus, applyBotStatus,
applyStatusIfAlone, applyStatusIfAlone,
clearBotStatusList, clearBotStatusList,
FALLBACK_STATUS, FALLBACK_STATUS,
formatSeconds, formatSeconds,
removeBotStatus, removeBotStatus,
ROTATION_MAX_SECONDS, ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS, ROTATION_MIN_SECONDS,
saveRotationSeconds, saveRotationSeconds,
STATUS_TYPE_CHOICES, STATUS_TYPE_CHOICES,
statusAddedEmbed, statusAddedEmbed,
statusListEmbed, statusListEmbed,
toggleBotStatus, toggleBotStatus,
} from '../../services/status/bot-status-service.js'; } from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) => const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1); option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('status') .setName('status')
.setDescription('Statuts affichés sous le nom du bot') .setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('add') .setName('add')
.setDescription('Ajouter un statut à la rotation') .setDescription('Ajouter un statut à la rotation')
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('text') .setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »') .setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true) .setRequired(true)
.setMaxLength(128), .setMaxLength(128),
) )
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('type') .setName('type')
.setDescription('Type d’activité (regarde par défaut)') .setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES), .addChoices(...STATUS_TYPE_CHOICES),
) )
.addStringOption((option) => .addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'), option.setName('url').setDescription('Lien exigé par le type « en direct »'),
), ),
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés')) .addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption), sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption), sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption), sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('interval') .setName('interval')
.setDescription('Rythme de la rotation') .setDescription('Rythme de la rotation')
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('seconds') .setName('seconds')
.setDescription('Secondes entre deux changements') .setDescription('Secondes entre deux changements')
.setRequired(true) .setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS) .setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS), .setMaxValue(ROTATION_MAX_SECONDS),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'), sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
); );
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */ /** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') { if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId })); await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return; return;
} }
if (subcommand === 'add') { if (subcommand === 'add') {
const status = addBotStatus({ const status = addBotStatus({
text: interaction.options.getString('text', true), text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching', type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'), url: interaction.options.getString('url'),
createdBy: interaction.user.id, createdBy: interaction.user.id,
}); });
// A single status is shown right away: an addition should never wait for the next turn. // A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null; const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied })); await reply(interaction, statusAddedEmbed(status, { applied }));
return; return;
} }
if (subcommand === 'interval') { if (subcommand === 'interval') {
const seconds = saveRotationSeconds( const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true), interaction.options.getInteger('seconds', true),
interaction.guildId, interaction.guildId,
interaction.user.id, interaction.user.id,
); );
await reply( await reply(
interaction, interaction,
successEmbed( successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`, `C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
), ),
); );
return; return;
} }
if (subcommand === 'clear') { if (subcommand === 'clear') {
const removed = clearBotStatusList(); const removed = clearBotStatusList();
applyBotStatus(interaction.client); applyBotStatus(interaction.client);
await reply( await reply(
interaction, interaction,
successEmbed( successEmbed(
removed === 0 removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».` ? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`, : `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
), ),
); );
return; return;
} }
const id = interaction.options.getInteger('id', true); const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') { if (subcommand === 'remove') {
const status = removeBotStatus(id); const status = removeBotStatus(id);
await reply( await reply(
interaction, interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`), successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
); );
return; return;
} }
const enabled = subcommand === 'enable'; const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled); const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client); if (enabled) applyStatusIfAlone(interaction.client);
await reply( await reply(
interaction, interaction,
successEmbed( successEmbed(
enabled enabled
? `« ${status.text} » reprend sa place dans la rotation.` ? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`, : `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
), ),
); );
} }
+74 -74
View File
@@ -1,74 +1,74 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js'; import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('gitea') .setName('gitea')
.setDescription('Activité Gitea de FWS Arch') .setDescription('Activité Gitea de FWS Arch')
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents')) .addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')); .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
const commitLines = (commits) => const commitLines = (commits) =>
bullets( bullets(
asList(commits) asList(commits)
.slice(0, 5) .slice(0, 5)
.map((commit) => { .map((commit) => {
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)'; const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`; return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`;
}), }),
); );
/** Read-only summaries of the repository (M5-T06 / M5-T07). */ /** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) { export async function execute(interaction) {
assertGiteaConfigured(); assertGiteaConfigured();
await interaction.deferReply(); await interaction.deferReply();
try { try {
if (interaction.options.getSubcommand() === 'release') { if (interaction.options.getSubcommand() === 'release') {
const releases = asList(await gitea.listReleases(5)); const releases = asList(await gitea.listReleases(5));
if (releases.length === 0) { if (releases.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] }); await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
return; return;
} }
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle('📦 Releases FWS Arch') .setTitle('📦 Releases FWS Arch')
.setURL(repositoryUrl()) .setURL(repositoryUrl())
.setDescription( .setDescription(
releases releases
.map((release) => { .map((release) => {
const date = release.published_at const date = release.published_at
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>` ? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
: 'date inconnue'; : 'date inconnue';
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name; const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`; return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
}) })
.join('\n'), .join('\n'),
); );
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
return; return;
} }
const [issues, pulls, commits] = await Promise.all([ const [issues, pulls, commits] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'), gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'), gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5), gitea.listCommits(5),
]); ]);
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité récente') .setTitle('📈 Activité récente')
.setURL(repositoryUrl()) .setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.') .setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.')
.addFields( .addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true }, { name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true }, { name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
); );
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
+80 -80
View File
@@ -1,80 +1,80 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { issueEmbed } from '../../services/gitea/gitea-embeds.js'; import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
import { import {
assertGiteaConfigured, assertGiteaConfigured,
openIssueModal, openIssueModal,
replyGiteaFailure, replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js'; } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
// TODO(M5-T03): make the required level for `create` configurable per guild. // TODO(M5-T03): make the required level for `create` configurable per guild.
export const subcommandAccess = { create: ACCESS_LEVELS.USER }; export const subcommandAccess = { create: ACCESS_LEVELS.USER };
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('issue') .setName('issue')
.setDescription('Issues Gitea') .setDescription('Issues Gitea')
.addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea')) .addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('view') .setName('view')
.setDescription('Afficher une issue') .setDescription('Afficher une issue')
.addIntegerOption((option) => .addIntegerOption((option) =>
option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1), option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1),
), ),
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes')); .addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */ /** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') { if (subcommand === 'create') {
await openIssueModal(interaction); await openIssueModal(interaction);
return; return;
} }
assertGiteaConfigured(); assertGiteaConfigured();
await interaction.deferReply(); await interaction.deferReply();
try { try {
if (subcommand === 'view') { if (subcommand === 'view') {
const issue = await gitea.getIssue(interaction.options.getInteger('number', true)); const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
if (!issue?.number) { if (!issue?.number) {
throw new UserFacingError( throw new UserFacingError(
'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.', 'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.',
); );
} }
await interaction.editReply({ embeds: [issueEmbed(issue)] }); await interaction.editReply({ embeds: [issueEmbed(issue)] });
return; return;
} }
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15')); const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
if (issues.length === 0) { if (issues.length === 0) {
await interaction.editReply({ await interaction.editReply({
embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')], embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')],
}); });
return; return;
} }
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Issues ouvertes') .setTitle('🐙 Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`) .setURL(`${repositoryUrl()}/issues`)
.setDescription( .setDescription(
bullets( bullets(
issues.map( issues.map(
(issue) => (issue) =>
`**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`, `**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`,
), ),
), ),
) )
.setFooter({ text: `${issues.length} issue(s) affichée(s)` }); .setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
+95 -95
View File
@@ -1,95 +1,95 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js'; import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
import { import {
assertGiteaConfigured, assertGiteaConfigured,
openPullRequestModal, openPullRequestModal,
replyGiteaFailure, replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js'; } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('pr') .setName('pr')
.setDescription('Pull requests Gitea') .setDescription('Pull requests Gitea')
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('create') .setName('create')
.setDescription('Créer une pull request') .setDescription('Créer une pull request')
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('head') .setName('head')
.setDescription('Branche source, celle qui apporte les changements') .setDescription('Branche source, celle qui apporte les changements')
.setRequired(true), .setRequired(true),
) )
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('base') .setName('base')
.setDescription('Branche cible, celle qui reçoit les changements') .setDescription('Branche cible, celle qui reçoit les changements')
.setRequired(true), .setRequired(true),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('view') .setName('view')
.setDescription('Afficher une pull request') .setDescription('Afficher une pull request')
.addIntegerOption((option) => .addIntegerOption((option) =>
option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1), option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1),
), ),
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes')); .addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
/** The title and description are collected through a modal (M5-T04 / M5-T05). */ /** The title and description are collected through a modal (M5-T04 / M5-T05). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') { if (subcommand === 'create') {
await openPullRequestModal(interaction); await openPullRequestModal(interaction);
return; return;
} }
assertGiteaConfigured(); assertGiteaConfigured();
await interaction.deferReply(); await interaction.deferReply();
try { try {
if (subcommand === 'view') { if (subcommand === 'view') {
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true)); const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
if (!pull?.number) { if (!pull?.number) {
throw new UserFacingError( throw new UserFacingError(
'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.', 'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.',
); );
} }
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] }); await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
return; return;
} }
const pulls = asList(await gitea.listPullRequests('state=open&limit=15')); const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
if (pulls.length === 0) { if (pulls.length === 0) {
await interaction.editReply({ await interaction.editReply({
embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')], embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')],
}); });
return; return;
} }
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Pull requests ouvertes') .setTitle('🐙 Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`) .setURL(`${repositoryUrl()}/pulls`)
.setDescription( .setDescription(
bullets( bullets(
pulls.map( pulls.map(
(pull) => (pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` + `**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`, `(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`,
), ),
), ),
) )
.setFooter({ text: `${pulls.length} PR affichée(s)` }); .setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
+59 -56
View File
@@ -1,56 +1,59 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { import { readSetting } from '../../config/guild-settings.js';
assertModerationTarget, import {
logModerationAction, assertModerationTarget,
targetNoticeEmbed, logModerationAction,
} from '../../services/moderation/moderation-service.js'; notifyTarget,
import { successEmbed } from '../../ui/embeds.js'; targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
export const access = ACCESS_LEVELS.STAFF; import { successEmbed } from '../../ui/embeds.js';
export const data = new SlashCommandBuilder() export const access = ACCESS_LEVELS.STAFF;
.setName('ban')
.setDescription('Bannir un membre') export const data = new SlashCommandBuilder()
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers) .setName('ban')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .setDescription('Bannir un membre')
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)) .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addIntegerOption((option) => .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
option .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500))
.setName('delete_days') .addIntegerOption((option) =>
.setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)') option
.setMinValue(0) .setName('delete_days')
.setMaxValue(7), .setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)')
); .setMinValue(0)
.setMaxValue(7),
/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */ );
export async function execute(interaction) {
const user = interaction.options.getUser('user', true); /** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
const reason = interaction.options.getString('reason'); export async function execute(interaction) {
const deleteDays = interaction.options.getInteger('delete_days') ?? 0; const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const member = await interaction.guild.members.fetch(user.id).catch(() => null); // Falls back to what the server configured rather than to a blunt zero.
if (member) { const deleteDays =
assertModerationTarget(interaction, member); interaction.options.getInteger('delete_days') ??
await member Math.round(readSetting('moderation.banDeleteMessageHours', interaction.guildId) / 24);
.send({
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })], const member = await interaction.guild.members.fetch(user.id).catch(() => null);
}) if (member) {
.catch(() => {}); assertModerationTarget(interaction, member);
} await notifyTarget(member, {
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); });
await interaction.guild.bans.create(user.id, { }
reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400, await interaction.deferReply({ flags: MessageFlags.Ephemeral });
}); await interaction.guild.bans.create(user.id, {
reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`,
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason }); deleteMessageSeconds: deleteDays * 86_400,
await interaction.editReply({ });
embeds: [
successEmbed( await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
`C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`, await interaction.editReply({
), embeds: [
], successEmbed(
}); `C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
} ),
],
});
}
+49 -49
View File
@@ -1,49 +1,49 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { logModerationAction } from '../../services/moderation/moderation-service.js'; import { logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('clear') .setName('clear')
.setDescription('Supprimer des messages') .setDescription('Supprimer des messages')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages) .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('amount') .setName('amount')
.setDescription('Nombre de messages à supprimer (1 à 100)') .setDescription('Nombre de messages à supprimer (1 à 100)')
.setRequired(true) .setRequired(true)
.setMinValue(1) .setMinValue(1)
.setMaxValue(100), .setMaxValue(100),
); );
/** Bulk deletes messages in the current channel and logs it (M8-T05). */ /** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) { export async function execute(interaction) {
const amount = interaction.options.getInteger('amount', true); const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) { if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError( throw new UserFacingError(
'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.', 'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.',
); );
} }
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const deleted = await interaction.channel.bulkDelete(amount, true); const deleted = await interaction.channel.bulkDelete(amount, true);
await logModerationAction(interaction, { await logModerationAction(interaction, {
action: 'clear', action: 'clear',
targetId: null, targetId: null,
reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`, reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`,
}); });
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
successEmbed( successEmbed(
`C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` + `C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount (deleted.size < amount
? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._' ? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._'
: ''), : ''),
), ),
], ],
}); });
} }
+43 -44
View File
@@ -1,44 +1,43 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { import {
assertModerationTarget, assertModerationTarget,
fetchTargetMember, fetchTargetMember,
logModerationAction, logModerationAction,
targetNoticeEmbed, notifyTarget,
} from '../../services/moderation/moderation-service.js'; targetNoticeEmbed,
import { successEmbed } from '../../ui/embeds.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('kick') export const data = new SlashCommandBuilder()
.setDescription('Expulser un membre du serveur') .setName('kick')
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers) .setDescription('Expulser un membre du serveur')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) { /** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
const user = interaction.options.getUser('user', true); export async function execute(interaction) {
const reason = interaction.options.getString('reason'); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target); const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target await interaction.deferReply({ flags: MessageFlags.Ephemeral });
.send({ await notifyTarget(target, {
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })], embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
}) });
.catch(() => {}); await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason }); await interaction.editReply({
await interaction.editReply({ embeds: [
embeds: [ successEmbed(
successEmbed( `C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`,
`C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`, ),
), ],
], });
}); }
}
+55 -55
View File
@@ -1,55 +1,55 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { listActions } from '../../database/repositories/moderation-repository.js'; import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration } from '../../services/moderation/moderation-service.js'; import { formatDuration } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js'; import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
const HISTORY_LIMIT = 15; const HISTORY_LIMIT = 15;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('mod') .setName('mod')
.setDescription('Outils de modération') .setDescription('Outils de modération')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('logs') .setName('logs')
.setDescription('Consulter les actions de modération') .setDescription('Consulter les actions de modération')
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')), .addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
); );
function formatEntry(row) { function formatEntry(row) {
const meta = MODERATION_ACTIONS[row.action]; const meta = MODERATION_ACTIONS[row.action];
const target = row.target_id ? `<@${row.target_id}>` : 'salon'; const target = row.target_id ? `<@${row.target_id}>` : 'salon';
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : ''; const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
return ( return (
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` + `\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}` `↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
); );
} }
/** Reads the moderation history from SQLite (M8-T06). */ /** Reads the moderation history from SQLite (M8-T06). */
export async function execute(interaction) { export async function execute(interaction) {
const user = interaction.options.getUser('user'); const user = interaction.options.getUser('user');
const actions = listActions({ const actions = listActions({
guildId: interaction.guildId, guildId: interaction.guildId,
targetId: user?.id ?? null, targetId: user?.id ?? null,
limit: HISTORY_LIMIT, limit: HISTORY_LIMIT,
}); });
const embed = const embed =
actions.length === 0 actions.length === 0
? infoEmbed( ? infoEmbed(
'📜 Historique de modération', '📜 Historique de modération',
user user
? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.` ? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.`
: 'Aucune action de modération enregistrée sur ce serveur, tout est calme.', : 'Aucune action de modération enregistrée sur ce serveur, tout est calme.',
) )
: baseEmbed(COLORS.moderation) : baseEmbed(COLORS.moderation)
.setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération') .setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération')
.setDescription(actions.map(formatEntry).join('\n\n')) .setDescription(actions.map(formatEntry).join('\n\n'))
.setFooter({ text: `${actions.length} action(s) affichée(s)` }); .setFooter({ text: `${actions.length} action(s) affichée(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
} }
+62 -61
View File
@@ -1,61 +1,62 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { import { readSetting } from '../../config/guild-settings.js';
assertModerationTarget, import {
fetchTargetMember, assertModerationTarget,
formatDuration, fetchTargetMember,
logModerationAction, formatDuration,
targetNoticeEmbed, logModerationAction,
} from '../../services/moderation/moderation-service.js'; notifyTarget,
import { successEmbed } from '../../ui/embeds.js'; targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
export const access = ACCESS_LEVELS.STAFF; import { successEmbed } from '../../ui/embeds.js';
export const data = new SlashCommandBuilder() export const access = ACCESS_LEVELS.STAFF;
.setName('mute')
.setDescription('Restreindre temporairement un membre') export const data = new SlashCommandBuilder()
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) .setName('mute')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .setDescription('Restreindre temporairement un membre')
.addIntegerOption((option) => .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
option .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.setName('minutes') .addIntegerOption((option) =>
.setDescription('Durée de la sanction, en minutes') option
.setRequired(true) .setName('minutes')
.setMinValue(1) .setDescription('Durée de la sanction, en minutes')
.setMaxValue(40_320), .setMinValue(1)
) .setMaxValue(40_320),
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); )
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) { /** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
const user = interaction.options.getUser('user', true); export async function execute(interaction) {
const minutes = interaction.options.getInteger('minutes', true); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason'); const minutes =
const durationMs = minutes * 60_000; interaction.options.getInteger('minutes') ??
readSetting('moderation.defaultMuteMinutes', interaction.guildId);
const target = await fetchTargetMember(interaction, user.id); const reason = interaction.options.getString('reason');
assertModerationTarget(interaction, target); const durationMs = minutes * 60_000;
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const target = await fetchTargetMember(interaction, user.id);
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`); assertModerationTarget(interaction, target);
await logModerationAction(interaction, { await interaction.deferReply({ flags: MessageFlags.Ephemeral });
action: 'mute', await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
targetId: target.id,
reason, await logModerationAction(interaction, {
durationMs, action: 'mute',
}); targetId: target.id,
await target reason,
.send({ durationMs,
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })], });
}) await notifyTarget(target, {
.catch(() => {}); embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
});
await interaction.editReply({
embeds: [ await interaction.editReply({
successEmbed( embeds: [
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`, successEmbed(
), `C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
], ),
}); ],
} });
}
+105 -105
View File
@@ -1,105 +1,105 @@
import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js'; import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { import {
listNotificationChannels, listNotificationChannels,
removeNotificationChannel, removeNotificationChannel,
setNotificationChannel, setNotificationChannel,
} from '../../database/repositories/notification-repository.js'; } from '../../database/repositories/notification-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type })); const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type }));
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('notify') .setName('notify')
.setDescription('Configuration des salons de notification') .setDescription('Configuration des salons de notification')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('set') .setName('set')
.setDescription('Associer un salon à un type de notification') .setDescription('Associer un salon à un type de notification')
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('type') .setName('type')
.setDescription('Type de notification') .setDescription('Type de notification')
.setRequired(true) .setRequired(true)
.addChoices(...TYPE_CHOICES), .addChoices(...TYPE_CHOICES),
) )
.addChannelOption((option) => .addChannelOption((option) =>
option option
.setName('channel') .setName('channel')
.setDescription('Salon de destination') .setDescription('Salon de destination')
.setRequired(true) .setRequired(true)
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement), .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('remove') .setName('remove')
.setDescription('Revenir au salon par défaut de la configuration') .setDescription('Revenir au salon par défaut de la configuration')
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('type') .setName('type')
.setDescription('Type de notification') .setDescription('Type de notification')
.setRequired(true) .setRequired(true)
.addChoices(...TYPE_CHOICES), .addChoices(...TYPE_CHOICES),
), ),
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle')); .addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle'));
/** Per-guild notification routing stored in SQLite (M9-T01). */ /** Per-guild notification routing stored in SQLite (M9-T01). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'set') { if (subcommand === 'set') {
const type = interaction.options.getString('type', true); const type = interaction.options.getString('type', true);
const channel = interaction.options.getChannel('channel', true); const channel = interaction.options.getChannel('channel', true);
setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id }); setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id });
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`), successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`),
], ],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
if (subcommand === 'remove') { if (subcommand === 'remove') {
const type = interaction.options.getString('type', true); const type = interaction.options.getString('type', true);
const removed = removeNotificationChannel(interaction.guildId, type); const removed = removeNotificationChannel(interaction.guildId, type);
if (!removed) { if (!removed) {
throw new UserFacingError( throw new UserFacingError(
`Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`, `Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`,
); );
} }
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`), successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`),
], ],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
const overrides = new Map( const overrides = new Map(
listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]), listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]),
); );
const lines = NOTIFICATION_TYPES.map((type) => { const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type); const channelId = overrides.get(type);
return channelId return channelId
? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_` ? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_`
: `\`${type}\` → _configuration par défaut_`; : `\`${type}\` → _configuration par défaut_`;
}); });
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
baseEmbed() baseEmbed()
.setTitle('🔔 Salons de notification') .setTitle('🔔 Salons de notification')
.setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`) .setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`)
.setFooter({ text: `Serveur ${interaction.guildId}` }), .setFooter({ text: `Serveur ${interaction.guildId}` }),
], ],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
} }
+91 -91
View File
@@ -1,91 +1,91 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js'; import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('role') .setName('role')
.setDescription('Gestion des rôles') .setDescription('Gestion des rôles')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles) .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('set') .setName('set')
.setDescription('Attribuer ou retirer un rôle') .setDescription('Attribuer ou retirer un rôle')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true)) .addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true))
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('action') .setName('action')
.setDescription('Ajouter ou retirer le rôle') .setDescription('Ajouter ou retirer le rôle')
.setRequired(true) .setRequired(true)
.addChoices( .addChoices(
{ name: 'Ajouter le rôle', value: 'add' }, { name: 'Ajouter le rôle', value: 'add' },
{ name: 'Retirer le rôle', value: 'remove' }, { name: 'Retirer le rôle', value: 'remove' },
), ),
), ),
); );
/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */ /** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) { export async function execute(interaction) {
const user = interaction.options.getUser('user', true); const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true); const role = interaction.options.getRole('role', true);
const action = interaction.options.getString('action', true); const action = interaction.options.getString('action', true);
const adding = action === 'add'; const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) { if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError( throw new UserFacingError(
'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.', 'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.',
); );
} }
if (role.managed) { if (role.managed) {
throw new UserFacingError( throw new UserFacingError(
'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.', 'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.',
); );
} }
const bot = interaction.guild.members.me; const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) { if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError( throw new UserFacingError(
'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.', 'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.',
); );
} }
const target = await fetchTargetMember(interaction, user.id); const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id); const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) { if (adding && hasRole) {
throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`); throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`);
} }
if (!adding && !hasRole) { if (!adding && !hasRole) {
throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`); throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`);
} }
const isGuildOwner = interaction.guild.ownerId === interaction.user.id; const isGuildOwner = interaction.guild.ownerId === interaction.user.id;
if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) { if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError( throw new UserFacingError(
'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.', 'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.',
); );
} }
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (adding) { if (adding) {
await target.roles.add(role, `Ajouté par ${interaction.user.tag}`); await target.roles.add(role, `Ajouté par ${interaction.user.tag}`);
} else { } else {
await target.roles.remove(role, `Retiré par ${interaction.user.tag}`); await target.roles.remove(role, `Retiré par ${interaction.user.tag}`);
} }
await logModerationAction(interaction, { await logModerationAction(interaction, {
action: 'role', action: 'role',
targetId: target.id, targetId: target.id,
reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`, reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`,
}); });
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
successEmbed( successEmbed(
`C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`, `C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`,
), ),
], ],
}); });
} }
+52 -53
View File
@@ -1,53 +1,52 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { countActions } from '../../database/repositories/moderation-repository.js'; import { countActions } from '../../database/repositories/moderation-repository.js';
import { import {
assertModerationTarget, assertModerationTarget,
fetchTargetMember, fetchTargetMember,
logModerationAction, logModerationAction,
targetNoticeEmbed, notifyTarget,
} from '../../services/moderation/moderation-service.js'; targetNoticeEmbed,
import { successEmbed } from '../../ui/embeds.js'; } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
export const access = ACCESS_LEVELS.STAFF;
export const data = new SlashCommandBuilder()
.setName('warn') export const data = new SlashCommandBuilder()
.setDescription('Avertir un membre') .setName('warn')
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) .setDescription('Avertir un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addStringOption((option) => .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500), .addStringOption((option) =>
); option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500),
);
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) { /** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
const user = interaction.options.getUser('user', true); export async function execute(interaction) {
const reason = interaction.options.getString('reason', true); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason', true);
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target); const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await target const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
.send({ await notifyTarget(target, {
embeds: [ embeds: [
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({ targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
name: 'Avertissements', name: 'Avertissements',
value: String(total), value: String(total),
}), }),
], ],
}) });
.catch(() => {});
await interaction.editReply({
await interaction.editReply({ embeds: [
embeds: [ successEmbed(
successEmbed( `C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`,
`C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`, ),
), ],
], });
}); }
}
+72 -72
View File
@@ -1,72 +1,72 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { import {
addParticipant, addParticipant,
claimTicket, claimTicket,
closeTicket, closeTicket,
createTicket, createTicket,
} from '../../services/tickets/ticket-service.js'; } from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js'; import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service. // `close` is also allowed for the ticket author: checked in the ticket service.
export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF }; export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF };
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('ticket') .setName('ticket')
.setDescription('Tickets de support privés') .setDescription('Tickets de support privés')
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('create') .setName('create')
.setDescription('Ouvrir un ticket') .setDescription('Ouvrir un ticket')
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('category') .setName('category')
.setDescription('Catégorie du ticket') .setDescription('Catégorie du ticket')
.setRequired(true) .setRequired(true)
.addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))), .addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('close') .setName('close')
.setDescription('Fermer le ticket') .setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)), .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)),
) )
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge')) .addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('add') .setName('add')
.setDescription('Ajouter un participant') .setDescription('Ajouter un participant')
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)), .addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
); );
/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */ /** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) { export async function execute(interaction) {
switch (interaction.options.getSubcommand()) { switch (interaction.options.getSubcommand()) {
case 'create': { case 'create': {
const categoryId = interaction.options.getString('category', true); const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId); const channel = await createTicket(interaction, categoryId);
await interaction.editReply({ await interaction.editReply({
embeds: [ embeds: [
successEmbed( successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`, `Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
), ),
], ],
}); });
return; return;
} }
case 'close': case 'close':
await closeTicket(interaction, interaction.options.getString('reason')); await closeTicket(interaction, interaction.options.getString('reason'));
return; return;
case 'claim': case 'claim':
await claimTicket(interaction); await claimTicket(interaction);
return; return;
case 'add': case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id); await addParticipant(interaction, interaction.options.getUser('user', true).id);
return; return;
default: default:
return; return;
} }
} }
+373 -373
View File
@@ -1,373 +1,373 @@
import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js'; import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { import {
activeChannelCount, activeChannelCount,
claimOwnership, claimOwnership,
findTrigger, findTrigger,
kickUser, kickUser,
listTriggerSummaries, listTriggerSummaries,
NAME_MAX, NAME_MAX,
permitUser, permitUser,
postSetupPanel, postSetupPanel,
rejectUser, rejectUser,
removeChannel, removeChannel,
removeVoiceTriggerConfig, removeVoiceTriggerConfig,
renameChannel, renameChannel,
saveVoiceTrigger, saveVoiceTrigger,
setChannelLimit, setChannelLimit,
setTriggerEnabled, setTriggerEnabled,
showInfo, showInfo,
toggleLock, toggleLock,
transferOwnership, transferOwnership,
} from '../../services/voice/voice-service.js'; } from '../../services/voice/voice-service.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { export const subcommandAccess = {
setup: ACCESS_LEVELS.STAFF, setup: ACCESS_LEVELS.STAFF,
panel: ACCESS_LEVELS.STAFF, panel: ACCESS_LEVELS.STAFF,
list: ACCESS_LEVELS.STAFF, list: ACCESS_LEVELS.STAFF,
remove: ACCESS_LEVELS.STAFF, remove: ACCESS_LEVELS.STAFF,
enable: ACCESS_LEVELS.STAFF, enable: ACCESS_LEVELS.STAFF,
disable: ACCESS_LEVELS.STAFF, disable: ACCESS_LEVELS.STAFF,
}; };
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice); const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
/** Longest embed listing worth sending before it gets unreadable. */ /** Longest embed listing worth sending before it gets unreadable. */
const MAX_LISTED_TRIGGERS = 20; const MAX_LISTED_TRIGGERS = 20;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('voice') .setName('voice')
.setDescription('Gestion des salons vocaux temporaires') .setDescription('Gestion des salons vocaux temporaires')
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('setup') .setName('setup')
.setDescription('Ajouter ou modifier un salon déclencheur') .setDescription('Ajouter ou modifier un salon déclencheur')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption( voiceChannelOption(
option option
.setName('trigger') .setName('trigger')
.setDescription('Salon vocal à rejoindre pour créer un salon') .setDescription('Salon vocal à rejoindre pour créer un salon')
.setRequired(true), .setRequired(true),
), ),
) )
.addStringOption((option) => .addStringOption((option) =>
option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40), option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40),
) )
.addChannelOption((option) => .addChannelOption((option) =>
option option
.setName('category') .setName('category')
.setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)') .setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)')
.addChannelTypes(ChannelType.GuildCategory), .addChannelTypes(ChannelType.GuildCategory),
) )
.addStringOption((option) => .addStringOption((option) =>
option option
.setName('template') .setName('template')
.setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)') .setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)')
.setMaxLength(NAME_MAX), .setMaxLength(NAME_MAX),
) )
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('limit') .setName('limit')
.setDescription('Places par défaut (0 = illimité)') .setDescription('Places par défaut (0 = illimité)')
.setMinValue(0) .setMinValue(0)
.setMaxValue(99), .setMaxValue(99),
) )
.addBooleanOption((option) => .addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'), option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'),
), ),
) )
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés')) .addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('panel') .setName('panel')
.setDescription('Republier le panneau d’explication dans les salons déclencheurs') .setDescription('Republier le panneau d’explication dans les salons déclencheurs')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')), voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')),
), ),
) )
.addSubcommandGroup((group) => .addSubcommandGroup((group) =>
group group
.setName('triggers') .setName('triggers')
.setDescription('Gérer les salons déclencheurs') .setDescription('Gérer les salons déclencheurs')
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs')) .addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('remove') .setName('remove')
.setDescription('Supprimer un déclencheur') .setDescription('Supprimer un déclencheur')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('disable') .setName('disable')
.setDescription('Désactiver un déclencheur sans le supprimer') .setDescription('Désactiver un déclencheur sans le supprimer')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('enable') .setName('enable')
.setDescription('Réactiver un déclencheur') .setDescription('Réactiver un déclencheur')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)), voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
), ),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('name') .setName('name')
.setDescription('Renommer ton salon') .setDescription('Renommer ton salon')
.addStringOption((option) => .addStringOption((option) =>
option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX), option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('limit') .setName('limit')
.setDescription('Limiter le nombre de places (0 = illimité)') .setDescription('Limiter le nombre de places (0 = illimité)')
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName('limit') .setName('limit')
.setDescription('Nombre de places') .setDescription('Nombre de places')
.setRequired(true) .setRequired(true)
.setMinValue(0) .setMinValue(0)
.setMaxValue(99), .setMaxValue(99),
), ),
) )
.addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon')) .addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon'))
.addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon')) .addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('permit') .setName('permit')
.setDescription('Autoriser un membre à rejoindre ton salon') .setDescription('Autoriser un membre à rejoindre ton salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('reject') .setName('reject')
.setDescription('Interdire l’accès à un membre') .setDescription('Interdire l’accès à un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('kick') .setName('kick')
.setDescription('Exclure un membre du salon') .setDescription('Exclure un membre du salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)), .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('transfer') .setName('transfer')
.setDescription('Transférer la propriété du salon') .setDescription('Transférer la propriété du salon')
.addUserOption((option) => .addUserOption((option) =>
option.setName('user').setDescription('Nouveau propriétaire').setRequired(true), option.setName('user').setDescription('Nouveau propriétaire').setRequired(true),
), ),
) )
.addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné')) .addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné'))
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('delete') .setName('delete')
.setDescription('Supprimer un salon temporaire') .setDescription('Supprimer un salon temporaire')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
), ),
) )
.addSubcommand((sub) => .addSubcommand((sub) =>
sub sub
.setName('info') .setName('info')
.setDescription('Détails du salon temporaire') .setDescription('Détails du salon temporaire')
.addChannelOption((option) => .addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')), voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
), ),
); );
const ORIGIN_LABELS = { const ORIGIN_LABELS = {
env: 'variables d’environnement', env: 'variables d’environnement',
settings: 'anciens réglages du bot', settings: 'anciens réglages du bot',
}; };
/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */ /** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */
function describeTrigger(trigger, index = null) { function describeTrigger(trigger, index = null) {
const lines = [ const lines = [
`**Salon :** <#${trigger.triggerId}>`, `**Salon :** <#${trigger.triggerId}>`,
`**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`, `**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`,
`**Modèle :** \`${trigger.template}\``, `**Modèle :** \`${trigger.template}\``,
`**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`, `**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`,
`**Salons en cours :** ${trigger.activeChannels ?? 0}`, `**Salons en cours :** ${trigger.activeChannels ?? 0}`,
]; ];
const origin = ORIGIN_LABELS[trigger.source]; const origin = ORIGIN_LABELS[trigger.source];
if (origin) lines.push(`**Origine :** ${origin}`); if (origin) lines.push(`**Origine :** ${origin}`);
return { return {
name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${ name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${
trigger.enabled ? '✅ Actif' : '⛔ Désactivé' trigger.enabled ? '✅ Actif' : '⛔ Désactivé'
}`, }`,
value: lines.join('\n'), value: lines.join('\n'),
}; };
} }
function configEmbed(guildId) { function configEmbed(guildId) {
const triggers = listTriggerSummaries(guildId); const triggers = listTriggerSummaries(guildId);
const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires'); const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires');
if (triggers.length === 0) { if (triggers.length === 0) {
return embed.setDescription( return embed.setDescription(
'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).', 'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).',
); );
} }
embed.setDescription( embed.setDescription(
`**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` + `**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` +
'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.', 'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.',
); );
embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i))); embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i)));
if (triggers.length > MAX_LISTED_TRIGGERS) { if (triggers.length > MAX_LISTED_TRIGGERS) {
embed.addFields({ embed.addFields({
name: 'Autres déclencheurs', name: 'Autres déclencheurs',
value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`, value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`,
}); });
} }
return embed; return embed;
} }
async function runSetup(interaction) { async function runSetup(interaction) {
const channel = interaction.options.getChannel('trigger', true); const channel = interaction.options.getChannel('trigger', true);
if (channel.type !== ChannelType.GuildVoice) { if (channel.type !== ChannelType.GuildVoice) {
throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.'); throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.');
} }
const category = interaction.options.getChannel('category'); const category = interaction.options.getChannel('category');
if (category && category.type !== ChannelType.GuildCategory) { if (category && category.type !== ChannelType.GuildCategory) {
throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.'); throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.');
} }
const existing = findTrigger(interaction.guildId, channel.id); const existing = findTrigger(interaction.guildId, channel.id);
const template = interaction.options.getString('template'); const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit'); const limit = interaction.options.getInteger('limit');
const label = interaction.options.getString('label'); const label = interaction.options.getString('label');
const trigger = saveVoiceTrigger( const trigger = saveVoiceTrigger(
interaction.guildId, interaction.guildId,
{ {
triggerId: channel.id, triggerId: channel.id,
...(label !== null && { label }), ...(label !== null && { label }),
// A trigger with no explicit category hosts its channels in its own category. // A trigger with no explicit category hosts its channels in its own category.
categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null, categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null,
...(template !== null && { template }), ...(template !== null && { template }),
...(limit !== null && { userLimit: limit }), ...(limit !== null && { userLimit: limit }),
}, },
interaction.user.id, interaction.user.id,
); );
if (!trigger) { if (!trigger) {
throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.'); throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.');
} }
const embed = baseEmbed(COLORS.success) const embed = baseEmbed(COLORS.success)
.setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté') .setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté')
.addFields(describeTrigger(trigger)) .addFields(describeTrigger(trigger))
.setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' }); .setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral }); await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
const wantsPanel = interaction.options.getBoolean('panel') ?? true; const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {}); if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {});
} }
/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */ /** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */
async function runTriggerGroup(interaction, subcommand) { async function runTriggerGroup(interaction, subcommand) {
const guildId = interaction.guildId; const guildId = interaction.guildId;
if (subcommand === 'list') { if (subcommand === 'list') {
await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral }); await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral });
return; return;
} }
const target = interaction.options.getChannel('trigger', true); const target = interaction.options.getChannel('trigger', true);
if (subcommand === 'remove') { if (subcommand === 'remove') {
removeVoiceTriggerConfig(guildId, target.id); removeVoiceTriggerConfig(guildId, target.id);
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
successEmbed( successEmbed(
`C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`, `C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`,
), ),
], ],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable'); const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable');
await interaction.reply({ await interaction.reply({
embeds: [ embeds: [
successEmbed( successEmbed(
trigger.enabled trigger.enabled
? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.` ? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.`
: `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`, : `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`,
), ),
], ],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
} }
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */ /** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
export async function execute(interaction) { export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand(); const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel'); const channel = interaction.options.getChannel('channel');
if (interaction.options.getSubcommandGroup(false) === 'triggers') { if (interaction.options.getSubcommandGroup(false) === 'triggers') {
await runTriggerGroup(interaction, subcommand); await runTriggerGroup(interaction, subcommand);
return; return;
} }
switch (subcommand) { switch (subcommand) {
case 'setup': case 'setup':
await runSetup(interaction); await runSetup(interaction);
return; return;
case 'panel': case 'panel':
await postSetupPanel(interaction, { await postSetupPanel(interaction, {
triggerId: interaction.options.getChannel('trigger')?.id ?? null, triggerId: interaction.options.getChannel('trigger')?.id ?? null,
}); });
return; return;
case 'config': case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral }); await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
return; return;
case 'name': case 'name':
await renameChannel(interaction, interaction.options.getString('name', true)); await renameChannel(interaction, interaction.options.getString('name', true));
return; return;
case 'limit': case 'limit':
await setChannelLimit(interaction, interaction.options.getInteger('limit', true)); await setChannelLimit(interaction, interaction.options.getInteger('limit', true));
return; return;
case 'lock': case 'lock':
case 'unlock': case 'unlock':
await toggleLock(interaction, { locked: subcommand === 'lock' }); await toggleLock(interaction, { locked: subcommand === 'lock' });
return; return;
case 'permit': case 'permit':
await permitUser(interaction, interaction.options.getUser('user', true).id); await permitUser(interaction, interaction.options.getUser('user', true).id);
return; return;
case 'reject': case 'reject':
await rejectUser(interaction, interaction.options.getUser('user', true).id); await rejectUser(interaction, interaction.options.getUser('user', true).id);
return; return;
case 'kick': case 'kick':
await kickUser(interaction, interaction.options.getUser('user', true).id); await kickUser(interaction, interaction.options.getUser('user', true).id);
return; return;
case 'transfer': case 'transfer':
await transferOwnership(interaction, interaction.options.getUser('user', true).id); await transferOwnership(interaction, interaction.options.getUser('user', true).id);
return; return;
case 'claim': case 'claim':
await claimOwnership(interaction); await claimOwnership(interaction);
return; return;
case 'delete': case 'delete':
await removeChannel(interaction, { channelId: channel?.id ?? null }); await removeChannel(interaction, { channelId: channel?.id ?? null });
return; return;
case 'info': case 'info':
await showInfo(interaction, { channelId: channel?.id ?? null }); await showInfo(interaction, { channelId: channel?.id ?? null });
return; return;
default: default:
return; return;
} }
} }
+68 -68
View File
@@ -1,68 +1,68 @@
export const BOT_NAME = 'FWS-Bot'; export const BOT_NAME = 'FWS-Bot';
/** Embed colors by category (M12-T01). */ /** Embed colors by category (M12-T01). */
export const COLORS = Object.freeze({ export const COLORS = Object.freeze({
primary: 0x1793d1, primary: 0x1793d1,
success: 0x2ecc71, success: 0x2ecc71,
warning: 0xf1c40f, warning: 0xf1c40f,
error: 0xe74c3c, error: 0xe74c3c,
info: 0x3498db, info: 0x3498db,
gitea: 0x609926, gitea: 0x609926,
moderation: 0xe67e22, moderation: 0xe67e22,
ticket: 0x9b59b6, ticket: 0x9b59b6,
}); });
/** Ordered from least to most privileged (M3-T01). */ /** Ordered from least to most privileged (M3-T01). */
export const ACCESS_LEVELS = Object.freeze({ export const ACCESS_LEVELS = Object.freeze({
USER: 0, USER: 0,
STAFF: 1, STAFF: 1,
DEV: 2, DEV: 2,
OWNER: 3, OWNER: 3,
}); });
/** Same names for the same levels in every message (M12-T02). */ /** Same names for the same levels in every message (M12-T02). */
export const ACCESS_LABELS = Object.freeze({ export const ACCESS_LABELS = Object.freeze({
[ACCESS_LEVELS.USER]: 'Membre', [ACCESS_LEVELS.USER]: 'Membre',
[ACCESS_LEVELS.STAFF]: 'Staff', [ACCESS_LEVELS.STAFF]: 'Staff',
[ACCESS_LEVELS.DEV]: 'Dev', [ACCESS_LEVELS.DEV]: 'Dev',
[ACCESS_LEVELS.OWNER]: 'Owner', [ACCESS_LEVELS.OWNER]: 'Owner',
}); });
/** Moderation actions: Discord label, embed color and stored duration (M8). */ /** Moderation actions: Discord label, embed color and stored duration (M8). */
export const MODERATION_ACTIONS = Object.freeze({ export const MODERATION_ACTIONS = Object.freeze({
warn: { label: 'Avertissement', color: COLORS.warning, duration: false }, warn: { label: 'Avertissement', color: COLORS.warning, duration: false },
mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true }, mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true },
kick: { label: 'Expulsion', color: COLORS.moderation, duration: false }, kick: { label: 'Expulsion', color: COLORS.moderation, duration: false },
ban: { label: 'Bannissement', color: COLORS.error, duration: false }, ban: { label: 'Bannissement', color: COLORS.error, duration: false },
clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false }, clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false },
role: { label: 'Modification de rôle', color: COLORS.primary, duration: false }, role: { label: 'Modification de rôle', color: COLORS.primary, duration: false },
}); });
/** Ticket categories and who can see them (M0-T05 / M6-T01). */ /** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([ export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] }, { id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] },
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] }, { id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] },
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] }, { id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] },
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] }, { id: 'report', label: 'Signalement', scope: ['staff', 'owner'] },
{ id: 'internal', label: 'Demande interne', scope: ['owner'] }, { id: 'internal', label: 'Demande interne', scope: ['owner'] },
]); ]);
/** Gitea webhook event -> notification type (M9-T03). */ /** Gitea webhook event -> notification type (M9-T03). */
export const GITEA_EVENT_TYPES = Object.freeze({ export const GITEA_EVENT_TYPES = Object.freeze({
issues: 'issues', issues: 'issues',
pull_request: 'pull_request', pull_request: 'pull_request',
push: 'push', push: 'push',
create: 'push', create: 'push',
delete: 'push', delete: 'push',
release: 'release', release: 'release',
}); });
export const NOTIFICATION_TYPES = Object.freeze([ export const NOTIFICATION_TYPES = Object.freeze([
'issues', 'issues',
'pull_requests', 'pull_requests',
'commits', 'commits',
'releases', 'releases',
'announcements', 'announcements',
'errors', 'errors',
'community', 'community',
]); ]);
+130 -103
View File
@@ -1,103 +1,130 @@
import { existsSync } from 'node:fs'; import { existsSync } from 'node:fs';
if (existsSync('.env')) { if (existsSync('.env')) {
process.loadEnvFile('.env'); process.loadEnvFile('.env');
} }
const read = (key, fallback = '') => process.env[key]?.trim() || fallback; const read = (key, fallback = '') => process.env[key]?.trim() || fallback;
const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback; const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback;
const readBool = (key, fallback = false) => { const readBool = (key, fallback = false) => {
const value = read(key); const value = read(key);
return value === '' ? fallback : value === 'true'; return value === '' ? fallback : value === 'true';
}; };
/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */ /** Durations accept 0, which `readInt` cannot express because 0 is falsy. */
const readDuration = (key, fallback) => { const readDuration = (key, fallback) => {
const value = read(key); const value = read(key);
if (value === '') return fallback; if (value === '') return fallback;
const parsed = Number.parseInt(value, 10); const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}; };
export const env = Object.freeze({ export const env = Object.freeze({
nodeEnv: read('NODE_ENV', 'development'), nodeEnv: read('NODE_ENV', 'development'),
logLevel: read('LOG_LEVEL', 'info'), logLevel: read('LOG_LEVEL', 'info'),
logDir: read('LOG_DIR', './logs'), logDir: read('LOG_DIR', './logs'),
logRetentionDays: readInt('LOG_RETENTION_DAYS', 30), logRetentionDays: readInt('LOG_RETENTION_DAYS', 30),
discord: { discord: {
token: read('DISCORD_TOKEN'), token: read('DISCORD_TOKEN'),
clientId: read('DISCORD_CLIENT_ID'), clientId: read('DISCORD_CLIENT_ID'),
guildId: read('DISCORD_GUILD_ID'), guildId: read('DISCORD_GUILD_ID'),
}, },
roles: { roles: {
owner: read('ROLE_OWNER_ID'), owner: read('ROLE_OWNER_ID'),
dev: read('ROLE_DEV_ID'), dev: read('ROLE_DEV_ID'),
staff: read('ROLE_STAFF_ID'), staff: read('ROLE_STAFF_ID'),
member: read('ROLE_MEMBER_ID'), member: read('ROLE_MEMBER_ID'),
}, },
channels: { channels: {
welcome: read('CHANNEL_WELCOME_ID'), welcome: read('CHANNEL_WELCOME_ID'),
rules: read('CHANNEL_RULES_ID'), rules: read('CHANNEL_RULES_ID'),
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'), announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
logs: read('CHANNEL_LOGS_ID'), logs: read('CHANNEL_LOGS_ID'),
modLogs: read('CHANNEL_MOD_LOGS_ID'), modLogs: read('CHANNEL_MOD_LOGS_ID'),
ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'), ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'),
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'), notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'), notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'), notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
ticketCategory: read('CATEGORY_TICKETS_ID'), ticketCategory: read('CATEGORY_TICKETS_ID'),
voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'), voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'),
voiceCategory: read('CATEGORY_VOICE_ID'), voiceCategory: read('CATEGORY_VOICE_ID'),
}, },
voice: { voice: {
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000), emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
}, },
bot: { bot: {
statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60), statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60),
}, },
gitea: { gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''), url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'), token: read('GITEA_TOKEN'),
owner: read('GITEA_OWNER'), owner: read('GITEA_OWNER'),
repo: read('GITEA_REPO'), repo: read('GITEA_REPO'),
timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000), timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000),
maxRetries: readInt('GITEA_MAX_RETRIES', 2), maxRetries: readInt('GITEA_MAX_RETRIES', 2),
}, },
webhook: { webhook: {
enabled: readBool('WEBHOOK_ENABLED'), enabled: readBool('WEBHOOK_ENABLED'),
host: read('WEBHOOK_HOST', '0.0.0.0'), host: read('WEBHOOK_HOST', '0.0.0.0'),
port: readInt('WEBHOOK_PORT', 3000), port: readInt('WEBHOOK_PORT', 3000),
path: read('WEBHOOK_PATH', '/webhooks/gitea'), path: read('WEBHOOK_PATH', '/webhooks/gitea'),
secret: read('GITEA_WEBHOOK_SECRET'), secret: read('GITEA_WEBHOOK_SECRET'),
}, },
database: { web: {
path: read('DATABASE_PATH', './data/fws-bot.sqlite'), enabled: readBool('WEB_ENABLED'),
backupDir: read('BACKUP_DIR', './data/backups'), host: read('WEB_HOST', '127.0.0.1'),
}, port: readInt('WEB_PORT', 3080),
publicUrl: read('WEB_PUBLIC_URL', '').replace(/\/+$/, ''),
links: { sessionSecret: read('WEB_SESSION_SECRET'),
website: read('FWS_WEBSITE_URL'), sessionTtlHours: readInt('WEB_SESSION_TTL_HOURS', 12),
docs: read('FWS_DOCS_URL'), oauthClientSecret: read('DISCORD_CLIENT_SECRET'),
discordInvite: read('FWS_DISCORD_INVITE_URL'), setupToken: read('WEB_SETUP_TOKEN'),
archRepo: read('FWS_ARCH_REPO_URL'), // Running shell commands from a browser is the most dangerous capability of the
}, // dashboard, so it stays off until it is explicitly enabled (M16-T06).
}); allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
allowRestart: readBool('WEB_ALLOW_RESTART'),
/** Values that must never appear in Discord messages or logs. */ // The public status page is opt-out rather than opt-in: a bot people rely on
export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean); // owes them a place to check before asking.
publicStatus: readBool('WEB_PUBLIC_STATUS', true),
export function assertRequiredEnv(keys) { deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
const missing = keys.filter((key) => !read(key)); rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
if (missing.length > 0) { },
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
} database: {
} path: read('DATABASE_PATH', './data/fws-bot.sqlite'),
backupDir: read('BACKUP_DIR', './data/backups'),
},
links: {
website: read('FWS_WEBSITE_URL'),
docs: read('FWS_DOCS_URL'),
discordInvite: read('FWS_DISCORD_INVITE_URL'),
archRepo: read('FWS_ARCH_REPO_URL'),
},
});
/** Values that must never appear in Discord messages or logs. */
export const secrets = [
env.discord.token,
env.gitea.token,
env.webhook.secret,
env.web.sessionSecret,
env.web.oauthClientSecret,
env.web.setupToken,
].filter(Boolean);
export function assertRequiredEnv(keys) {
const missing = keys.filter((key) => !read(key));
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
}
+250
View File
@@ -0,0 +1,250 @@
import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js';
import { env } from './env.js';
/**
* Settings a server can change without touching the `.env` (M16-T13).
*
* Single source of truth: the form, the validation and the values the services
* read all come from here. A setting that is not read by anything has no
* business being in this list — a switch that does nothing is worse than no
* switch at all.
*/
export const SETTING_SECTIONS = Object.freeze([
{
id: 'welcome',
title: 'Arrivées et départs',
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
},
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{
id: 'voice',
title: 'Salons vocaux',
summary: 'Salons temporaires créés par les déclencheurs.',
},
{ id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' },
{ id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' },
]);
export const GUILD_SETTINGS = Object.freeze([
// --- Arrivées et départs ---------------------------------------------------
{
key: 'welcome.enabled',
section: 'welcome',
label: 'Message de bienvenue',
help: 'Publier un message dans le salon d’accueil à chaque arrivée.',
type: 'bool',
default: true,
},
{
key: 'welcome.message',
section: 'welcome',
label: 'Texte de bienvenue',
help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.',
type: 'text',
default: 'Bienvenue sur le serveur **{server}** !',
maxLength: 500,
},
{
key: 'welcome.showRules',
section: 'welcome',
label: 'Rappeler le règlement',
help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.',
type: 'bool',
default: true,
},
{
key: 'welcome.directMessage',
section: 'welcome',
label: 'Message privé de bienvenue',
help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.',
type: 'bool',
default: false,
},
{
key: 'members.autoRole',
section: 'welcome',
label: 'Attribuer le rôle d’arrivée',
help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.',
type: 'bool',
default: true,
},
{
key: 'departure.announce',
section: 'welcome',
label: 'Annoncer les départs',
help: 'Publie une ligne dans les logs quand un membre quitte le serveur.',
type: 'bool',
default: true,
},
// --- Modération ------------------------------------------------------------
{
key: 'moderation.dmTarget',
section: 'moderation',
label: 'Prévenir le membre sanctionné',
help: 'Envoie un message privé expliquant la sanction et son motif.',
type: 'bool',
default: true,
},
{
key: 'moderation.defaultMuteMinutes',
section: 'moderation',
label: 'Durée d’exclusion par défaut (min)',
help: 'Proposée quand `/mute` est lancé sans durée.',
type: 'int',
default: 60,
min: 1,
max: 40_320,
},
{
key: 'moderation.banDeleteMessageHours',
section: 'moderation',
label: 'Messages supprimés au bannissement (h)',
help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.',
type: 'int',
default: 0,
min: 0,
max: 168,
advanced: true,
},
// --- Tickets ---------------------------------------------------------------
{
key: 'tickets.deleteChannelOnClose',
section: 'tickets',
label: 'Supprimer le salon à la clôture',
help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.',
type: 'bool',
default: true,
},
// --- Salons vocaux ---------------------------------------------------------
{
key: 'voice.adoptOrphans',
section: 'voice',
label: 'Récupérer les salons orphelins',
help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.',
type: 'bool',
default: true,
},
// --- Notifications ---------------------------------------------------------
{
key: 'notifications.mentionRoleId',
section: 'notifications',
label: 'Rôle à mentionner',
help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.',
type: 'snowflake',
default: '',
advanced: true,
},
// --- Tableau de bord -------------------------------------------------------
{
key: 'deploy.requireConfirmation',
section: 'interface',
label: 'Confirmation avant déploiement',
help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.',
type: 'bool',
default: true,
},
{
key: 'web.defaultMode',
section: 'interface',
label: 'Mode d’affichage par défaut',
help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.',
type: 'enum',
options: ['simple', 'advanced'],
default: 'simple',
},
]);
export const SETTING_BY_KEY = Object.freeze(
Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])),
);
/** Coerces a stored value to the declared type, falling back on the default. */
function coerce(setting, value) {
if (value === null || value === undefined) return setting.default;
switch (setting.type) {
case 'bool':
return Boolean(value);
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return setting.default;
if (setting.min !== undefined && parsed < setting.min) return setting.min;
if (setting.max !== undefined && parsed > setting.max) return setting.max;
return parsed;
}
case 'enum':
return setting.options.includes(value) ? value : setting.default;
default:
return String(value);
}
}
/**
* Reads a setting. Never throws: called from event handlers that must keep
* working even when the database is momentarily unavailable.
*/
export function readSetting(key, guildId = env.discord.guildId) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
return coerce(setting, resolveSetting(guildId, key, setting.default));
}
/** Validates then stores a setting. Returns the stored value. */
export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
const message = validateSetting(key, value);
if (message) throw new Error(message);
const stored = coerce(setting, value);
setSetting(guildId, key, stored, updatedBy);
return stored;
}
/** Returns null when the value is acceptable, a French message otherwise. */
export function validateSetting(key, value) {
const setting = SETTING_BY_KEY[key];
if (!setting) return `Réglage inconnu : ${key}`;
switch (setting.type) {
case 'bool':
return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.';
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.';
if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`;
if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`;
return null;
}
case 'enum':
return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`;
case 'snowflake': {
const text = String(value ?? '').trim();
return text === '' || /^\d{17,20}$/.test(text)
? null
: 'Un identifiant Discord est composé de 17 à 20 chiffres.';
}
default: {
const text = String(value ?? '');
if (setting.maxLength && text.length > setting.maxLength) {
return `${setting.maxLength} caractères maximum.`;
}
return null;
}
}
}
/** Every setting with its current value, for the settings page. */
export function allSettings(guildId = env.discord.guildId) {
return Object.fromEntries(
GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]),
);
}
+26 -26
View File
@@ -1,26 +1,26 @@
import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js'; import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js';
/** /**
* Only the intents required by the bot (M2-T02): * Only the intents required by the bot (M2-T02):
* - Guilds: slash commands, channels, roles * - Guilds: slash commands, channels, roles
* - GuildMembers (privileged): welcome, departures, role assignment * - GuildMembers (privileged): welcome, departures, role assignment
* - GuildModeration: ban/kick audit events * - GuildModeration: ban/kick audit events
* - GuildMessages: /clear and ticket channels * - GuildMessages: /clear and ticket channels
* - GuildVoiceStates: temporary voice channels (M14) * - GuildVoiceStates: temporary voice channels (M14)
* MessageContent is intentionally not requested. * MessageContent is intentionally not requested.
*/ */
export function createClient() { export function createClient() {
const client = new Client({ const client = new Client({
intents: [ intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildVoiceStates,
], ],
partials: [Partials.GuildMember], partials: [Partials.GuildMember],
}); });
client.commands = new Collection(); client.commands = new Collection();
return client; return client;
} }
+28 -28
View File
@@ -1,28 +1,28 @@
import { readdir } from 'node:fs/promises'; import { readdir } from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url'; import { fileURLToPath, pathToFileURL } from 'node:url';
const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands'); const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands');
/** /**
* Loads every command module from src/commands/<category>/<name>.js. * Loads every command module from src/commands/<category>/<name>.js.
* A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`. * A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`.
*/ */
export async function loadCommands() { export async function loadCommands() {
const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true }); const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true });
const commands = []; const commands = [];
for (const entry of entries) { for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith('.js')) continue; if (!entry.isFile() || !entry.name.endsWith('.js')) continue;
const filePath = path.join(entry.parentPath, entry.name); const filePath = path.join(entry.parentPath, entry.name);
const command = await import(pathToFileURL(filePath).href); const command = await import(pathToFileURL(filePath).href);
if (!command.data || typeof command.execute !== 'function') { if (!command.data || typeof command.execute !== 'function') {
throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`); throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`);
} }
commands.push(command); commands.push(command);
} }
return commands; return commands;
} }
+24 -24
View File
@@ -1,24 +1,24 @@
/** Error whose message is safe to show to Discord users. */ /** Error whose message is safe to show to Discord users. */
export class UserFacingError extends Error { export class UserFacingError extends Error {
constructor(message, options) { constructor(message, options) {
super(message, options); super(message, options);
this.name = 'UserFacingError'; this.name = 'UserFacingError';
} }
} }
export class PermissionDeniedError extends UserFacingError { export class PermissionDeniedError extends UserFacingError {
constructor( constructor(
message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.', message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.',
) { ) {
super(message); super(message);
this.name = 'PermissionDeniedError'; this.name = 'PermissionDeniedError';
} }
} }
export class ExternalApiError extends Error { export class ExternalApiError extends Error {
constructor(service, message, options) { constructor(service, message, options) {
super(`[${service}] ${message}`, options); super(`[${service}] ${message}`, options);
this.name = 'ExternalApiError'; this.name = 'ExternalApiError';
this.service = service; this.service = service;
} }
} }
+29 -29
View File
@@ -1,29 +1,29 @@
import { readdir } from 'node:fs/promises'; import { readdir } from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url'; import { fileURLToPath, pathToFileURL } from 'node:url';
import { createLogger } from './logger.js'; import { createLogger } from './logger.js';
const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events'); const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events');
const log = createLogger('events'); const log = createLogger('events');
/** /**
* Registers every event module from src/events. * Registers every event module from src/events.
* An event module exports: `name`, optional `once` and `execute(client, ...args)`. * An event module exports: `name`, optional `once` and `execute(client, ...args)`.
*/ */
export async function registerEvents(client) { export async function registerEvents(client) {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js')); const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
for (const file of files) { for (const file of files) {
const event = await import(pathToFileURL(path.join(eventsDir, file)).href); const event = await import(pathToFileURL(path.join(eventsDir, file)).href);
const handler = async (...args) => { const handler = async (...args) => {
try { try {
await event.execute(client, ...args); await event.execute(client, ...args);
} catch (error) { } catch (error) {
log.error(`Event handler failed: ${event.name}`, error); log.error(`Event handler failed: ${event.name}`, error);
} }
}; };
client[event.once ? 'once' : 'on'](event.name, handler); client[event.once ? 'once' : 'on'](event.name, handler);
log.debug(`Registered event ${event.name}`); log.debug(`Registered event ${event.name}`);
} }
} }
+50 -50
View File
@@ -1,50 +1,50 @@
import { appendFileSync, mkdirSync } from 'node:fs'; import { appendFileSync, mkdirSync } from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { env, secrets } from '../config/env.js'; import { env, secrets } from '../config/env.js';
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }; const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
const threshold = LEVELS[env.logLevel] ?? LEVELS.info; const threshold = LEVELS[env.logLevel] ?? LEVELS.info;
mkdirSync(env.logDir, { recursive: true }); mkdirSync(env.logDir, { recursive: true });
export function maskSecrets(text) { export function maskSecrets(text) {
return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text)); return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text));
} }
function serialize(meta) { function serialize(meta) {
if (meta instanceof Error) { if (meta instanceof Error) {
return { name: meta.name, message: meta.message, stack: meta.stack }; return { name: meta.name, message: meta.message, stack: meta.stack };
} }
return meta; return meta;
} }
function write(level, scope, message, meta) { function write(level, scope, message, meta) {
if (LEVELS[level] < threshold) return; if (LEVELS[level] < threshold) return;
const entry = { const entry = {
time: new Date().toISOString(), time: new Date().toISOString(),
level, level,
scope, scope,
message, message,
...(meta !== undefined && { meta: serialize(meta) }), ...(meta !== undefined && { meta: serialize(meta) }),
}; };
const line = maskSecrets(JSON.stringify(entry)); const line = maskSecrets(JSON.stringify(entry));
const output = level === 'error' || level === 'warn' ? console.error : console.log; const output = level === 'error' || level === 'warn' ? console.error : console.log;
output(line); output(line);
// Technical logs are split per day to simplify retention (M11-T08). // Technical logs are split per day to simplify retention (M11-T08).
const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`); const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`);
appendFileSync(file, `${line}\n`); appendFileSync(file, `${line}\n`);
} }
export function createLogger(scope) { export function createLogger(scope) {
return { return {
debug: (message, meta) => write('debug', scope, message, meta), debug: (message, meta) => write('debug', scope, message, meta),
info: (message, meta) => write('info', scope, message, meta), info: (message, meta) => write('info', scope, message, meta),
warn: (message, meta) => write('warn', scope, message, meta), warn: (message, meta) => write('warn', scope, message, meta),
error: (message, meta) => write('error', scope, message, meta), error: (message, meta) => write('error', scope, message, meta),
}; };
} }
export const logger = createLogger('app'); export const logger = createLogger('app');
+33 -33
View File
@@ -1,33 +1,33 @@
import { ACCESS_LEVELS } from '../config/constants.js'; import { ACCESS_LEVELS } from '../config/constants.js';
import { env } from '../config/env.js'; import { env } from '../config/env.js';
/** /**
* Resolves the highest FWS access level of a guild member (M3-T02). * Resolves the highest FWS access level of a guild member (M3-T02).
* @param {import('discord.js').GuildMember} member * @param {import('discord.js').GuildMember} member
*/ */
export function getAccessLevel(member, roles = env.roles) { export function getAccessLevel(member, roles = env.roles) {
if (!member) return ACCESS_LEVELS.USER; if (!member) return ACCESS_LEVELS.USER;
if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER; if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER;
const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId); const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId);
if (has(roles.owner)) return ACCESS_LEVELS.OWNER; if (has(roles.owner)) return ACCESS_LEVELS.OWNER;
if (has(roles.dev)) return ACCESS_LEVELS.DEV; if (has(roles.dev)) return ACCESS_LEVELS.DEV;
if (has(roles.staff)) return ACCESS_LEVELS.STAFF; if (has(roles.staff)) return ACCESS_LEVELS.STAFF;
return ACCESS_LEVELS.USER; return ACCESS_LEVELS.USER;
} }
export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) { export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) {
return getAccessLevel(member, roles) >= requiredLevel; return getAccessLevel(member, roles) >= requiredLevel;
} }
/** /**
* Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08). * Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08).
* @param {import('discord.js').GuildMember} actor * @param {import('discord.js').GuildMember} actor
* @param {import('discord.js').GuildMember} target * @param {import('discord.js').GuildMember} target
*/ */
export function canActOn(actor, target) { export function canActOn(actor, target) {
if (!actor || !target || actor.id === target.id) return false; if (!actor || !target || actor.id === target.id) return false;
if (target.guild.ownerId === target.id) return false; if (target.guild.ownerId === target.id) return false;
if (actor.guild.ownerId === actor.id) return true; if (actor.guild.ownerId === actor.id) return true;
return actor.roles.highest.comparePositionTo(target.roles.highest) > 0; return actor.roles.highest.comparePositionTo(target.roles.highest) > 0;
} }
+63 -63
View File
@@ -1,63 +1,63 @@
import { mkdirSync, readdirSync, readFileSync } from 'node:fs'; import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { DatabaseSync } from 'node:sqlite'; import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { env } from '../config/env.js'; import { env } from '../config/env.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
const log = createLogger('database'); const log = createLogger('database');
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations'); const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
let db; let db;
function runMigrations(database) { function runMigrations(database) {
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations ( database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY, name TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now')) applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`); )`);
const applied = new Set( const applied = new Set(
database database
.prepare('SELECT name FROM schema_migrations') .prepare('SELECT name FROM schema_migrations')
.all() .all()
.map((row) => row.name), .map((row) => row.name),
); );
const pending = readdirSync(migrationsDir) const pending = readdirSync(migrationsDir)
.filter((file) => file.endsWith('.sql') && !applied.has(file)) .filter((file) => file.endsWith('.sql') && !applied.has(file))
.sort(); .sort();
for (const file of pending) { for (const file of pending) {
database.exec('BEGIN'); database.exec('BEGIN');
try { try {
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8')); database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file); database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
database.exec('COMMIT'); database.exec('COMMIT');
log.info(`Applied migration ${file}`); log.info(`Applied migration ${file}`);
} catch (error) { } catch (error) {
database.exec('ROLLBACK'); database.exec('ROLLBACK');
throw error; throw error;
} }
} }
} }
export function initDatabase(filePath = env.database.path) { export function initDatabase(filePath = env.database.path) {
if (db) return db; if (db) return db;
if (filePath !== ':memory:') { if (filePath !== ':memory:') {
mkdirSync(path.dirname(filePath), { recursive: true }); mkdirSync(path.dirname(filePath), { recursive: true });
} }
db = new DatabaseSync(filePath); db = new DatabaseSync(filePath);
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;'); db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
runMigrations(db); runMigrations(db);
return db; return db;
} }
export function getDatabase() { export function getDatabase() {
if (!db) throw new Error('Database not initialized. Call initDatabase() first.'); if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
return db; return db;
} }
export function closeDatabase() { export function closeDatabase() {
db?.close(); db?.close();
db = undefined; db = undefined;
} }
+97 -97
View File
@@ -1,97 +1,97 @@
-- Server settings, isolated per guild (M3-T06) -- Server settings, isolated per guild (M3-T06)
CREATE TABLE IF NOT EXISTS guild_settings ( CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
key TEXT NOT NULL, key TEXT NOT NULL,
value TEXT, value TEXT,
updated_by TEXT, updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (guild_id, key) PRIMARY KEY (guild_id, key)
); );
-- Notification type -> channel mapping (M9-T01) -- Notification type -> channel mapping (M9-T01)
CREATE TABLE IF NOT EXISTS notification_channels ( CREATE TABLE IF NOT EXISTS notification_channels (
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
type TEXT NOT NULL, type TEXT NOT NULL,
channel_id TEXT NOT NULL, channel_id TEXT NOT NULL,
detail_level TEXT NOT NULL DEFAULT 'normal', detail_level TEXT NOT NULL DEFAULT 'normal',
PRIMARY KEY (guild_id, type) PRIMARY KEY (guild_id, type)
); );
-- Ticket categories (M6-T01) and tickets (M6) -- Ticket categories (M6-T01) and tickets (M6)
CREATE TABLE IF NOT EXISTS ticket_categories ( CREATE TABLE IF NOT EXISTS ticket_categories (
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
id TEXT NOT NULL, id TEXT NOT NULL,
label TEXT NOT NULL, label TEXT NOT NULL,
description TEXT, description TEXT,
scope TEXT NOT NULL, scope TEXT NOT NULL,
PRIMARY KEY (guild_id, id) PRIMARY KEY (guild_id, id)
); );
CREATE TABLE IF NOT EXISTS tickets ( CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
channel_id TEXT UNIQUE, channel_id TEXT UNIQUE,
category_id TEXT NOT NULL, category_id TEXT NOT NULL,
author_id TEXT NOT NULL, author_id TEXT NOT NULL,
claimed_by TEXT, claimed_by TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')),
closed_at TEXT, closed_at TEXT,
closed_by TEXT closed_by TEXT
); );
-- Prevents duplicate open tickets per author and category (M6-T08) -- Prevents duplicate open tickets per author and category (M6-T08)
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
ON tickets (guild_id, author_id, category_id) WHERE status = 'open'; ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
-- Moderation actions (M8) -- Moderation actions (M8)
CREATE TABLE IF NOT EXISTS moderation_actions ( CREATE TABLE IF NOT EXISTS moderation_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')), action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
target_id TEXT, target_id TEXT,
moderator_id TEXT NOT NULL, moderator_id TEXT NOT NULL,
reason TEXT, reason TEXT,
duration_ms INTEGER, duration_ms INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now')) created_at TEXT NOT NULL DEFAULT (datetime('now'))
); );
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id); CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
-- Polls (M10) -- Polls (M10)
CREATE TABLE IF NOT EXISTS polls ( CREATE TABLE IF NOT EXISTS polls (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL, channel_id TEXT NOT NULL,
message_id TEXT UNIQUE, message_id TEXT UNIQUE,
creator_id TEXT NOT NULL, creator_id TEXT NOT NULL,
question TEXT NOT NULL, question TEXT NOT NULL,
choices TEXT NOT NULL, choices TEXT NOT NULL,
ends_at TEXT, ends_at TEXT,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at TEXT NOT NULL DEFAULT (datetime('now')) created_at TEXT NOT NULL DEFAULT (datetime('now'))
); );
CREATE TABLE IF NOT EXISTS poll_votes ( CREATE TABLE IF NOT EXISTS poll_votes (
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE, poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
user_id TEXT NOT NULL, user_id TEXT NOT NULL,
choice_index INTEGER NOT NULL, choice_index INTEGER NOT NULL,
voted_at TEXT NOT NULL DEFAULT (datetime('now')), voted_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (poll_id, user_id) PRIMARY KEY (poll_id, user_id)
); );
-- Functional event log (M11-T05) -- Functional event log (M11-T05)
CREATE TABLE IF NOT EXISTS event_logs ( CREATE TABLE IF NOT EXISTS event_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT, guild_id TEXT,
type TEXT NOT NULL, type TEXT NOT NULL,
actor_id TEXT, actor_id TEXT,
payload TEXT, payload TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')) created_at TEXT NOT NULL DEFAULT (datetime('now'))
); );
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at); CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08) -- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
CREATE TABLE IF NOT EXISTS webhook_deliveries ( CREATE TABLE IF NOT EXISTS webhook_deliveries (
delivery_id TEXT PRIMARY KEY, delivery_id TEXT PRIMARY KEY,
event TEXT NOT NULL, event TEXT NOT NULL,
received_at TEXT NOT NULL DEFAULT (datetime('now')) received_at TEXT NOT NULL DEFAULT (datetime('now'))
); );
+14 -14
View File
@@ -1,14 +1,14 @@
-- Several "join to create" triggers per guild, each with its own home category (M14) -- Several "join to create" triggers per guild, each with its own home category (M14)
CREATE TABLE IF NOT EXISTS voice_triggers ( CREATE TABLE IF NOT EXISTS voice_triggers (
trigger_id TEXT PRIMARY KEY, trigger_id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL, guild_id TEXT NOT NULL,
label TEXT, label TEXT,
category_id TEXT, category_id TEXT,
template TEXT, template TEXT,
user_limit INTEGER NOT NULL DEFAULT 0, user_limit INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1, enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT updated_at TEXT
); );
CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id); CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id);
@@ -0,0 +1,80 @@
-- Web dashboard: sessions, machine tokens, deploy targets and deployments (M16)
-- Browser sessions created by the Discord OAuth2 login (M16-T02).
-- Only the hash of the cookie value is stored, so a database dump cannot be replayed.
CREATE TABLE IF NOT EXISTS web_sessions (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
user_id TEXT,
username TEXT,
display_name TEXT,
avatar TEXT,
access_level INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'discord' CHECK (source IN ('discord', 'setup', 'token')),
ip TEXT,
user_agent TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_seen_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at);
CREATE INDEX IF NOT EXISTS idx_web_sessions_user ON web_sessions (user_id);
-- Long lived tokens for scripts and CI calling the dashboard API (M16-T03).
CREATE TABLE IF NOT EXISTS web_api_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
prefix TEXT NOT NULL,
access_level INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_used_at TEXT,
expires_at TEXT,
revoked_at TEXT
);
-- Where a release can be deployed: a signed webhook, a local command or a Gitea Action (M16-T06).
CREATE TABLE IF NOT EXISTS deploy_targets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
name TEXT NOT NULL,
repository TEXT NOT NULL,
environment TEXT NOT NULL DEFAULT 'production',
kind TEXT NOT NULL CHECK (kind IN ('webhook', 'command', 'gitea-action')),
config TEXT NOT NULL DEFAULT '{}',
auto_deploy INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_deploy_targets_name ON deploy_targets (guild_id, name);
CREATE INDEX IF NOT EXISTS idx_deploy_targets_repo ON deploy_targets (guild_id, repository);
-- One row per deployment attempt. `target_name` is denormalised so the history
-- survives the deletion of its target (M16-T07).
CREATE TABLE IF NOT EXISTS deployments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
target_id INTEGER REFERENCES deploy_targets (id) ON DELETE SET NULL,
target_name TEXT NOT NULL,
repository TEXT NOT NULL,
environment TEXT NOT NULL,
ref TEXT,
release_tag TEXT,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'running', 'success', 'failed', 'cancelled')),
source TEXT NOT NULL DEFAULT 'web',
triggered_by TEXT,
log TEXT,
error TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
started_at TEXT,
finished_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_deployments_target ON deployments (guild_id, target_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments (status, id DESC);
+21
View File
@@ -0,0 +1,21 @@
-- Public wiki pages, written from the dashboard and served without a session (M17)
CREATE TABLE IF NOT EXISTS wiki_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
summary TEXT,
content TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'Général',
position INTEGER NOT NULL DEFAULT 0,
published INTEGER NOT NULL DEFAULT 0,
-- A legal page is protected from deletion: the bot must always be able to
-- point at its terms and its privacy notice.
protected INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_wiki_published ON wiki_pages (published, category, position);
+57
View File
@@ -0,0 +1,57 @@
-- Kanban boards: one per repository, plus one for the organization (M18)
CREATE TABLE IF NOT EXISTS project_boards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
-- 'org' has no repository; 'repo' carries `owner/name`.
scope TEXT NOT NULL CHECK (scope IN ('org', 'repo')),
repository TEXT,
name TEXT NOT NULL,
description TEXT,
archived INTEGER NOT NULL DEFAULT 0,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- One board per repository, and a single organization board per guild.
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_repository
ON project_boards (guild_id, repository) WHERE repository IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_boards_org
ON project_boards (guild_id) WHERE scope = 'org';
CREATE TABLE IF NOT EXISTS project_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
name TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
-- 0 means no limit; above it the column is flagged as overloaded.
wip_limit INTEGER NOT NULL DEFAULT 0,
-- Cards dropped here are considered finished, which drives the board counters.
is_done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_columns_board ON project_columns (board_id, position);
CREATE TABLE IF NOT EXISTS project_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
board_id INTEGER NOT NULL REFERENCES project_boards (id) ON DELETE CASCADE,
column_id INTEGER NOT NULL REFERENCES project_columns (id) ON DELETE CASCADE,
title TEXT NOT NULL,
body TEXT,
position INTEGER NOT NULL DEFAULT 0,
-- Discord id of whoever carries the card.
assignee_id TEXT,
-- `owner/repo#12`, resolved against Gitea when the forge answers.
issue_ref TEXT,
labels TEXT NOT NULL DEFAULT '[]',
due_at TEXT,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_cards_column ON project_cards (column_id, position);
CREATE INDEX IF NOT EXISTS idx_cards_board ON project_cards (board_id);
CREATE INDEX IF NOT EXISTS idx_cards_assignee ON project_cards (board_id, assignee_id);
@@ -0,0 +1,9 @@
-- The legal pages move to the addresses platforms expect (M17)
--
-- Discord, and most app stores, ask for a terms URL and a privacy URL. Serving
-- them under `/wiki/` works but reads badly in a form field, so they move to
-- the root. Renaming rather than recreating keeps whatever the organization
-- has already written in them.
UPDATE wiki_pages SET slug = 'terms-of-service' WHERE slug = 'conditions-utilisation';
UPDATE wiki_pages SET slug = 'privacy-policy' WHERE slug = 'politique-confidentialite';
@@ -1,42 +1,42 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
/** Adds a status and returns the stored row, so the command can show its id. */ /** Adds a status and returns the stored row, so the command can show its id. */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) { export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
const result = getDatabase() const result = getDatabase()
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)') .prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
.run(text, type, url, createdBy); .run(text, type, url, createdBy);
return getBotStatus(Number(result.lastInsertRowid)); return getBotStatus(Number(result.lastInsertRowid));
} }
export function getBotStatus(id) { export function getBotStatus(id) {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null; return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
} }
/** Every status, disabled ones included, in the order they were added. */ /** Every status, disabled ones included, in the order they were added. */
export function listBotStatuses() { export function listBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all(); return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
} }
/** The statuses the rotation is allowed to show. */ /** The statuses the rotation is allowed to show. */
export function listEnabledBotStatuses() { export function listEnabledBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all(); return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
} }
export function setBotStatusEnabled(id, enabled) { export function setBotStatusEnabled(id, enabled) {
return getDatabase() return getDatabase()
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?') .prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
.run(enabled ? 1 : 0, id).changes; .run(enabled ? 1 : 0, id).changes;
} }
export function removeBotStatus(id) { export function removeBotStatus(id) {
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes; return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
} }
export function clearBotStatuses() { export function clearBotStatuses() {
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes; return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
} }
export function countBotStatuses() { export function countBotStatuses() {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get(); const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
return row.count; return row.count;
} }
@@ -0,0 +1,176 @@
import { getDatabase } from '../index.js';
/** Deploy targets and deployment history of the release pipeline (M16-T06 / M16-T07). */
const parseTarget = (row) =>
row
? {
...row,
config: JSON.parse(row.config),
auto_deploy: Boolean(row.auto_deploy),
enabled: Boolean(row.enabled),
}
: null;
export function createTarget({
guildId,
name,
repository,
environment = 'production',
kind,
config = {},
autoDeploy = false,
enabled = true,
createdBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO deploy_targets
(guild_id, name, repository, environment, kind, config, auto_deploy, enabled, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
guildId,
name,
repository,
environment,
kind,
JSON.stringify(config),
autoDeploy ? 1 : 0,
enabled ? 1 : 0,
createdBy,
);
return getTarget(Number(lastInsertRowid));
}
export function getTarget(id) {
return parseTarget(getDatabase().prepare('SELECT * FROM deploy_targets WHERE id = ?').get(id) ?? null);
}
export function listTargets({ guildId, repository = null } = {}) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (repository) {
clauses.push('repository = ?');
params.push(repository);
}
return getDatabase()
.prepare(`SELECT * FROM deploy_targets WHERE ${clauses.join(' AND ')} ORDER BY environment, name`)
.all(...params)
.map(parseTarget);
}
/** Targets eligible for an automatic deployment when a release is published (M16-T08). */
export function listAutoTargets({ guildId, repository }) {
return getDatabase()
.prepare(
`SELECT * FROM deploy_targets
WHERE guild_id = ? AND repository = ? AND auto_deploy = 1 AND enabled = 1
ORDER BY environment, name`,
)
.all(guildId, repository)
.map(parseTarget);
}
const UPDATABLE = Object.freeze({
name: (value) => value,
repository: (value) => value,
environment: (value) => value,
kind: (value) => value,
config: (value) => JSON.stringify(value),
auto_deploy: (value) => (value ? 1 : 0),
enabled: (value) => (value ? 1 : 0),
});
export function updateTarget(id, patch) {
const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE);
if (entries.length === 0) return getTarget(id);
const assignments = entries.map(([key]) => `${key} = ?`).join(', ');
const values = entries.map(([key, value]) => UPDATABLE[key](value));
getDatabase()
.prepare(`UPDATE deploy_targets SET ${assignments}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getTarget(id);
}
export function removeTarget(id) {
return getDatabase().prepare('DELETE FROM deploy_targets WHERE id = ?').run(id).changes;
}
export function createDeployment({
guildId,
targetId = null,
targetName,
repository,
environment,
ref = null,
releaseTag = null,
source = 'web',
triggeredBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO deployments
(guild_id, target_id, target_name, repository, environment, ref, release_tag, source, triggered_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(guildId, targetId, targetName, repository, environment, ref, releaseTag, source, triggeredBy);
return getDeployment(Number(lastInsertRowid));
}
export function getDeployment(id) {
return getDatabase().prepare('SELECT * FROM deployments WHERE id = ?').get(id) ?? null;
}
export function listDeployments({ guildId, targetId = null, repository = null, status = null, limit = 30 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (targetId) {
clauses.push('target_id = ?');
params.push(targetId);
}
if (repository) {
clauses.push('repository = ?');
params.push(repository);
}
if (status) {
clauses.push('status = ?');
params.push(status);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM deployments WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function markRunning(id) {
return getDatabase()
.prepare("UPDATE deployments SET status = 'running', started_at = datetime('now') WHERE id = ?")
.run(id).changes;
}
export function finishDeployment(id, { status, log = null, error = null }) {
return getDatabase()
.prepare(
`UPDATE deployments SET status = ?, log = ?, error = ?, finished_at = datetime('now') WHERE id = ?`,
)
.run(status, log, error, id).changes;
}
/** Counts per status, used by the dashboard tiles. */
export function countByStatus(guildId) {
return getDatabase()
.prepare('SELECT status, COUNT(*) AS count FROM deployments WHERE guild_id = ? GROUP BY status')
.all(guildId);
}
export function lastDeploymentPerEnvironment(guildId) {
return getDatabase()
.prepare(
`SELECT environment, repository, status, release_tag, finished_at, MAX(id) AS id
FROM deployments WHERE guild_id = ? GROUP BY environment, repository ORDER BY environment`,
)
.all(guildId);
}
@@ -1,13 +1,13 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function logEvent({ guildId = null, type, actorId = null, payload = null }) { export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
getDatabase() getDatabase()
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)') .prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null); .run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
} }
export function purgeEventsOlderThan(days) { export function purgeEventsOlderThan(days) {
return getDatabase() return getDatabase()
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)") .prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
.run(`-${days} days`).changes; .run(`-${days} days`).changes;
} }
@@ -1,50 +1,50 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function recordAction({ export function recordAction({
guildId, guildId,
action, action,
moderatorId, moderatorId,
targetId = null, targetId = null,
reason = null, reason = null,
durationMs = null, durationMs = null,
}) { }) {
getDatabase() getDatabase()
.prepare( .prepare(
`INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms) `INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms)
VALUES (?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?)`,
) )
.run(guildId, action, targetId, moderatorId, reason, durationMs); .run(guildId, action, targetId, moderatorId, reason, durationMs);
} }
export function listActions({ guildId, targetId = null, action = null, limit = 20 }) { export function listActions({ guildId, targetId = null, action = null, limit = 20 }) {
const clauses = ['guild_id = ?']; const clauses = ['guild_id = ?'];
const params = [guildId]; const params = [guildId];
if (targetId) { if (targetId) {
clauses.push('target_id = ?'); clauses.push('target_id = ?');
params.push(targetId); params.push(targetId);
} }
if (action) { if (action) {
clauses.push('action = ?'); clauses.push('action = ?');
params.push(action); params.push(action);
} }
params.push(limit); params.push(limit);
return getDatabase() return getDatabase()
.prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) .prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params); .all(...params);
} }
export function countActions({ guildId, targetId, action }) { export function countActions({ guildId, targetId, action }) {
const row = getDatabase() const row = getDatabase()
.prepare( .prepare(
'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?', 'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?',
) )
.get(guildId, targetId, action); .get(guildId, targetId, action);
return row.count; return row.count;
} }
export function countByAction(guildId) { export function countByAction(guildId) {
return getDatabase() return getDatabase()
.prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action') .prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action')
.all(guildId); .all(guildId);
} }
@@ -1,34 +1,34 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
/** Per-guild override of a notification channel (M9-T01). */ /** Per-guild override of a notification channel (M9-T01). */
export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) { export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) {
getDatabase() getDatabase()
.prepare( .prepare(
`INSERT INTO notification_channels (guild_id, type, channel_id, detail_level) `INSERT INTO notification_channels (guild_id, type, channel_id, detail_level)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, type) DO UPDATE SET ON CONFLICT (guild_id, type) DO UPDATE SET
channel_id = excluded.channel_id, channel_id = excluded.channel_id,
detail_level = excluded.detail_level`, detail_level = excluded.detail_level`,
) )
.run(guildId, type, channelId, detailLevel); .run(guildId, type, channelId, detailLevel);
} }
export function getNotificationChannel(guildId, type) { export function getNotificationChannel(guildId, type) {
return ( return (
getDatabase() getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?') .prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?')
.get(guildId, type) ?? null .get(guildId, type) ?? null
); );
} }
export function listNotificationChannels(guildId) { export function listNotificationChannels(guildId) {
return getDatabase() return getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type') .prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type')
.all(guildId); .all(guildId);
} }
export function removeNotificationChannel(guildId, type) { export function removeNotificationChannel(guildId, type) {
return getDatabase() return getDatabase()
.prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?') .prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?')
.run(guildId, type).changes; .run(guildId, type).changes;
} }
+97 -97
View File
@@ -1,97 +1,97 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) { export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) {
const { lastInsertRowid } = getDatabase() const { lastInsertRowid } = getDatabase()
.prepare( .prepare(
`INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at) `INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at)
VALUES (?, ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?)`,
) )
.run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt); .run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt);
return Number(lastInsertRowid); return Number(lastInsertRowid);
} }
export function attachPollMessage(id, messageId) { export function attachPollMessage(id, messageId) {
getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id); getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id);
} }
export function getPoll(id) { export function getPoll(id) {
return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null; return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null;
} }
export function getPollByMessage(messageId) { export function getPollByMessage(messageId) {
return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null; return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null;
} }
export function listPolls({ guildId, status = null, limit = 10 }) { export function listPolls({ guildId, status = null, limit = 10 }) {
const clauses = ['guild_id = ?']; const clauses = ['guild_id = ?'];
const params = [guildId]; const params = [guildId];
if (status) { if (status) {
clauses.push('status = ?'); clauses.push('status = ?');
params.push(status); params.push(status);
} }
params.push(limit); params.push(limit);
return getDatabase() return getDatabase()
.prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) .prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params); .all(...params);
} }
/** Polls whose end date is reached and that are still open (M10-T05). */ /** Polls whose end date is reached and that are still open (M10-T05). */
export function listDuePolls(limit = 10) { export function listDuePolls(limit = 10) {
return getDatabase() return getDatabase()
.prepare( .prepare(
`SELECT * FROM polls `SELECT * FROM polls
WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now') WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now')
ORDER BY ends_at ASC LIMIT ?`, ORDER BY ends_at ASC LIMIT ?`,
) )
.all(limit); .all(limit);
} }
export function listOpenPolls(limit = 25) { export function listOpenPolls(limit = 25) {
return getDatabase() return getDatabase()
.prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?") .prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?")
.all(limit); .all(limit);
} }
export function listVotes(pollId) { export function listVotes(pollId) {
return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId); return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId);
} }
/** Counts votes per choice index: `[{ choice_index, count }]`. */ /** Counts votes per choice index: `[{ choice_index, count }]`. */
export function countVotes(pollId) { export function countVotes(pollId) {
return getDatabase() return getDatabase()
.prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index') .prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index')
.all(pollId); .all(pollId);
} }
/** /**
* Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04). * Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04).
*/ */
export function castVote(pollId, userId, choiceIndex) { export function castVote(pollId, userId, choiceIndex) {
const database = getDatabase(); const database = getDatabase();
const previous = database const previous = database
.prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?') .prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?')
.get(pollId, userId); .get(pollId, userId);
if (previous && previous.choice_index === choiceIndex) return 'unchanged'; if (previous && previous.choice_index === choiceIndex) return 'unchanged';
database database
.prepare( .prepare(
`INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?) `INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?)
ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index, ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index,
voted_at = datetime('now')`, voted_at = datetime('now')`,
) )
.run(pollId, userId, choiceIndex); .run(pollId, userId, choiceIndex);
return previous ? 'changed' : 'created'; return previous ? 'changed' : 'created';
} }
export function closePoll(id) { export function closePoll(id) {
return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id) return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id)
.changes; .changes;
} }
export function countPolls(guildId) { export function countPolls(guildId) {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId); const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId);
return row.count; return row.count;
} }
@@ -0,0 +1,352 @@
import { getDatabase } from '../index.js';
/** Kanban boards, their columns and their cards (M18). */
/** Same wording as the board described in the FWS README. */
export const DEFAULT_COLUMNS = Object.freeze([
{ name: 'À faire', wipLimit: 0, isDone: false },
{ name: 'En cours', wipLimit: 3, isDone: false },
{ name: 'En revue', wipLimit: 0, isDone: false },
{ name: 'Terminé', wipLimit: 0, isDone: true },
]);
const parseBoard = (row) => (row ? { ...row, archived: Boolean(row.archived) } : null);
const parseColumn = (row) => (row ? { ...row, is_done: Boolean(row.is_done) } : null);
const parseCard = (row) => (row ? { ...row, labels: JSON.parse(row.labels || '[]') } : null);
// --- Boards ------------------------------------------------------------------
export function createBoard({
guildId,
scope,
repository = null,
name,
description = null,
createdBy = null,
}) {
const database = getDatabase();
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_boards (guild_id, scope, repository, name, description, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, scope, repository, name, description, createdBy);
const id = Number(lastInsertRowid);
// A board with no column cannot receive a card, so it is never created empty.
for (const [index, column] of DEFAULT_COLUMNS.entries()) {
addColumn({
boardId: id,
name: column.name,
position: index,
wipLimit: column.wipLimit,
isDone: column.isDone,
});
}
return getBoard(id);
}
export function getBoard(id) {
return parseBoard(getDatabase().prepare('SELECT * FROM project_boards WHERE id = ?').get(id) ?? null);
}
export function getBoardByRepository(guildId, repository) {
return parseBoard(
getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? AND repository = ?')
.get(guildId, repository) ?? null,
);
}
export function getOrgBoard(guildId) {
return parseBoard(
getDatabase().prepare("SELECT * FROM project_boards WHERE guild_id = ? AND scope = 'org'").get(guildId) ??
null,
);
}
export function listBoards(guildId) {
return getDatabase()
.prepare('SELECT * FROM project_boards WHERE guild_id = ? ORDER BY scope DESC, name')
.all(guildId)
.map(parseBoard);
}
export function updateBoard(id, { name, description, archived }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (description !== undefined) (fields.push('description = ?'), values.push(description));
if (archived !== undefined) (fields.push('archived = ?'), values.push(archived ? 1 : 0));
if (fields.length === 0) return getBoard(id);
getDatabase()
.prepare(`UPDATE project_boards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getBoard(id);
}
export function removeBoard(id) {
return getDatabase().prepare('DELETE FROM project_boards WHERE id = ?').run(id).changes;
}
// --- Columns -----------------------------------------------------------------
export function addColumn({ boardId, name, position = null, wipLimit = 0, isDone = false }) {
const database = getDatabase();
const nextPosition =
position ??
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_columns WHERE board_id = ?')
.get(boardId).next ??
0;
const { lastInsertRowid } = database
.prepare(
'INSERT INTO project_columns (board_id, name, position, wip_limit, is_done) VALUES (?, ?, ?, ?, ?)',
)
.run(boardId, name, nextPosition, wipLimit, isDone ? 1 : 0);
return getColumn(Number(lastInsertRowid));
}
export function getColumn(id) {
return parseColumn(getDatabase().prepare('SELECT * FROM project_columns WHERE id = ?').get(id) ?? null);
}
export function listColumns(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_columns WHERE board_id = ? ORDER BY position, id')
.all(boardId)
.map(parseColumn);
}
export function updateColumn(id, { name, wipLimit, isDone, position }) {
const fields = [];
const values = [];
if (name !== undefined) (fields.push('name = ?'), values.push(name));
if (wipLimit !== undefined) (fields.push('wip_limit = ?'), values.push(Number(wipLimit) || 0));
if (isDone !== undefined) (fields.push('is_done = ?'), values.push(isDone ? 1 : 0));
if (position !== undefined) (fields.push('position = ?'), values.push(Number(position) || 0));
if (fields.length === 0) return getColumn(id);
getDatabase()
.prepare(`UPDATE project_columns SET ${fields.join(', ')} WHERE id = ?`)
.run(...values, id);
return getColumn(id);
}
export function removeColumn(id) {
return getDatabase().prepare('DELETE FROM project_columns WHERE id = ?').run(id).changes;
}
export function countColumns(boardId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_columns WHERE board_id = ?')
.get(boardId).count;
}
// --- Cards -------------------------------------------------------------------
export function addCard({
boardId,
columnId,
title,
body = null,
assigneeId = null,
issueRef = null,
labels = [],
dueAt = null,
createdBy = null,
}) {
const database = getDatabase();
const next =
database
.prepare('SELECT COALESCE(MAX(position), -1) + 1 AS next FROM project_cards WHERE column_id = ?')
.get(columnId).next ?? 0;
const { lastInsertRowid } = database
.prepare(
`INSERT INTO project_cards
(board_id, column_id, title, body, position, assignee_id, issue_ref, labels, due_at, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
boardId,
columnId,
title,
body,
next,
assigneeId,
issueRef,
JSON.stringify(labels),
dueAt,
createdBy,
);
return getCard(Number(lastInsertRowid));
}
export function getCard(id) {
return parseCard(getDatabase().prepare('SELECT * FROM project_cards WHERE id = ?').get(id) ?? null);
}
export function listCards(boardId) {
return getDatabase()
.prepare('SELECT * FROM project_cards WHERE board_id = ? ORDER BY column_id, position, id')
.all(boardId)
.map(parseCard);
}
export function countCardsInColumn(columnId) {
return getDatabase()
.prepare('SELECT COUNT(*) AS count FROM project_cards WHERE column_id = ?')
.get(columnId).count;
}
export function updateCard(id, { title, body, assigneeId, issueRef, labels, dueAt }) {
const fields = [];
const values = [];
if (title !== undefined) (fields.push('title = ?'), values.push(title));
if (body !== undefined) (fields.push('body = ?'), values.push(body));
if (assigneeId !== undefined) (fields.push('assignee_id = ?'), values.push(assigneeId || null));
if (issueRef !== undefined) (fields.push('issue_ref = ?'), values.push(issueRef || null));
if (labels !== undefined) (fields.push('labels = ?'), values.push(JSON.stringify(labels)));
if (dueAt !== undefined) (fields.push('due_at = ?'), values.push(dueAt || null));
if (fields.length === 0) return getCard(id);
getDatabase()
.prepare(`UPDATE project_cards SET ${fields.join(', ')}, updated_at = datetime('now') WHERE id = ?`)
.run(...values, id);
return getCard(id);
}
/**
* Moves a card to a rank in a column.
*
* The order is rebuilt explicitly — take the column without the card, insert it
* at the wanted index, renumber — rather than nudged with fractional positions.
* Within one column the card has to be removed before being counted back in, a
* subtlety fractional ranks get wrong every time.
*/
export function moveCard(id, { columnId, position = 0 }) {
const database = getDatabase();
const card = getCard(id);
if (!card) return null;
const order = (target) =>
database
.prepare('SELECT id FROM project_cards WHERE column_id = ? ORDER BY position, id')
.all(target)
.map((row) => row.id)
.filter((cardId) => cardId !== id);
const write = (ids, target) => {
for (const [index, cardId] of ids.entries()) {
database
.prepare(
"UPDATE project_cards SET column_id = ?, position = ?, updated_at = datetime('now') WHERE id = ?",
)
.run(target, index, cardId);
}
};
const destination = order(columnId);
const rank = Math.max(0, Math.min(Number(position) || 0, destination.length));
destination.splice(rank, 0, id);
database.exec('BEGIN');
try {
// The column it leaves closes its gap, the one it joins makes room.
if (card.column_id !== columnId) write(order(card.column_id), card.column_id);
write(destination, columnId);
database.exec('COMMIT');
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
return getCard(id);
}
export function removeCard(id) {
return getDatabase().prepare('DELETE FROM project_cards WHERE id = ?').run(id).changes;
}
const parseAssignedCard = (row) => ({
...parseCard(row),
column_is_done: Boolean(row.column_is_done),
});
/**
* Cards carried by one member, across every board of the guild (M19).
*
* The column travels with the card: « what am I on today » cannot be answered
* without knowing whether a card is still open, and asking per card turns the
* page into a staircase of queries. `done_column_id` comes along for the same
* reason — finishing a card from here is then a single move.
*/
export function listCardsForAssignee(guildId, assigneeId) {
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done,
(SELECT d.id FROM project_columns d
WHERE d.board_id = b.id AND d.is_done = 1
ORDER BY d.position, d.id LIMIT 1) AS done_column_id
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id = ?
ORDER BY c.due_at IS NULL, c.due_at, c.id`,
)
.all(guildId, assigneeId)
.map(parseAssignedCard);
}
/**
* Who carries cards, and how many are still open.
*
* Lets the page offer a picker without asking Discord for the member list,
* which is unavailable whenever the bot is offline — precisely when someone is
* most likely to be looking at the dashboard.
*/
export function listAssignees(guildId) {
return getDatabase()
.prepare(
`SELECT c.assignee_id AS assigneeId,
COUNT(*) AS total,
SUM(CASE WHEN col.is_done = 1 THEN 0 ELSE 1 END) AS open
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ? AND c.assignee_id IS NOT NULL AND c.assignee_id <> ''
GROUP BY c.assignee_id
ORDER BY open DESC, total DESC`,
)
.all(guildId);
}
/** Cards whose title, body, labels or issue matches, for the command palette (M19). */
export function searchCards(guildId, term, limit = 8) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT c.*,
b.name AS board_name,
b.scope AS board_scope,
b.repository,
col.name AS column_name,
col.is_done AS column_is_done
FROM project_cards c
JOIN project_boards b ON b.id = c.board_id
JOIN project_columns col ON col.id = c.column_id
WHERE b.guild_id = ?
AND (c.title LIKE ? OR c.body LIKE ? OR c.labels LIKE ? OR c.issue_ref LIKE ?)
ORDER BY col.is_done, c.due_at IS NULL, c.due_at, c.id DESC
LIMIT ?`,
)
.all(guildId, needle, needle, needle, needle, limit)
.map(parseAssignedCard);
}
@@ -1,33 +1,33 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function getSetting(guildId, key, fallback = null) { export function getSetting(guildId, key, fallback = null) {
const row = getDatabase() const row = getDatabase()
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?') .prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
.get(guildId, key); .get(guildId, key);
return row ? JSON.parse(row.value) : fallback; return row ? JSON.parse(row.value) : fallback;
} }
/** /**
* Reads a setting without throwing when the database is not ready (tests, early startup). * Reads a setting without throwing when the database is not ready (tests, early startup).
* Never use it when a missing database should be an error. * Never use it when a missing database should be an error.
*/ */
export function resolveSetting(guildId, key, fallback = null) { export function resolveSetting(guildId, key, fallback = null) {
try { try {
return getSetting(guildId, key, fallback); return getSetting(guildId, key, fallback);
} catch { } catch {
return fallback; return fallback;
} }
} }
export function setSetting(guildId, key, value, updatedBy = null) { export function setSetting(guildId, key, value, updatedBy = null) {
getDatabase() getDatabase()
.prepare( .prepare(
`INSERT INTO guild_settings (guild_id, key, value, updated_by) `INSERT INTO guild_settings (guild_id, key, value, updated_by)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, key) DO UPDATE SET ON CONFLICT (guild_id, key) DO UPDATE SET
value = excluded.value, value = excluded.value,
updated_by = excluded.updated_by, updated_by = excluded.updated_by,
updated_at = datetime('now')`, updated_at = datetime('now')`,
) )
.run(guildId, key, JSON.stringify(value), updatedBy); .run(guildId, key, JSON.stringify(value), updatedBy);
} }
+71 -71
View File
@@ -1,71 +1,71 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function createTicket({ guildId, channelId, categoryId, authorId }) { export function createTicket({ guildId, channelId, categoryId, authorId }) {
const { lastInsertRowid } = getDatabase() const { lastInsertRowid } = getDatabase()
.prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)') .prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)')
.run(guildId, channelId, categoryId, authorId); .run(guildId, channelId, categoryId, authorId);
return Number(lastInsertRowid); return Number(lastInsertRowid);
} }
export function getTicket(id) { export function getTicket(id) {
return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null; return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null;
} }
export function getTicketByChannel(channelId) { export function getTicketByChannel(channelId) {
return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null; return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null;
} }
/** Returns the open ticket of an author for a category, if any (M6-T08). */ /** Returns the open ticket of an author for a category, if any (M6-T08). */
export function getOpenTicket({ guildId, authorId, categoryId }) { export function getOpenTicket({ guildId, authorId, categoryId }) {
return ( return (
getDatabase() getDatabase()
.prepare( .prepare(
`SELECT * FROM tickets `SELECT * FROM tickets
WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`, WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`,
) )
.get(guildId, authorId, categoryId) ?? null .get(guildId, authorId, categoryId) ?? null
); );
} }
export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) { export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) {
const clauses = ['guild_id = ?']; const clauses = ['guild_id = ?'];
const params = [guildId]; const params = [guildId];
if (status) { if (status) {
clauses.push('status = ?'); clauses.push('status = ?');
params.push(status); params.push(status);
} }
if (authorId) { if (authorId) {
clauses.push('author_id = ?'); clauses.push('author_id = ?');
params.push(authorId); params.push(authorId);
} }
params.push(limit); params.push(limit);
return getDatabase() return getDatabase()
.prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) .prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params); .all(...params);
} }
export function claimTicket(id, userId) { export function claimTicket(id, userId) {
return getDatabase() return getDatabase()
.prepare( .prepare(
"UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'", "UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'",
) )
.run(userId, id).changes; .run(userId, id).changes;
} }
export function closeTicket(id, { closedBy, reason = null }) { export function closeTicket(id, { closedBy, reason = null }) {
return getDatabase() return getDatabase()
.prepare( .prepare(
`UPDATE tickets `UPDATE tickets
SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ? SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ?
WHERE id = ? AND status = 'open'`, WHERE id = ? AND status = 'open'`,
) )
.run(closedBy, reason, id).changes; .run(closedBy, reason, id).changes;
} }
export function countOpenTickets(guildId) { export function countOpenTickets(guildId) {
const row = getDatabase() const row = getDatabase()
.prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'") .prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'")
.get(guildId); .get(guildId);
return row.count; return row.count;
} }
+72 -72
View File
@@ -1,72 +1,72 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) { export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) {
getDatabase() getDatabase()
.prepare( .prepare(
`INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit) `INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (channel_id) DO UPDATE SET ON CONFLICT (channel_id) DO UPDATE SET
owner_id = excluded.owner_id, owner_id = excluded.owner_id,
name = excluded.name`, name = excluded.name`,
) )
.run(channelId, guildId, ownerId, triggerId, name, userLimit); .run(channelId, guildId, ownerId, triggerId, name, userLimit);
} }
export function getVoiceChannel(channelId) { export function getVoiceChannel(channelId) {
return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null; return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null;
} }
export function listVoiceChannels(guildId) { export function listVoiceChannels(guildId) {
return getDatabase() return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC') .prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC')
.all(guildId); .all(guildId);
} }
/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */ /** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */
export function listOwnedVoiceChannels(guildId, ownerId) { export function listOwnedVoiceChannels(guildId, ownerId) {
return getDatabase() return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC') .prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC')
.all(guildId, ownerId); .all(guildId, ownerId);
} }
export function setVoiceOwner(channelId, ownerId) { export function setVoiceOwner(channelId, ownerId) {
return getDatabase() return getDatabase()
.prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?') .prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?')
.run(ownerId, channelId).changes; .run(ownerId, channelId).changes;
} }
export function setVoiceName(channelId, name) { export function setVoiceName(channelId, name) {
return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId) return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId)
.changes; .changes;
} }
export function setVoiceLocked(channelId, locked) { export function setVoiceLocked(channelId, locked) {
return getDatabase() return getDatabase()
.prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?') .prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?')
.run(locked ? 1 : 0, channelId).changes; .run(locked ? 1 : 0, channelId).changes;
} }
export function setVoiceLimit(channelId, userLimit) { export function setVoiceLimit(channelId, userLimit) {
return getDatabase() return getDatabase()
.prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?') .prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?')
.run(userLimit, channelId).changes; .run(userLimit, channelId).changes;
} }
export function removeVoiceChannel(channelId) { export function removeVoiceChannel(channelId) {
return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes; return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes;
} }
export function countVoiceChannels(guildId) { export function countVoiceChannels(guildId) {
const row = getDatabase() const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?') .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?')
.get(guildId); .get(guildId);
return row.count; return row.count;
} }
/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */ /** Channels still alive for one trigger, used by the configuration embed (M14-T01). */
export function countVoiceChannelsByTrigger(triggerId) { export function countVoiceChannelsByTrigger(triggerId) {
const row = getDatabase() const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?') .prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?')
.get(triggerId); .get(triggerId);
return row.count; return row.count;
} }
@@ -1,52 +1,52 @@
import { getDatabase } from '../index.js'; import { getDatabase } from '../index.js';
/** /**
* Declares (or updates) a trigger channel. Every value is explicit: the service merges the * Declares (or updates) a trigger channel. Every value is explicit: the service merges the
* previous row before writing, so an omitted option keeps its stored value (M14-T01). * previous row before writing, so an omitted option keeps its stored value (M14-T01).
*/ */
export function upsertVoiceTrigger({ export function upsertVoiceTrigger({
triggerId, triggerId,
guildId, guildId,
label = null, label = null,
categoryId = null, categoryId = null,
template = null, template = null,
userLimit = 0, userLimit = 0,
enabled = true, enabled = true,
}) { }) {
getDatabase() getDatabase()
.prepare( .prepare(
`INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled) `INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled)
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (trigger_id) DO UPDATE SET ON CONFLICT (trigger_id) DO UPDATE SET
guild_id = excluded.guild_id, guild_id = excluded.guild_id,
label = excluded.label, label = excluded.label,
category_id = excluded.category_id, category_id = excluded.category_id,
template = excluded.template, template = excluded.template,
user_limit = excluded.user_limit, user_limit = excluded.user_limit,
enabled = excluded.enabled, enabled = excluded.enabled,
updated_at = datetime('now')`, updated_at = datetime('now')`,
) )
.run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0); .run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0);
} }
export function getVoiceTrigger(triggerId) { export function getVoiceTrigger(triggerId) {
return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null; return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null;
} }
/** All the triggers of a guild, disabled ones included, in creation order. */ /** All the triggers of a guild, disabled ones included, in creation order. */
export function listVoiceTriggers(guildId) { export function listVoiceTriggers(guildId) {
return getDatabase() return getDatabase()
.prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC') .prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC')
.all(guildId); .all(guildId);
} }
export function removeVoiceTrigger(triggerId) { export function removeVoiceTrigger(triggerId) {
return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes; return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes;
} }
export function countVoiceTriggers(guildId) { export function countVoiceTriggers(guildId) {
const row = getDatabase() const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?') .prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?')
.get(guildId); .get(guildId);
return row.count; return row.count;
} }
@@ -0,0 +1,107 @@
import { getDatabase } from '../index.js';
/** Browser sessions and machine tokens of the web dashboard (M16-T02 / M16-T03). */
export function createSession({
id,
tokenHash,
userId = null,
username = null,
displayName = null,
avatar = null,
accessLevel = 0,
source = 'discord',
ip = null,
userAgent = null,
expiresAt,
}) {
getDatabase()
.prepare(
`INSERT INTO web_sessions
(id, token_hash, user_id, username, display_name, avatar, access_level, source, ip, user_agent, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(id, tokenHash, userId, username, displayName, avatar, accessLevel, source, ip, userAgent, expiresAt);
return getSession(id);
}
export function getSession(id) {
return getDatabase().prepare('SELECT * FROM web_sessions WHERE id = ?').get(id) ?? null;
}
/** Only returns sessions that have not expired, so callers never have to check. */
export function getLiveSessionByHash(tokenHash) {
return (
getDatabase()
.prepare("SELECT * FROM web_sessions WHERE token_hash = ? AND expires_at > datetime('now')")
.get(tokenHash) ?? null
);
}
export function touchSession(id) {
return getDatabase().prepare("UPDATE web_sessions SET last_seen_at = datetime('now') WHERE id = ?").run(id)
.changes;
}
export function deleteSession(id) {
return getDatabase().prepare('DELETE FROM web_sessions WHERE id = ?').run(id).changes;
}
export function deleteSessionsOfUser(userId) {
return getDatabase().prepare('DELETE FROM web_sessions WHERE user_id = ?').run(userId).changes;
}
export function listSessions(limit = 50) {
return getDatabase()
.prepare(
`SELECT id, user_id, username, display_name, avatar, access_level, source, ip, user_agent,
created_at, last_seen_at, expires_at
FROM web_sessions WHERE expires_at > datetime('now') ORDER BY last_seen_at DESC LIMIT ?`,
)
.all(limit);
}
export function purgeExpiredSessions() {
return getDatabase().prepare("DELETE FROM web_sessions WHERE expires_at <= datetime('now')").run().changes;
}
export function createApiToken({ name, tokenHash, prefix, accessLevel, createdBy = null, expiresAt = null }) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO web_api_tokens (name, token_hash, prefix, access_level, created_by, expires_at)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(name, tokenHash, prefix, accessLevel, createdBy, expiresAt);
return Number(lastInsertRowid);
}
export function getLiveApiTokenByHash(tokenHash) {
return (
getDatabase()
.prepare(
`SELECT * FROM web_api_tokens
WHERE token_hash = ? AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > datetime('now'))`,
)
.get(tokenHash) ?? null
);
}
export function touchApiToken(id) {
getDatabase().prepare("UPDATE web_api_tokens SET last_used_at = datetime('now') WHERE id = ?").run(id);
}
export function listApiTokens() {
return getDatabase()
.prepare(
`SELECT id, name, prefix, access_level, created_by, created_at, last_used_at, expires_at, revoked_at
FROM web_api_tokens ORDER BY id DESC`,
)
.all();
}
export function revokeApiToken(id) {
return getDatabase()
.prepare("UPDATE web_api_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL")
.run(id).changes;
}
@@ -0,0 +1,106 @@
import { getDatabase } from '../index.js';
/** Public wiki pages (M17). */
const parse = (row) =>
row ? { ...row, published: Boolean(row.published), protected: Boolean(row.protected) } : null;
export function createPage({
slug,
title,
summary = null,
content = '',
category = 'Général',
position = 0,
published = false,
isProtected = false,
createdBy = null,
}) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO wiki_pages
(slug, title, summary, content, category, position, published, protected, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
slug,
title,
summary,
content,
category,
position,
published ? 1 : 0,
isProtected ? 1 : 0,
createdBy,
createdBy,
);
return getPage(Number(lastInsertRowid));
}
export function getPage(id) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE id = ?').get(id) ?? null);
}
export function getPageBySlug(slug) {
return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE slug = ?').get(slug) ?? null);
}
/** Published pages only, in reading order — what the public site shows. */
export function listPublished() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages WHERE published = 1 ORDER BY category, position, title')
.all()
.map(parse);
}
export function listAllPages() {
return getDatabase()
.prepare('SELECT * FROM wiki_pages ORDER BY category, position, title')
.all()
.map(parse);
}
const UPDATABLE = Object.freeze({
slug: (value) => value,
title: (value) => value,
summary: (value) => value,
content: (value) => value,
category: (value) => value,
position: (value) => Number.parseInt(value, 10) || 0,
published: (value) => (value ? 1 : 0),
});
export function updatePage(id, patch, updatedBy = null) {
const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE);
if (entries.length === 0) return getPage(id);
const assignments = entries.map(([key]) => `${key} = ?`).join(', ');
const values = entries.map(([key, value]) => UPDATABLE[key](value));
getDatabase()
.prepare(
`UPDATE wiki_pages SET ${assignments}, updated_by = ?, updated_at = datetime('now') WHERE id = ?`,
)
.run(...values, updatedBy, id);
return getPage(id);
}
export function removePage(id) {
return getDatabase().prepare('DELETE FROM wiki_pages WHERE id = ? AND protected = 0').run(id).changes;
}
export function countPages() {
return getDatabase().prepare('SELECT COUNT(*) AS count FROM wiki_pages').get().count;
}
/** Full-text-ish search over the published pages, good enough for a small wiki. */
export function searchPublished(term) {
const needle = `%${term}%`;
return getDatabase()
.prepare(
`SELECT * FROM wiki_pages
WHERE published = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?)
ORDER BY category, position, title LIMIT 25`,
)
.all(needle, needle, needle)
.map(parse);
}
+10 -10
View File
@@ -1,10 +1,10 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
const log = createLogger('discord'); const log = createLogger('discord');
export const name = Events.Error; export const name = Events.Error;
export async function execute(_client, error) { export async function execute(_client, error) {
log.error('Discord client error', error); log.error('Discord client error', error);
} }
+30 -21
View File
@@ -1,21 +1,30 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js'; import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js'; import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js'; import {
adoptOrphanVoiceChannels,
const log = createLogger('discord'); startVoiceJanitor,
sweepVoiceChannels,
export const name = Events.ClientReady; } from '../services/voice/voice-service.js';
export const once = true;
const log = createLogger('discord');
export async function execute(client) {
startPollScheduler(client); export const name = Events.ClientReady;
await sweepVoiceChannels(client); export const once = true;
startVoiceJanitor(client);
startBotStatusRotation(client); export async function execute(client) {
log.info(`Connected as ${client.user.tag}`, { startPollScheduler(client);
guilds: client.guilds.cache.size, // Channels outlive the process: take back the ones the database forgot before
commands: client.commands.size, // the sweep decides they are not ours.
}); await adoptOrphanVoiceChannels(client).catch((error) =>
} log.warn('Could not recover the orphan voice channels', error),
);
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
});
}
+21 -20
View File
@@ -1,20 +1,21 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { readSetting } from '../config/guild-settings.js';
import { import { createLogger } from '../core/logger.js';
assignMemberRole, import {
sendWelcome, assignMemberRole,
sendWelcomeDirectMessage, sendWelcome,
} from '../services/members/member-service.js'; sendWelcomeDirectMessage,
} from '../services/members/member-service.js';
const log = createLogger('members');
const log = createLogger('members');
export const name = Events.GuildMemberAdd;
export const name = Events.GuildMemberAdd;
/** Welcome message, resources and default role (M7-T01..T04). */
export async function execute(client, member) { /** Welcome message, resources and default role (M7-T01..T04). */
log.info('Member joined', { userId: member.id, guildId: member.guild.id }); export async function execute(client, member) {
log.info('Member joined', { userId: member.id, guildId: member.guild.id });
await assignMemberRole(member);
await sendWelcome(client, member); await assignMemberRole(member);
await sendWelcomeDirectMessage(member); await sendWelcome(client, member);
} if (readSetting('welcome.directMessage', member.guild.id)) await sendWelcomeDirectMessage(member);
}
+13 -13
View File
@@ -1,13 +1,13 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { announceDeparture } from '../services/members/member-service.js'; import { announceDeparture } from '../services/members/member-service.js';
const log = createLogger('members'); const log = createLogger('members');
export const name = Events.GuildMemberRemove; export const name = Events.GuildMemberRemove;
/** Announces and records departures (M7-T04). */ /** Announces and records departures (M7-T04). */
export async function execute(client, member) { export async function execute(client, member) {
log.info('Member left', { userId: member.id, guildId: member.guild.id }); log.info('Member left', { userId: member.id, guildId: member.guild.id });
await announceDeparture(client, member); await announceDeparture(client, member);
} }
+88 -88
View File
@@ -1,88 +1,88 @@
import { Events, MessageFlags } from 'discord.js'; import { Events, MessageFlags } from 'discord.js';
import { ACCESS_LABELS } from '../config/constants.js'; import { ACCESS_LABELS } from '../config/constants.js';
import { PermissionDeniedError, UserFacingError } from '../core/errors.js'; import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js'; import { hasAccess } from '../core/permissions.js';
import { handleGiteaModal } from '../services/gitea/gitea-modals.js'; import { handleGiteaModal } from '../services/gitea/gitea-modals.js';
import { handlePollComponent } from '../services/polls/poll-service.js'; import { handlePollComponent } from '../services/polls/poll-service.js';
import { handleTicketComponent } from '../services/tickets/ticket-service.js'; import { handleTicketComponent } from '../services/tickets/ticket-service.js';
import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js'; import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js';
import { errorEmbed } from '../ui/embeds.js'; import { errorEmbed } from '../ui/embeds.js';
const log = createLogger('interactions'); const log = createLogger('interactions');
export const name = Events.InteractionCreate; export const name = Events.InteractionCreate;
/** Custom id prefix -> handlers for the message components and the modals. */ /** Custom id prefix -> handlers for the message components and the modals. */
const routes = [ const routes = [
{ prefix: 'ticket:', component: handleTicketComponent }, { prefix: 'ticket:', component: handleTicketComponent },
{ prefix: 'poll:', component: handlePollComponent }, { prefix: 'poll:', component: handlePollComponent },
{ prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal }, { prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal },
{ prefix: 'issue:', modal: handleGiteaModal }, { prefix: 'issue:', modal: handleGiteaModal },
{ prefix: 'pr:', modal: handleGiteaModal }, { prefix: 'pr:', modal: handleGiteaModal },
]; ];
async function replyError(interaction, message) { async function replyError(interaction, message) {
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral }; const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) { if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload); await interaction.followUp(payload);
} else { } else {
await interaction.reply(payload); await interaction.reply(payload);
} }
} }
async function runChatInputCommand(interaction) { async function runChatInputCommand(interaction) {
const command = interaction.client.commands.get(interaction.commandName); const command = interaction.client.commands.get(interaction.commandName);
if (!command) return; if (!command) return;
const subcommand = interaction.options.getSubcommand(false); const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access; const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) { if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError( throw new PermissionDeniedError(
`Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`, `Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`,
); );
} }
await command.execute(interaction); await command.execute(interaction);
} }
async function runRoute(interaction, kind) { async function runRoute(interaction, kind) {
const route = routes.find( const route = routes.find(
({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix), ({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix),
); );
if (!route) { if (!route) {
log.debug(`Ignored ${kind} ${interaction.customId}`); log.debug(`Ignored ${kind} ${interaction.customId}`);
return; return;
} }
await route[kind](interaction); await route[kind](interaction);
} }
export async function execute(_client, interaction) { export async function execute(_client, interaction) {
try { try {
if (interaction.isAutocomplete()) { if (interaction.isAutocomplete()) {
await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction); await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction);
return; return;
} }
if (interaction.isButton() || interaction.isAnySelectMenu()) { if (interaction.isButton() || interaction.isAnySelectMenu()) {
await runRoute(interaction, 'component'); await runRoute(interaction, 'component');
return; return;
} }
if (interaction.isModalSubmit()) { if (interaction.isModalSubmit()) {
await runRoute(interaction, 'modal'); await runRoute(interaction, 'modal');
return; return;
} }
if (!interaction.isChatInputCommand()) return; if (!interaction.isChatInputCommand()) return;
await runChatInputCommand(interaction); await runChatInputCommand(interaction);
} catch (error) { } catch (error) {
if (error instanceof UserFacingError) { if (error instanceof UserFacingError) {
await replyError(interaction, error.message); await replyError(interaction, error.message);
return; return;
} }
log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error); log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error);
await replyError( await replyError(
interaction, interaction,
'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.', 'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.',
).catch(() => {}); ).catch(() => {});
} }
} }
+11 -11
View File
@@ -1,11 +1,11 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
const log = createLogger('discord'); const log = createLogger('discord');
// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08). // discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08).
export const name = Events.ShardDisconnect; export const name = Events.ShardDisconnect;
export async function execute(_client, closeEvent, shardId) { export async function execute(_client, closeEvent, shardId) {
log.warn('Shard disconnected', { shardId, code: closeEvent?.code }); log.warn('Shard disconnected', { shardId, code: closeEvent?.code });
} }
+32 -32
View File
@@ -1,32 +1,32 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } from '../services/voice/voice-service.js'; import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } from '../services/voice/voice-service.js';
const log = createLogger('voice'); const log = createLogger('voice');
export const name = Events.VoiceStateUpdate; export const name = Events.VoiceStateUpdate;
/** /**
* Joining any of the trigger channels creates a private channel in that trigger's category and * Joining any of the trigger channels creates a private channel in that trigger's category and
* moves the member in; leaving a temporary channel deletes it once the last member is gone * moves the member in; leaving a temporary channel deletes it once the last member is gone
* (M14-T02 / M14-T04). * (M14-T02 / M14-T04).
*/ */
export async function execute(_client, oldState, newState) { export async function execute(_client, oldState, newState) {
const member = newState.member ?? oldState.member; const member = newState.member ?? oldState.member;
if (!member || member.user.bot) return; if (!member || member.user.bot) return;
try { try {
const joinedId = const joinedId =
newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null; newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null;
if (joinedId) { if (joinedId) {
const trigger = getVoiceTrigger(newState.guild.id, joinedId); const trigger = getVoiceTrigger(newState.guild.id, joinedId);
if (trigger) await createFromTrigger(member, trigger); if (trigger) await createFromTrigger(member, trigger);
} }
if (oldState.channelId && oldState.channelId !== newState.channelId) { if (oldState.channelId && oldState.channelId !== newState.channelId) {
await cleanupVoiceChannel(oldState.guild, oldState.channelId); await cleanupVoiceChannel(oldState.guild, oldState.channelId);
} }
} catch (error) { } catch (error) {
log.error('Voice state handling failed', error); log.error('Voice state handling failed', error);
} }
} }
+53 -35
View File
@@ -1,35 +1,53 @@
import { assertRequiredEnv, env } from './config/env.js'; import { assertRequiredEnv, env } from './config/env.js';
import { createClient } from './core/client.js'; import { createClient } from './core/client.js';
import { loadCommands } from './core/command-loader.js'; import { loadCommands } from './core/command-loader.js';
import { registerEvents } from './core/event-loader.js'; import { registerEvents } from './core/event-loader.js';
import { logger } from './core/logger.js'; import { logger } from './core/logger.js';
import { closeDatabase, initDatabase } from './database/index.js'; import { closeDatabase, initDatabase } from './database/index.js';
import { startWebhookServer } from './webhooks/server.js'; import { startWebServer, webhookSharesWebPort } from './web/server.js';
import { startWebhookServer } from './webhooks/server.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
try {
initDatabase(); assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
} catch (error) {
const client = createClient(); logger.error(`${error.message}. Lance \`npm run setup\` pour remplir le .env pas à pas.`);
throw error;
for (const command of await loadCommands()) { }
client.commands.set(command.data.name, command);
} initDatabase();
await registerEvents(client);
const client = createClient();
const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null;
for (const command of await loadCommands()) {
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason)); client.commands.set(command.data.name, command);
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error)); }
await registerEvents(client);
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`); // When both listen on the same port, the dashboard serves the webhook route too.
webhookServer?.close(); const webServer = env.web.enabled ? startWebServer({ client }) : null;
await client.destroy(); const webhookServer = env.webhook.enabled && !webhookSharesWebPort() ? startWebhookServer(client) : null;
closeDatabase();
process.exit(0); // Saying nothing when the dashboard is off is how an afternoon gets lost
} // looking for a site that was never asked to start.
process.once('SIGINT', shutdown); if (!env.web.enabled) {
process.once('SIGTERM', shutdown); logger.warn(
'Le tableau de bord est désactivé : `WEB_ENABLED` ne vaut pas `true`. ' +
await client.login(env.discord.token); 'Aucun site ne sera servi. Mets `WEB_ENABLED=true` dans le .env puis redémarre.',
);
}
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`);
webhookServer?.close();
webServer?.close();
await client.destroy();
closeDatabase();
process.exit(0);
}
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
await client.login(env.discord.token);
+153
View File
@@ -0,0 +1,153 @@
import { env } from '../../config/env.js';
import { asList, giteaRequest } from './gitea-client.js';
/**
* Administration endpoints used by the web dashboard (M16-T04).
*
* `gitea-client.js` stays focused on the single repository the Discord commands
* talk to; this module addresses any repository of the organization, which is
* what the dashboard needs.
*/
const query = (params = {}) => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null && value !== '') search.set(key, String(value));
}
const rendered = search.toString();
return rendered ? `?${rendered}` : '';
};
const path = (owner, repo) => `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
/** Organization the dashboard manages by default. */
export const defaultOwner = () => env.gitea.owner;
export const org = {
get: (owner = defaultOwner()) => giteaRequest(`/orgs/${encodeURIComponent(owner)}`),
update: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}`, { method: 'PATCH', body: payload }),
listRepos: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos${query({ page, limit })}`).then(asList),
listMembers: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/members${query({ page, limit })}`).then(asList),
listTeams: ({ owner = defaultOwner(), page = 1, limit = 50 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/teams${query({ page, limit })}`).then(asList),
listTeamMembers: (teamId) => giteaRequest(`/teams/${teamId}/members`).then(asList),
listLabels: ({ owner = defaultOwner(), limit = 100 } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/labels${query({ limit })}`).then(asList),
listHooks: ({ owner = defaultOwner() } = {}) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/hooks`).then(asList),
createRepo: (payload, owner = defaultOwner()) =>
giteaRequest(`/orgs/${encodeURIComponent(owner)}/repos`, { method: 'POST', body: payload }),
/**
* Issues and pull requests of the whole organization, in one request.
*
* The per-repository endpoint would mean one call per repository, which the
* command palette cannot afford on every keystroke. Absent before Gitea 1.15,
* so callers tolerate a rejection.
*/
searchIssues: ({ owner = defaultOwner(), q, state = 'open', type, limit = 10 } = {}) =>
giteaRequest(`/repos/issues/search${query({ q, owner, state, type, limit })}`).then(asList),
/** Identity behind `GITEA_TOKEN`, used by the settings page to check the credentials. */
whoami: () => giteaRequest('/user'),
};
export const repos = {
get: (owner, repo) => giteaRequest(path(owner, repo)),
update: (owner, repo, payload) => giteaRequest(path(owner, repo), { method: 'PATCH', body: payload }),
remove: (owner, repo) => giteaRequest(path(owner, repo), { method: 'DELETE' }),
listBranches: (owner, repo, { page = 1, limit = 50 } = {}) =>
giteaRequest(`${path(owner, repo)}/branches${query({ page, limit })}`).then(asList),
createBranch: (owner, repo, { newBranchName, oldBranchName }) =>
giteaRequest(`${path(owner, repo)}/branches`, {
method: 'POST',
body: { new_branch_name: newBranchName, old_branch_name: oldBranchName },
}),
removeBranch: (owner, repo, branch) =>
giteaRequest(`${path(owner, repo)}/branches/${encodeURIComponent(branch)}`, { method: 'DELETE' }),
listTags: (owner, repo, { limit = 50 } = {}) =>
giteaRequest(`${path(owner, repo)}/tags${query({ limit })}`).then(asList),
listCommits: (owner, repo, { sha, page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/commits${query({ sha, page, limit })}`).then(asList),
languages: (owner, repo) => giteaRequest(`${path(owner, repo)}/languages`),
listTopics: (owner, repo) => giteaRequest(`${path(owner, repo)}/topics`),
replaceTopics: (owner, repo, topics) =>
giteaRequest(`${path(owner, repo)}/topics`, { method: 'PUT', body: { topics } }),
listIssues: (owner, repo, { state = 'open', type = 'issues', page = 1, limit = 20, q } = {}) =>
giteaRequest(`${path(owner, repo)}/issues${query({ state, type, page, limit, q })}`).then(asList),
createIssue: (owner, repo, { title, body, labels, assignees }) =>
giteaRequest(`${path(owner, repo)}/issues`, { method: 'POST', body: { title, body, labels, assignees } }),
updateIssue: (owner, repo, number, payload) =>
giteaRequest(`${path(owner, repo)}/issues/${number}`, { method: 'PATCH', body: payload }),
commentIssue: (owner, repo, number, body) =>
giteaRequest(`${path(owner, repo)}/issues/${number}/comments`, { method: 'POST', body: { body } }),
listLabels: (owner, repo, { limit = 100 } = {}) =>
giteaRequest(`${path(owner, repo)}/labels${query({ limit })}`).then(asList),
listPulls: (owner, repo, { state = 'open', page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/pulls${query({ state, page, limit })}`).then(asList),
createPull: (owner, repo, { title, body, head, base }) =>
giteaRequest(`${path(owner, repo)}/pulls`, { method: 'POST', body: { title, body, head, base } }),
mergePull: (owner, repo, number, { style = 'squash', title, message, deleteBranch = false } = {}) =>
giteaRequest(`${path(owner, repo)}/pulls/${number}/merge`, {
method: 'POST',
body: {
Do: style,
MergeTitleField: title,
MergeMessageField: message,
delete_branch_after_merge: deleteBranch,
},
}),
listReleases: (owner, repo, { page = 1, limit = 20, draft, preRelease } = {}) =>
giteaRequest(
`${path(owner, repo)}/releases${query({ page, limit, draft, 'pre-release': preRelease })}`,
).then(asList),
getRelease: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/releases/${id}`),
latestRelease: (owner, repo) => giteaRequest(`${path(owner, repo)}/releases/latest`),
createRelease: (owner, repo, { tagName, target, name, body, draft = false, prerelease = false }) =>
giteaRequest(`${path(owner, repo)}/releases`, {
method: 'POST',
body: { tag_name: tagName, target_commitish: target, name, body, draft, prerelease },
}),
updateRelease: (owner, repo, id, payload) =>
giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'PATCH', body: payload }),
removeRelease: (owner, repo, id) =>
giteaRequest(`${path(owner, repo)}/releases/${id}`, { method: 'DELETE' }),
listCollaborators: (owner, repo) => giteaRequest(`${path(owner, repo)}/collaborators`).then(asList),
addCollaborator: (owner, repo, username, permission = 'write') =>
giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, {
method: 'PUT',
body: { permission },
}),
removeCollaborator: (owner, repo, username) =>
giteaRequest(`${path(owner, repo)}/collaborators/${encodeURIComponent(username)}`, { method: 'DELETE' }),
listHooks: (owner, repo) => giteaRequest(`${path(owner, repo)}/hooks`).then(asList),
createHook: (owner, repo, { url, secret, events, type = 'gitea' }) =>
giteaRequest(`${path(owner, repo)}/hooks`, {
method: 'POST',
body: { type, active: true, events, config: { url, content_type: 'json', secret } },
}),
removeHook: (owner, repo, id) => giteaRequest(`${path(owner, repo)}/hooks/${id}`, { method: 'DELETE' }),
/** Gitea Actions. Absent before Gitea 1.20, so callers must tolerate a 404. */
listActionTasks: (owner, repo, { page = 1, limit = 20 } = {}) =>
giteaRequest(`${path(owner, repo)}/actions/tasks${query({ page, limit })}`),
dispatchWorkflow: (owner, repo, workflow, { ref, inputs = {} }) =>
giteaRequest(`${path(owner, repo)}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, {
method: 'POST',
body: { ref, inputs },
}),
};
/** Splits `FWS/FWS-Arch` into its two parts, rejecting anything else. */
export function splitRepository(fullName) {
const [owner, repo, ...rest] = String(fullName ?? '').split('/');
if (!owner || !repo || rest.length > 0) return null;
return { owner, repo };
}
+69 -69
View File
@@ -1,69 +1,69 @@
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js'; import { ExternalApiError } from '../../core/errors.js';
import { withRetry } from '../../utils/retry.js'; import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500; const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Minimal Gitea REST API client (M5-T01). */ /** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) { if (!env.gitea.url || !env.gitea.token) {
throw new ExternalApiError('gitea', 'Gitea is not configured'); throw new ExternalApiError('gitea', 'Gitea is not configured');
} }
return withRetry( return withRetry(
async () => { async () => {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, { const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method, method,
headers: { headers: {
Authorization: `token ${env.gitea.token}`, Authorization: `token ${env.gitea.token}`,
Accept: 'application/json', Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }), ...(body && { 'Content-Type': 'application/json' }),
}, },
body: body ? JSON.stringify(body) : undefined, body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(env.gitea.timeoutMs), signal: AbortSignal.timeout(env.gitea.timeoutMs),
}); });
if (!response.ok) { if (!response.ok) {
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`); const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
error.status = response.status; error.status = response.status;
throw error; throw error;
} }
return response.status === 204 ? null : response.json(); return response.status === 204 ? null : response.json();
}, },
{ retries: env.gitea.maxRetries, shouldRetry: isTransient }, { retries: env.gitea.maxRetries, shouldRetry: isTransient },
); );
} }
/** True when both the Gitea URL and token are configured (M5-T01). */ /** True when both the Gitea URL and token are configured (M5-T01). */
export function isGiteaConfigured() { export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token); return Boolean(env.gitea.url && env.gitea.token);
} }
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */ /** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) { export function asList(payload) {
if (Array.isArray(payload)) return payload; if (Array.isArray(payload)) return payload;
return Array.isArray(payload?.data) ? payload.data : []; return Array.isArray(payload?.data) ? payload.data : [];
} }
/** Human readable URL of the configured repository, used in embeds. */ /** Human readable URL of the configured repository, used in embeds. */
export function repositoryUrl() { export function repositoryUrl() {
return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : ''; return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : '';
} }
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`; const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = { export const gitea = {
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`), listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`), getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
createIssue: ({ title, body }) => createIssue: ({ title, body }) =>
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }), giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`), listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`), getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
createPullRequest: ({ title, body, head, base }) => createPullRequest: ({ title, body, head, base }) =>
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }), giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`), listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`), listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
}; };
+97 -97
View File
@@ -1,97 +1,97 @@
import { COLORS } from '../../config/constants.js'; import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js'; import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500; const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */ /** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) { export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim(); const value = String(text ?? '').trim();
if (!value) return ''; if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value; return value.length > max ? `${value.slice(0, max - 1)}…` : value;
} }
/** Falls back to a neutral word: the value always sits next to a person, never a role. */ /** Falls back to a neutral word: the value always sits next to a person, never a role. */
const authorOf = (source) => const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu'; source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */ /** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) { export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`) .setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Aucune description fournie.') .setDescription(truncate(issue.body) || 'Aucune description fournie.')
.addFields( .addFields(
{ name: 'Ouverte par', value: authorOf(issue), inline: true }, { name: 'Ouverte par', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true }, { name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true }, { name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
); );
if (issue.html_url) embed.setURL(issue.html_url); if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean); const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') }); if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') });
return embed; return embed;
} }
/** Shared header of a pull request (M5-T04 / M9-T05). */ /** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) { export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte'; const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`) .setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Aucune description fournie.') .setDescription(truncate(pull.body) || 'Aucune description fournie.')
.addFields( .addFields(
{ name: 'Proposée par', value: authorOf(pull), inline: true }, { name: 'Proposée par', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true }, { name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true }, { name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
); );
if (pull.html_url) embed.setURL(pull.html_url); if (pull.html_url) embed.setURL(pull.html_url);
return embed; return embed;
} }
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */ /** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) { export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`) .setTitle(`${release.name || release.tag_name}`)
.addFields( .addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true }, { name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true }, { name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true }, { name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
); );
if (release.html_url) embed.setURL(release.html_url); if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) { if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000); const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true }); embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
} }
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900)); if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed; return embed;
} }
/** Push notification: the last commits of a branch (M9-T06). */ /** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) { export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? []; const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', ''); const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits const lines = commits
.slice(0, maxCommits) .slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`); .map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length; const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`) .setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.') .setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.')
.addFields( .addFields(
{ name: 'Poussé par', value: authorOf(payload), inline: true }, { name: 'Poussé par', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true }, { name: 'Commits', value: String(commits.length), inline: true },
); );
if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` }); if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed; return embed;
} }
/** Git references created or deleted (`create` / `delete` events). */ /** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) { export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu'; const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref'; const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea) const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`) .setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`); .setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url); if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed; return embed;
} }
+152 -152
View File
@@ -1,152 +1,152 @@
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js'; import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js'; import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js'; import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js'; import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js'; import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js'; import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js'; import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea'); const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000; const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */ /** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() { export function assertGiteaConfigured() {
if (!isGiteaConfigured()) { if (!isGiteaConfigured()) {
throw new UserFacingError( throw new UserFacingError(
'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.', 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.',
); );
} }
} }
function modal(id, title, fields) { function modal(id, title, fields) {
return new ModalBuilder() return new ModalBuilder()
.setCustomId(id) .setCustomId(id)
.setTitle(title) .setTitle(title)
.addComponents( .addComponents(
fields.map((field) => fields.map((field) =>
new ActionRowBuilder().addComponents( new ActionRowBuilder().addComponents(
new TextInputBuilder() new TextInputBuilder()
.setCustomId(field.id) .setCustomId(field.id)
.setLabel(field.label) .setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short) .setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength) .setMaxLength(field.maxLength)
.setRequired(field.required ?? true), .setRequired(field.required ?? true),
), ),
), ),
); );
} }
/** `/issue create` collects the title and description through a modal (M5-T03). */ /** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) { export async function openIssueModal(interaction) {
assertGiteaConfigured(); assertGiteaConfigured();
await interaction.showModal( await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [ modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 }, { id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 }, { id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]), ]),
); );
} }
/** `/pr create` keeps the branch options and asks for the title through a modal. */ /** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) { export async function openPullRequestModal(interaction) {
assertGiteaConfigured(); assertGiteaConfigured();
const head = interaction.options.getString('head', true); const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true); const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS }); remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal( await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [ modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 }, { id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false }, { id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]), ]),
); );
} }
/** Turns an API failure into a message the user can act on (M5-T08). */ /** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) { export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error); log.error('Gitea request failed', error);
const detail = const detail =
error instanceof ExternalApiError && /not configured/.test(error.message) error instanceof ExternalApiError && /not configured/.test(error.message)
? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.' ? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.'
: 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.'; : 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral }; const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) { if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {}); await interaction.followUp(payload).catch(() => {});
} else { } else {
await interaction.reply(payload).catch(() => {}); await interaction.reply(payload).catch(() => {});
} }
} }
export async function submitIssueModal(interaction) { export async function submitIssueModal(interaction) {
assertGiteaConfigured(); assertGiteaConfigured();
await interaction.deferReply(); await interaction.deferReply();
try { try {
const issue = await gitea.createIssue({ const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'), title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`, body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
}); });
logEvent({ logEvent({
guildId: interaction.guildId, guildId: interaction.guildId,
type: 'gitea.issue.created', type: 'gitea.issue.created',
actorId: interaction.user.id, actorId: interaction.user.id,
payload: { number: issue.number }, payload: { number: issue.number },
}); });
await interaction.editReply({ await interaction.editReply({
embeds: [issueEmbed(issue)], embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]), components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
}); });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
export async function submitPullRequestModal(interaction) { export async function submitPullRequestModal(interaction) {
assertGiteaConfigured(); assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`); const context = consume(`pr:${interaction.user.id}`);
if (!context) { if (!context) {
throw new UserFacingError( throw new UserFacingError(
'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.', 'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.',
); );
} }
await interaction.deferReply(); await interaction.deferReply();
try { try {
const pull = await gitea.createPullRequest({ const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'), title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(), body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head, head: context.head,
base: context.base, base: context.base,
}); });
logEvent({ logEvent({
guildId: interaction.guildId, guildId: interaction.guildId,
type: 'gitea.pull_request.created', type: 'gitea.pull_request.created',
actorId: interaction.user.id, actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base }, payload: { number: pull.number, head: context.head, base: context.base },
}); });
await interaction.editReply({ await interaction.editReply({
embeds: [pullRequestEmbed(pull)], embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]), components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
}); });
} catch (error) { } catch (error) {
await replyGiteaFailure(interaction, error); await replyGiteaFailure(interaction, error);
} }
} }
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */ /** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) { export async function handleGiteaModal(interaction) {
switch (interaction.customId) { switch (interaction.customId) {
case 'issue:create': case 'issue:create':
await submitIssueModal(interaction); await submitIssueModal(interaction);
return; return;
case 'pr:create': case 'pr:create':
await submitPullRequestModal(interaction); await submitPullRequestModal(interaction);
return; return;
default: default:
log.debug(`Ignored unknown modal ${interaction.customId}`); log.debug(`Ignored unknown modal ${interaction.customId}`);
} }
} }
+32 -32
View File
@@ -1,32 +1,32 @@
/** /**
* In-memory store for the short-lived context of a modal flow, e.g. the branches * In-memory store for the short-lived context of a modal flow, e.g. the branches
* of `/pr create` which are typed as options but sent with the modal (M5-T04). * of `/pr create` which are typed as options but sent with the modal (M5-T04).
* Entries expire on their own and disappear on restart. * Entries expire on their own and disappear on restart.
*/ */
const DEFAULT_TTL_MS = 5 * 60_000; const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map(); const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) { export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs }); entries.set(key, { value, expiresAt: now + ttlMs });
return value; return value;
} }
/** Returns the stored value and forgets it, or null when missing or expired. */ /** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) { export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key); const entry = entries.get(key);
if (!entry) return null; if (!entry) return null;
entries.delete(key); entries.delete(key);
return entry.expiresAt > now ? entry.value : null; return entry.expiresAt > now ? entry.value : null;
} }
export function purgeExpired(now = Date.now()) { export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) { for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key); if (entry.expiresAt <= now) entries.delete(key);
} }
return entries.size; return entries.size;
} }
export function pendingCount() { export function pendingCount() {
return entries.size; return entries.size;
} }
+128 -115
View File
@@ -1,115 +1,128 @@
import { COLORS } from '../../config/constants.js'; import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { readSetting } from '../../config/guild-settings.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { createLogger } from '../../core/logger.js';
import { baseEmbed } from '../../ui/embeds.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('members');
const log = createLogger('members');
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
async function sendTo(channel) {
return channel?.isSendable() ? channel : null; async function sendTo(channel) {
} return channel?.isSendable() ? channel : null;
}
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) { /** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
if (!env.channels.welcome) { export async function sendWelcome(client, member) {
log.debug('No welcome channel configured'); if (!readSetting('welcome.enabled', member.guild.id)) {
return; log.debug('Welcome message disabled for this guild');
} return;
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null)); if (!env.channels.welcome) {
if (!channel) { log.debug('No welcome channel configured');
log.warn('Welcome channel unavailable', { channelId: env.channels.welcome }); return;
return; }
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null));
const embed = baseEmbed(COLORS.primary) if (!channel) {
.setTitle('🎉 Nouveau membre') log.warn('Welcome channel unavailable', { channelId: env.channels.welcome });
.setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`) return;
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true }) }
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
const greeting =
if (env.channels.rules) { readSetting('welcome.message', member.guild.id).replaceAll('{server}', member.guild.name) ||
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` }); DEFAULT_WELCOME;
}
const embed = baseEmbed(COLORS.primary)
await channel.send({ content: `${member}`, embeds: [embed] }); .setTitle('🎉 Nouveau membre')
logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } }); .setDescription(`${member} vient d’arriver. ${greeting}`)
} .addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
/** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) { if (env.channels.rules && readSetting('welcome.showRules', member.guild.id)) {
const roleId = env.roles.member; embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
if (!roleId || member.roles.cache.has(roleId)) return; }
const role = await member.guild.roles.fetch(roleId).catch(() => null); await channel.send({ content: `${member}`, embeds: [embed] });
if (!role) { logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } });
log.warn('Default member role not found', { roleId }); }
return;
} /** Gives the default member role (M7-T03). */
if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) { export async function assignMemberRole(member) {
log.warn('Member role is above the bot role, skipping', { roleId }); if (!readSetting('members.autoRole', member.guild.id)) return;
return;
} const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return;
await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error); const role = await member.guild.roles.fetch(roleId).catch(() => null);
}); if (!role) {
} log.warn('Default member role not found', { roleId });
return;
/** Welcomes the member in a direct message with the server resources (M7-T02). */ }
export async function sendWelcomeDirectMessage(member) { if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) {
const links = [ log.warn('Member role is above the bot role, skipping', { roleId });
env.links.website && `[Site officiel](${env.links.website})`, return;
env.links.docs && `[Documentation](${env.links.docs})`, }
env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
].filter(Boolean); await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error);
const embed = baseEmbed(COLORS.primary) });
.setTitle(`Bienvenue sur ${member.guild.name} !`) }
.setDescription(
'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' + /** Welcomes the member in a direct message with the server resources (M7-T02). */
'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.', export async function sendWelcomeDirectMessage(member) {
); const links = [
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') }); env.links.website && `[Site officiel](${env.links.website})`,
env.links.docs && `[Documentation](${env.links.docs})`,
await member.send({ embeds: [embed] }).catch(() => { env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
log.debug('Welcome DM could not be delivered', { userId: member.id }); ].filter(Boolean);
});
} const embed = baseEmbed(COLORS.primary)
.setTitle(`Bienvenue sur ${member.guild.name} !`)
/** Logs a departure in the log channel (M7-T04). */ .setDescription(
export async function announceDeparture(client, member) { 'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' +
const channelId = env.channels.logs || env.channels.modLogs; 'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.',
if (!channelId) return; );
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
if (!channel) return; await member.send({ embeds: [embed] }).catch(() => {
log.debug('Welcome DM could not be delivered', { userId: member.id });
const joinedAt = member.joinedTimestamp; });
const embed = baseEmbed(COLORS.warning) }
.setTitle('👋 Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`) /** Logs a departure in the log channel (M7-T04). */
.addFields( export async function announceDeparture(client, member) {
{ name: 'Membres', value: String(member.guild.memberCount), inline: true }, if (!readSetting('departure.announce', member.guild.id)) return;
{
name: 'Compte créé', const channelId = env.channels.logs || env.channels.modLogs;
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`, if (!channelId) return;
inline: true,
}, const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
) if (!channel) return;
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
const joinedAt = member.joinedTimestamp;
if (joinedAt) { const embed = baseEmbed(COLORS.warning)
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true }); .setTitle('👋 Départ d’un membre')
} .setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
await channel.send({ embeds: [embed] }); { name: 'Membres', value: String(member.guild.memberCount), inline: true },
logEvent({ {
guildId: member.guild.id, name: 'Compte créé',
type: 'member.left', value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
payload: { userId: member.id, joinedAt: joinedAt ?? null }, inline: true,
}); },
} )
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (joinedAt) {
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true });
}
await channel.send({ embeds: [embed] });
logEvent({
guildId: member.guild.id,
type: 'member.left',
payload: { userId: member.id, joinedAt: joinedAt ?? null },
});
}
+146 -132
View File
@@ -1,132 +1,146 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js'; import { readSetting } from '../../config/guild-settings.js';
import { canActOn } from '../../core/permissions.js'; import { UserFacingError } from '../../core/errors.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { canActOn } from '../../core/permissions.js';
import { recordAction } from '../../database/repositories/moderation-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { baseEmbed } from '../../ui/embeds.js'; import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08). /**
* @param {import('discord.js').ChatInputCommandInteraction} interaction * Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').GuildMember} target * @param {import('discord.js').ChatInputCommandInteraction} interaction
*/ * @param {import('discord.js').GuildMember} target
export function assertModerationTarget(interaction, target) { */
if (!target) { export function assertModerationTarget(interaction, target) {
throw new UserFacingError( if (!target) {
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', throw new UserFacingError(
); 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
} );
if (target.id === interaction.user.id) { }
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.'); if (target.id === interaction.user.id) {
} throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.');
if (!canActOn(interaction.member, target)) { }
throw new UserFacingError( if (!canActOn(interaction.member, target)) {
'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.', throw new UserFacingError(
); 'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.',
} );
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) { const bot = interaction.guild.members.me;
throw new UserFacingError( if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
`Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`, throw new UserFacingError(
); `Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`,
} );
} }
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06). /**
* Call it only once the Discord action has succeeded. * Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
*/ * Call it only once the Discord action has succeeded.
export async function logModerationAction( */
interaction, export async function logModerationAction(
{ action, targetId, reason = null, durationMs = null }, interaction,
) { { action, targetId, reason = null, durationMs = null },
recordAction({ ) {
guildId: interaction.guildId, recordAction({
action, guildId: interaction.guildId,
moderatorId: interaction.user.id, action,
targetId, moderatorId: interaction.user.id,
reason, targetId,
durationMs, reason,
}); durationMs,
logEvent({ });
guildId: interaction.guildId, logEvent({
type: `moderation.${action}`, guildId: interaction.guildId,
actorId: interaction.user.id, type: `moderation.${action}`,
payload: { targetId, reason, durationMs }, actorId: interaction.user.id,
}); payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, { const meta = MODERATION_ACTIONS[action];
action, await sendModerationLog(interaction.client, interaction.guild, {
color: meta?.color ?? COLORS.moderation, action,
targetId, color: meta?.color ?? COLORS.moderation,
moderatorId: interaction.user.id, targetId,
reason, moderatorId: interaction.user.id,
durationMs, reason,
}); durationMs,
} });
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog( /** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
client, export async function sendModerationLog(
guild, client,
{ action, targetId, moderatorId, reason, durationMs }, guild,
) { { action, targetId, moderatorId, reason, durationMs },
if (!env.channels.modLogs) return; ) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return; const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color) const meta = MODERATION_ACTIONS[action];
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`) const embed = baseEmbed(meta?.color)
.addFields( .setTitle(`🛡️ Modération — ${meta?.label ?? action}`)
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true }, .addFields(
{ name: 'Par', value: `<@${moderatorId}>`, inline: true }, { name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Motif', value: reason || 'Non précisé' }, { name: 'Par', value: `<@${moderatorId}>`, inline: true },
); { name: 'Motif', value: reason || 'Non précisé' },
if (durationMs) { );
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true }); if (durationMs) {
} embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` }); }
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
} await channel.send({ embeds: [embed] }).catch(() => {});
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) { /**
const meta = MODERATION_ACTIONS[action]; * Sends the private notice to the sanctioned member, when the server wants one
const embed = baseEmbed(meta?.color) * (M8-T07). Never throws: plenty of accounts refuse direct messages, and that
.setTitle(`Sanction sur ${guildName}`) * must not turn a successful sanction into an error.
.setDescription( */
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`, export async function notifyTarget(member, payload) {
) if (!readSetting('moderation.dmTarget', member.guild.id)) return false;
.addFields({ name: 'Motif', value: reason || 'Non précisé' }); return member
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) }); .send(payload)
return embed; .then(() => true)
} .catch(() => false);
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) { /** Direct message sent to the member who is being moderated (M8-T07). */
const minutes = Math.round(durationMs / 60_000); export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
if (minutes < 60) return `${minutes} min`; const meta = MODERATION_ACTIONS[action];
const hours = Math.floor(minutes / 60); const embed = baseEmbed(meta?.color)
const rest = minutes % 60; .setTitle(`Sanction sur ${guildName}`)
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; .setDescription(
const days = Math.floor(hours / 24); `Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
const remainingHours = hours % 24; )
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`; .addFields({ name: 'Motif', value: reason || 'Non précisé' });
} if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
/** Fetches the member targeted by a command, with a clear error if absent. */ }
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null); /** Human readable duration for embeds: `2 h 30 min`. */
if (!member) { export function formatDuration(durationMs) {
throw new UserFacingError( const minutes = Math.round(durationMs / 60_000);
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', if (minutes < 60) return `${minutes} min`;
); const hours = Math.floor(minutes / 60);
} const rest = minutes % 60;
return member; if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
} const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
return member;
}
@@ -1,31 +1,31 @@
import { GITEA_EVENT_TYPES } from '../../config/constants.js'; import { GITEA_EVENT_TYPES } from '../../config/constants.js';
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js'; import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
/** /**
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event * Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
* should not be published (M9-T03). * should not be published (M9-T03).
*/ */
export function buildGiteaNotification(event, payload) { export function buildGiteaNotification(event, payload) {
const type = GITEA_EVENT_TYPES[event]; const type = GITEA_EVENT_TYPES[event];
if (!type) return null; if (!type) return null;
switch (event) { switch (event) {
case 'issues': case 'issues':
return { type, embed: issueEmbed(payload.issue ?? payload) }; return { type, embed: issueEmbed(payload.issue ?? payload) };
case 'pull_request': case 'pull_request':
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) }; return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
case 'push': case 'push':
if (!payload.commits?.length) return null; if (!payload.commits?.length) return null;
return { type, embed: pushEmbed(payload) }; return { type, embed: pushEmbed(payload) };
case 'create': case 'create':
case 'delete': case 'delete':
return { return {
type, type,
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'), embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
}; };
case 'release': case 'release':
return { type, embed: releaseEmbed(payload.release ?? payload) }; return { type, embed: releaseEmbed(payload.release ?? payload) };
default: default:
return null; return null;
} }
} }
@@ -1,61 +1,86 @@
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { readSetting } from '../../config/guild-settings.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js'; import { createLogger } from '../../core/logger.js';
import { errorEmbed } from '../../ui/embeds.js'; import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js';
const log = createLogger('notifications');
const log = createLogger('notifications');
/** Fallback routing from the environment when the guild has no override (M9-T01). */
const defaultChannels = { /** Fallback routing from the environment when the guild has no override (M9-T01). */
issues: env.channels.notifIssues, const defaultChannels = {
pull_request: env.channels.notifPullRequests, issues: env.channels.notifIssues,
push: env.channels.notifCommits, pull_request: env.channels.notifPullRequests,
release: env.channels.notifReleases, push: env.channels.notifCommits,
errors: env.channels.notifErrors, release: env.channels.notifReleases,
announcements: env.channels.announcements, errors: env.channels.notifErrors,
community: env.channels.logs, announcements: env.channels.announcements,
}; community: env.channels.logs,
};
/** SQLite override first, then the environment default (M9-T01). */
export function resolveChannelId(type, guildId = env.discord.guildId) { /**
try { * `/notify` and the dashboard name the types after `NOTIFICATION_TYPES`, while the
if (guildId) { * webhook handler names them after the Gitea event. Both spellings must resolve to
const override = getNotificationChannel(guildId, type); * the same channel, otherwise an override set from Discord is never applied (M9-T01).
if (override?.channel_id) return override.channel_id; */
} const TYPE_ALIASES = Object.freeze({
} catch { pull_request: 'pull_requests',
// The database is unavailable (tests, early startup): use the environment. pull_requests: 'pull_request',
} push: 'commits',
return defaultChannels[type] ?? null; commits: 'push',
} release: 'releases',
releases: 'release',
/** Sends a notification payload to the channel configured for its type (M9). */ });
export async function notify(client, type, payload) {
const channelId = resolveChannelId(type); /** SQLite override first, then the environment default (M9-T01). */
if (!channelId) { export function resolveChannelId(type, guildId = env.discord.guildId) {
log.debug(`No channel configured for notification type ${type}`); try {
return null; if (guildId) {
} for (const candidate of [type, TYPE_ALIASES[type]].filter(Boolean)) {
const override = getNotificationChannel(guildId, candidate);
const channel = await client.channels.fetch(channelId).catch(() => null); if (override?.channel_id) return override.channel_id;
if (!channel?.isSendable()) { }
log.warn(`Notification channel unavailable for ${type}`, { channelId }); }
return null; } catch {
} // The database is unavailable (tests, early startup): use the environment.
return channel.send(payload); }
} return defaultChannels[type] ?? defaultChannels[TYPE_ALIASES[type]] ?? null;
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') { /** Sends a notification payload to the channel configured for its type (M9). */
log.error(`Notification error (${context})`, error); export async function notify(client, type, payload) {
return notify(client, 'errors', { const channelId = resolveChannelId(type);
embeds: [ if (!channelId) {
errorEmbed( log.debug(`No channel configured for notification type ${type}`);
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`, return null;
).addFields({ }
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``, const channel = await client.channels.fetch(channelId).catch(() => null);
}), if (!channel?.isSendable()) {
], log.warn(`Notification channel unavailable for ${type}`, { channelId });
}); return null;
} }
// An optional ping, prepended rather than replacing whatever content the
// caller already prepared.
const mention = readSetting('notifications.mentionRoleId');
const message = mention
? { ...payload, content: payload.content ? `<@&${mention}> ${payload.content}` : `<@&${mention}>` }
: payload;
return channel.send(message);
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') {
log.error(`Notification error (${context})`, error);
return notify(client, 'errors', {
embeds: [
errorEmbed(
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`,
).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
],
});
}
+219 -219
View File
@@ -1,219 +1,219 @@
import { MessageFlags } from 'discord.js'; import { MessageFlags } from 'discord.js';
import { COLORS } from '../../config/constants.js'; import { COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { import {
attachPollMessage, attachPollMessage,
castVote, castVote,
closePoll, closePoll,
countVotes, countVotes,
createPoll as createPollRow, createPoll as createPollRow,
getPoll, getPoll,
listDuePolls, listDuePolls,
} from '../../database/repositories/poll-repository.js'; } from '../../database/repositories/poll-repository.js';
import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js'; import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js';
import { baseEmbed } from '../../ui/embeds.js'; import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('polls'); const log = createLogger('polls');
const CHOICES_MIN = 2; const CHOICES_MIN = 2;
const BAR_LENGTH = 12; const BAR_LENGTH = 12;
const SCHEDULER_INTERVAL_MS = 30_000; const SCHEDULER_INTERVAL_MS = 30_000;
/** Splits the `choices` option on `;` and validates the count (M10-T01). */ /** Splits the `choices` option on `;` and validates the count (M10-T01). */
export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) { export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) {
const choices = String(input) const choices = String(input)
.split(';') .split(';')
.map((choice) => choice.trim()) .map((choice) => choice.trim())
.filter(Boolean); .filter(Boolean);
if (choices.length < min || choices.length > max) { if (choices.length < min || choices.length > max) {
throw new UserFacingError( throw new UserFacingError(
`Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`, `Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`,
); );
} }
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) { if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError( throw new UserFacingError(
'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.', 'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.',
); );
} }
return choices; return choices;
} }
/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */ /** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */
export function toSqliteDate(date) { export function toSqliteDate(date) {
return date.toISOString().slice(0, 19).replace('T', ' '); return date.toISOString().slice(0, 19).replace('T', ' ');
} }
function renderBar(ratio) { function renderBar(ratio) {
const filled = Math.round(ratio * BAR_LENGTH); const filled = Math.round(ratio * BAR_LENGTH);
return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`; return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`;
} }
/** Results embed, shared by creation, voting and closing (M10-T06). */ /** Results embed, shared by creation, voting and closing (M10-T06). */
export function buildPollEmbed(poll, counts = countVotes(poll.id)) { export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
const choices = JSON.parse(poll.choices); const choices = JSON.parse(poll.choices);
const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0; const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0;
const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0); const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0);
const lines = choices.map((choice, index) => { const lines = choices.map((choice, index) => {
const count = countFor(index); const count = countFor(index);
const percent = total === 0 ? 0 : Math.round((count / total) * 100); const percent = total === 0 ? 0 : Math.round((count / total) * 100);
return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`; return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`;
}); });
const embed = baseEmbed(COLORS.info) const embed = baseEmbed(COLORS.info)
.setTitle(`📊 Sondage #${poll.id} — ${poll.question}`) .setTitle(`📊 Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n')) .setDescription(lines.join('\n\n'))
.addFields( .addFields(
{ name: 'Votes', value: String(total), inline: true }, { name: 'Votes', value: String(total), inline: true },
{ name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true }, { name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true },
{ name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, { name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
); );
if (poll.ends_at) { if (poll.ends_at) {
const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000); const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000);
embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true }); embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true });
} }
if (poll.status === 'closed') { if (poll.status === 'closed') {
embed.setColor(COLORS.success); embed.setColor(COLORS.success);
const best = choices.reduce( const best = choices.reduce(
(winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner), (winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner),
0, 0,
); );
const top = countFor(best); const top = countFor(best);
embed.addFields({ embed.addFields({
name: 'Résultat', name: 'Résultat',
value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`, value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`,
}); });
} }
return embed; return embed;
} }
export function buildPollComponents(poll) { export function buildPollComponents(poll) {
return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : []; return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : [];
} }
/** Creates the poll message and records it (M10-T01 / M10-T02). */ /** Creates the poll message and records it (M10-T01 / M10-T02). */
export async function createPoll(interaction, { question, choicesInput, minutes = null }) { export async function createPoll(interaction, { question, choicesInput, minutes = null }) {
const choices = parseChoices(choicesInput); const choices = parseChoices(choicesInput);
const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null; const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null;
const pollId = createPollRow({ const pollId = createPollRow({
guildId: interaction.guildId, guildId: interaction.guildId,
channelId: interaction.channelId, channelId: interaction.channelId,
creatorId: interaction.user.id, creatorId: interaction.user.id,
question, question,
choices, choices,
endsAt, endsAt,
}); });
const poll = getPoll(pollId); const poll = getPoll(pollId);
const message = await interaction.channel.send({ const message = await interaction.channel.send({
embeds: [buildPollEmbed(poll, [])], embeds: [buildPollEmbed(poll, [])],
components: buildPollComponents(poll), components: buildPollComponents(poll),
}); });
attachPollMessage(pollId, message.id); attachPollMessage(pollId, message.id);
logEvent({ logEvent({
guildId: interaction.guildId, guildId: interaction.guildId,
type: 'poll.created', type: 'poll.created',
actorId: interaction.user.id, actorId: interaction.user.id,
payload: { pollId, choices: choices.length }, payload: { pollId, choices: choices.length },
}); });
return pollId; return pollId;
} }
async function fetchPollMessage(interaction, poll) { async function fetchPollMessage(interaction, poll) {
if (!poll.message_id) return null; if (!poll.message_id) return null;
return interaction.channel.messages.fetch(poll.message_id).catch(() => null); return interaction.channel.messages.fetch(poll.message_id).catch(() => null);
} }
/** Closes a poll and freezes its results (M10-T05). */ /** Closes a poll and freezes its results (M10-T05). */
export async function closePollById(client, pollId) { export async function closePollById(client, pollId) {
const poll = getPoll(pollId); const poll = getPoll(pollId);
if (!poll) { if (!poll) {
throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`); throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`);
} }
if (poll.status === 'closed') { if (poll.status === 'closed') {
throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`); throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`);
} }
closePoll(pollId); closePoll(pollId);
const closed = { ...poll, status: 'closed' }; const closed = { ...poll, status: 'closed' };
const channel = await client.channels.fetch(poll.channel_id).catch(() => null); const channel = await client.channels.fetch(poll.channel_id).catch(() => null);
const message = channel?.isSendable() const message = channel?.isSendable()
? await channel.messages.fetch(poll.message_id).catch(() => null) ? await channel.messages.fetch(poll.message_id).catch(() => null)
: null; : null;
await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] }); await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] });
logEvent({ logEvent({
guildId: poll.guild_id, guildId: poll.guild_id,
type: 'poll.closed', type: 'poll.closed',
payload: { pollId }, payload: { pollId },
}); });
return closed; return closed;
} }
/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */ /** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */
export async function handlePollComponent(interaction) { export async function handlePollComponent(interaction) {
const [, rawId, rawIndex] = interaction.customId.split(':'); const [, rawId, rawIndex] = interaction.customId.split(':');
const poll = getPoll(Number(rawId)); const poll = getPoll(Number(rawId));
if (!poll || poll.status !== 'open') { if (!poll || poll.status !== 'open') {
throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.'); throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.');
} }
const choices = JSON.parse(poll.choices); const choices = JSON.parse(poll.choices);
const index = Number(rawIndex); const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) { if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Cette proposition n’existe plus dans le sondage.'); throw new UserFacingError('Cette proposition n’existe plus dans le sondage.');
} }
const result = castVote(poll.id, interaction.user.id, index); const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') { if (result === 'unchanged') {
await interaction.reply({ await interaction.reply({
content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`, content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`,
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
const message = await fetchPollMessage(interaction, poll); const message = await fetchPollMessage(interaction, poll);
await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) }); await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) });
await interaction.reply({ await interaction.reply({
content: content:
result === 'changed' result === 'changed'
? `C’est noté : ton vote va maintenant à **${choices[index]}**.` ? `C’est noté : ton vote va maintenant à **${choices[index]}**.`
: `Merci ! Ton vote est sur **${choices[index]}**.`, : `Merci ! Ton vote est sur **${choices[index]}**.`,
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
}); });
} }
/** Polls expire on their own even without activity (M10-T05). */ /** Polls expire on their own even without activity (M10-T05). */
export function startPollScheduler(client) { export function startPollScheduler(client) {
const timer = setInterval(async () => { const timer = setInterval(async () => {
let due = []; let due = [];
try { try {
due = listDuePolls(); due = listDuePolls();
} catch (error) { } catch (error) {
log.warn('Could not read the polls to close', error); log.warn('Could not read the polls to close', error);
return; return;
} }
for (const poll of due) { for (const poll of due) {
try { try {
await closePollById(client, poll.id); await closePollById(client, poll.id);
log.info(`Closed poll #${poll.id} at its end date`); log.info(`Closed poll #${poll.id} at its end date`);
} catch (error) { } catch (error) {
log.error(`Could not close poll #${poll.id}`, error); log.error(`Could not close poll #${poll.id}`, error);
} }
} }
}, SCHEDULER_INTERVAL_MS); }, SCHEDULER_INTERVAL_MS);
timer.unref(); timer.unref();
return timer; return timer;
} }
+314 -314
View File
@@ -1,314 +1,314 @@
import { ActivityType } from 'discord.js'; import { ActivityType } from 'discord.js';
import { COLORS } from '../../config/constants.js'; import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js'; import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { logEvent } from '../../database/repositories/event-log-repository.js';
import { import {
addBotStatus as addBotStatusRow, addBotStatus as addBotStatusRow,
clearBotStatuses, clearBotStatuses,
countBotStatuses, countBotStatuses,
getBotStatus, getBotStatus,
listBotStatuses, listBotStatuses,
listEnabledBotStatuses, listEnabledBotStatuses,
removeBotStatus as removeBotStatusRow, removeBotStatus as removeBotStatusRow,
setBotStatusEnabled, setBotStatusEnabled,
} from '../../database/repositories/bot-status-repository.js'; } from '../../database/repositories/bot-status-repository.js';
import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js'; import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js'; import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
const log = createLogger('status'); const log = createLogger('status');
/** Discord caps an activity name at 128 characters. */ /** Discord caps an activity name at 128 characters. */
export const STATUS_TEXT_MAX = 128; export const STATUS_TEXT_MAX = 128;
/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */ /** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */
export const STATUS_MAX = 25; export const STATUS_MAX = 25;
export const ROTATION_MIN_SECONDS = 5; export const ROTATION_MIN_SECONDS = 5;
export const ROTATION_MAX_SECONDS = 86_400; export const ROTATION_MAX_SECONDS = 86_400;
/** Key of the rotation delay, stored per guild like the other settings (M15). */ /** Key of the rotation delay, stored per guild like the other settings (M15). */
export const ROTATION_KEY = 'bot.status.interval'; export const ROTATION_KEY = 'bot.status.interval';
/** Shown while the list is empty, so the bot never displays nothing useful. */ /** Shown while the list is empty, so the bot never displays nothing useful. */
export const FALLBACK_STATUS = Object.freeze({ export const FALLBACK_STATUS = Object.freeze({
id: null, id: null,
text: 'les commandes avec /help', text: 'les commandes avec /help',
type: 'watching', type: 'watching',
}); });
/** /**
* Accepted activity types. Discord writes the verb itself, so only the label used in the * Accepted activity types. Discord writes the verb itself, so only the label used in the
* embeds lives here; `streaming` is the one type that requires a link. * embeds lives here; `streaming` is the one type that requires a link.
*/ */
export const STATUS_TYPES = Object.freeze({ export const STATUS_TYPES = Object.freeze({
playing: { label: 'joue à', activity: ActivityType.Playing }, playing: { label: 'joue à', activity: ActivityType.Playing },
streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true }, streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true },
listening: { label: 'écoute', activity: ActivityType.Listening }, listening: { label: 'écoute', activity: ActivityType.Listening },
watching: { label: 'regarde', activity: ActivityType.Watching }, watching: { label: 'regarde', activity: ActivityType.Watching },
competing: { label: 'participe à', activity: ActivityType.Competing }, competing: { label: 'participe à', activity: ActivityType.Competing },
}); });
/** Choice list for the slash command. */ /** Choice list for the slash command. */
export const STATUS_TYPE_CHOICES = Object.freeze( export const STATUS_TYPE_CHOICES = Object.freeze(
Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })), Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })),
); );
/** Strips control characters without a control-character regex, then collapses the spaces. */ /** Strips control characters without a control-character regex, then collapses the spaces. */
const clean = (value) => const clean = (value) =>
[...String(value ?? '')] [...String(value ?? '')]
.map((char) => { .map((char) => {
const code = char.codePointAt(0); const code = char.codePointAt(0);
return code <= 31 || code === 127 ? ' ' : char; return code <= 31 || code === 127 ? ' ' : char;
}) })
.join('') .join('')
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.trim(); .trim();
export function sanitizeStatusText(value) { export function sanitizeStatusText(value) {
const text = clean(value); const text = clean(value);
if (!text) { if (!text) {
throw new UserFacingError( throw new UserFacingError(
'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».', 'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».',
); );
} }
if (text.length > STATUS_TEXT_MAX) { if (text.length > STATUS_TEXT_MAX) {
throw new UserFacingError( throw new UserFacingError(
`Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`, `Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`,
); );
} }
return text; return text;
} }
export function normalizeStatusType(value) { export function normalizeStatusType(value) {
const key = String(value ?? 'watching') const key = String(value ?? 'watching')
.toLowerCase() .toLowerCase()
.trim(); .trim();
if (!STATUS_TYPES[key]) { if (!STATUS_TYPES[key]) {
throw new UserFacingError( throw new UserFacingError(
`Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`, `Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`,
); );
} }
return key; return key;
} }
/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */ /** Only a streaming status uses a link, and Discord refuses it without a valid URL. */
export function validateStatusUrl(value, typeKey) { export function validateStatusUrl(value, typeKey) {
const url = String(value ?? '').trim(); const url = String(value ?? '').trim();
if (STATUS_TYPES[typeKey]?.needsUrl && !url) { if (STATUS_TYPES[typeKey]?.needsUrl && !url) {
throw new UserFacingError( throw new UserFacingError(
'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.', 'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.',
); );
} }
if (!url) return null; if (!url) return null;
if (!/^https?:\/\/\S+$/i.test(url)) { if (!/^https?:\/\/\S+$/i.test(url)) {
throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.'); throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.');
} }
return url; return url;
} }
/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */ /** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */
export function formatSeconds(seconds) { export function formatSeconds(seconds) {
const value = Math.max(0, Math.round(Number(seconds) || 0)); const value = Math.max(0, Math.round(Number(seconds) || 0));
if (value < 60) return `${value} s`; if (value < 60) return `${value} s`;
const minutes = Math.round(value / 60); const minutes = Math.round(value / 60);
if (minutes < 60) return `${minutes} min`; if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60); const hours = Math.floor(minutes / 60);
const rest = minutes % 60; const rest = minutes % 60;
return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`; return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
} }
/** Delay used when neither the database nor the environment gives a usable value. */ /** Delay used when neither the database nor the environment gives a usable value. */
const FALLBACK_ROTATION_SECONDS = 60; const FALLBACK_ROTATION_SECONDS = 60;
/** The environment default, ignored when it is out of range rather than applied blindly. */ /** The environment default, ignored when it is out of range rather than applied blindly. */
const envRotationSeconds = () => { const envRotationSeconds = () => {
const value = Number(env.bot.statusIntervalSeconds); const value = Number(env.bot.statusIntervalSeconds);
return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS
? value ? value
: FALLBACK_ROTATION_SECONDS; : FALLBACK_ROTATION_SECONDS;
}; };
export function clampRotation(value, { strict = false } = {}) { export function clampRotation(value, { strict = false } = {}) {
const seconds = Number(value); const seconds = Number(value);
if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) { if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) {
if (strict) { if (strict) {
throw new UserFacingError( throw new UserFacingError(
`Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`, `Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`,
); );
} }
return envRotationSeconds(); return envRotationSeconds();
} }
return seconds; return seconds;
} }
/** Rotation delay, overridable from Discord; the environment provides the default (M15). */ /** Rotation delay, overridable from Discord; the environment provides the default (M15). */
export function getRotationSeconds(guildId = env.discord.guildId) { export function getRotationSeconds(guildId = env.discord.guildId) {
return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds)); return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds));
} }
export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) { export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) {
const value = clampRotation(seconds, { strict: true }); const value = clampRotation(seconds, { strict: true });
setSetting(guildId, ROTATION_KEY, value, updatedBy); setSetting(guildId, ROTATION_KEY, value, updatedBy);
return value; return value;
} }
/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */ /** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) { export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) {
const statusText = sanitizeStatusText(text); const statusText = sanitizeStatusText(text);
const typeKey = normalizeStatusType(type); const typeKey = normalizeStatusType(type);
const statusUrl = validateStatusUrl(url, typeKey); const statusUrl = validateStatusUrl(url, typeKey);
if (countBotStatuses() >= STATUS_MAX) { if (countBotStatuses() >= STATUS_MAX) {
throw new UserFacingError( throw new UserFacingError(
`La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`, `La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`,
); );
} }
let status; let status;
try { try {
status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy }); status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy });
} catch (error) { } catch (error) {
if (!/UNIQUE constraint/i.test(String(error?.message))) throw error; if (!/UNIQUE constraint/i.test(String(error?.message))) throw error;
log.debug('Duplicate status refused', error); log.debug('Duplicate status refused', error);
throw new UserFacingError( throw new UserFacingError(
`« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`, `« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`,
); );
} }
logEvent({ logEvent({
guildId: env.discord.guildId, guildId: env.discord.guildId,
type: 'bot.status.added', type: 'bot.status.added',
actorId: createdBy, actorId: createdBy,
payload: { id: status.id }, payload: { id: status.id },
}); });
return status; return status;
} }
export function removeBotStatus(id) { export function removeBotStatus(id) {
const status = getBotStatus(id); const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
removeBotStatusRow(id); removeBotStatusRow(id);
logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } }); logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } });
return status; return status;
} }
export function toggleBotStatus(id, enabled) { export function toggleBotStatus(id, enabled) {
const status = getBotStatus(id); const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`); if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
if (Boolean(status.enabled) === enabled) { if (Boolean(status.enabled) === enabled) {
throw new UserFacingError( throw new UserFacingError(
enabled enabled
? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.` ? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.`
: `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`, : `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`,
); );
} }
setBotStatusEnabled(id, enabled); setBotStatusEnabled(id, enabled);
return { ...status, enabled: enabled ? 1 : 0 }; return { ...status, enabled: enabled ? 1 : 0 };
} }
/** Empties the list; the fallback status takes over immediately. */ /** Empties the list; the fallback status takes over immediately. */
export function clearBotStatusList() { export function clearBotStatusList() {
const removed = clearBotStatuses(); const removed = clearBotStatuses();
logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } }); logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } });
return removed; return removed;
} }
/** /**
* Next status of the rotation: the enabled ones in insertion order, one after the other. * Next status of the rotation: the enabled ones in insertion order, one after the other.
* Returns `null` when nothing is enabled, so the caller falls back to a default line. * Returns `null` when nothing is enabled, so the caller falls back to a default line.
*/ */
export function selectNextStatus(statuses, lastId = null) { export function selectNextStatus(statuses, lastId = null) {
if (statuses.length === 0) return null; if (statuses.length === 0) return null;
const index = statuses.findIndex((status) => status.id === lastId); const index = statuses.findIndex((status) => status.id === lastId);
return statuses[(index + 1) % statuses.length]; return statuses[(index + 1) % statuses.length];
} }
/** Shows one status in Discord. */ /** Shows one status in Discord. */
export function applyBotStatus(client, status = FALLBACK_STATUS) { export function applyBotStatus(client, status = FALLBACK_STATUS) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const activity = { name: status.text, type: type.activity }; const activity = { name: status.text, type: type.activity };
if (type.needsUrl && status.url) activity.url = status.url; if (type.needsUrl && status.url) activity.url = status.url;
client.user.setPresence({ status: 'online', activities: [activity] }); client.user.setPresence({ status: 'online', activities: [activity] });
return activity; return activity;
} }
/** Applies the only enabled status right away, so an addition shows up immediately. */ /** Applies the only enabled status right away, so an addition shows up immediately. */
export function applyStatusIfAlone(client) { export function applyStatusIfAlone(client) {
const statuses = listEnabledBotStatuses(); const statuses = listEnabledBotStatuses();
if (statuses.length !== 1) return null; if (statuses.length !== 1) return null;
applyBotStatus(client, statuses[0]); applyBotStatus(client, statuses[0]);
return statuses[0]; return statuses[0];
} }
/** Shows the next status and returns it; used by the rotation and by the tests. */ /** Shows the next status and returns it; used by the rotation and by the tests. */
export function rotateBotStatus(client, lastId = null) { export function rotateBotStatus(client, lastId = null) {
const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS; const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS;
applyBotStatus(client, status); applyBotStatus(client, status);
return status; return status;
} }
/** /**
* Rotates the statuses forever. The delay is read again on every turn, so `/status interval` * Rotates the statuses forever. The delay is read again on every turn, so `/status interval`
* takes effect without restarting the bot (M15). * takes effect without restarting the bot (M15).
*/ */
export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) { export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) {
let lastId = null; let lastId = null;
let timer = null; let timer = null;
const tick = () => { const tick = () => {
try { try {
lastId = rotateBotStatus(client, lastId)?.id ?? null; lastId = rotateBotStatus(client, lastId)?.id ?? null;
} catch (error) { } catch (error) {
log.warn('Could not rotate the bot status', error); log.warn('Could not rotate the bot status', error);
} }
timer = setTimeout(tick, getRotationSeconds(guildId) * 1000); timer = setTimeout(tick, getRotationSeconds(guildId) * 1000);
timer.unref?.(); timer.unref?.();
}; };
tick(); tick();
return { stop: () => clearTimeout(timer) }; return { stop: () => clearTimeout(timer) };
} }
function describeStatus(status) { function describeStatus(status) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching; const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const link = type.needsUrl && status.url ? ` · ${status.url}` : ''; const link = type.needsUrl && status.url ? ` · ${status.url}` : '';
return `« ${status.text} » — ${type.label}${link}`; return `« ${status.text} » — ${type.label}${link}`;
} }
/** The list shown by `/status list` (M15). */ /** The list shown by `/status list` (M15). */
export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) { export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) {
const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot'); const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot');
if (statuses.length === 0) { if (statuses.length === 0) {
return embed.setDescription( return embed.setDescription(
`Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`, `Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`,
); );
} }
const active = statuses.filter((status) => status.enabled).length; const active = statuses.filter((status) => status.enabled).length;
embed.setDescription( embed.setDescription(
`${bullets([ `${bullets([
`**${statuses.length}** statut(s), dont **${active}** en rotation`, `**${statuses.length}** statut(s), dont **${active}** en rotation`,
`changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`, `changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`,
'la rotation suit l’ordre d’ajout et saute les statuts en pause', 'la rotation suit l’ordre d’ajout et saute les statuts en pause',
])}`, ])}`,
); );
embed.addFields( embed.addFields(
statuses.map((status) => ({ statuses.map((status) => ({
name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`, name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`,
value: describeStatus(status), value: describeStatus(status),
})), })),
); );
return embed; return embed;
} }
/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */ /** Confirmation shown after `/status add`, including when the addition changes what is displayed. */
export function statusAddedEmbed(status, { applied = false } = {}) { export function statusAddedEmbed(status, { applied = false } = {}) {
const next = applied const next = applied
? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.' ? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.'
: 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.'; : 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.';
return successEmbed( return successEmbed(
`C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`, `C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`,
).setTitle('✅ Statut ajouté'); ).setTitle('✅ Statut ajouté');
} }
+307 -295
View File
@@ -1,295 +1,307 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js'; import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { readSetting } from '../../config/guild-settings.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { getAccessLevel } from '../../core/permissions.js'; import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js'; import { getAccessLevel } from '../../core/permissions.js';
import { import { logEvent } from '../../database/repositories/event-log-repository.js';
claimTicket as claimTicketRow, import {
closeTicket as closeTicketRow, claimTicket as claimTicketRow,
createTicket as createTicketRow, closeTicket as closeTicketRow,
getTicketByChannel, createTicket as createTicketRow,
} from '../../database/repositories/ticket-repository.js'; getTicketByChannel,
import { ticketButtons } from '../../ui/buttons.js'; } from '../../database/repositories/ticket-repository.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js'; import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
const log = createLogger('tickets');
/** Ticket scope names to the FWS access level they require. */
const SCOPE_LEVELS = { /** Ticket scope names to the FWS access level they require. */
staff: ACCESS_LEVELS.STAFF, const SCOPE_LEVELS = {
dev: ACCESS_LEVELS.DEV, staff: ACCESS_LEVELS.STAFF,
owner: ACCESS_LEVELS.OWNER, dev: ACCESS_LEVELS.DEV,
}; owner: ACCESS_LEVELS.OWNER,
};
export function findCategory(categoryId) {
return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null; export function findCategory(categoryId) {
} return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null;
}
/** A member may open a ticket only for a category their access level covers (M6-T02). */
export function canUseCategory(member, category) { /** A member may open a ticket only for a category their access level covers (M6-T02). */
const level = getAccessLevel(member); export function canUseCategory(member, category) {
return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]); const level = getAccessLevel(member);
} return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]);
}
/** Static info about a ticket, used by the embeds below. */
function ticketEmbed(ticket, category) { /** Static info about a ticket, used by the embeds below. */
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne'; function ticketEmbed(ticket, category) {
return baseEmbed(COLORS.ticket) const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
.setTitle(`🎫 Ticket ${category.label} #${ticket.id}`) return baseEmbed(COLORS.ticket)
.setDescription( .setTitle(`🎫 Ticket ${category.label} #${ticket.id}`)
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` + .setDescription(
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.', `<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
) 'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
.addFields( )
{ name: 'Catégorie', value: category.label, inline: true }, .addFields(
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true }, { name: 'Catégorie', value: category.label, inline: true },
{ name: 'Pris en charge par', value: claimed, inline: true }, { name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
); { name: 'Pris en charge par', value: claimed, inline: true },
} );
}
function channelName(categoryId, username) {
const slug = username function channelName(categoryId, username) {
.toLowerCase() const slug = username
.normalize('NFD') .toLowerCase()
.replace(/[\u0300-\u036f]/g, '') .normalize('NFD')
.replace(/[^a-z0-9-]/g, '-') .replace(/[\u0300-\u036f]/g, '')
.replace(/-+/g, '-') .replace(/[^a-z0-9-]/g, '-')
.replace(/^-|-$/g, '') .replace(/-+/g, '-')
.slice(0, 40); .replace(/^-|-$/g, '')
return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100); .slice(0, 40);
} return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100);
}
/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
function buildOverwrites(guild, client, category, authorId) { /** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
const allow = [ function buildOverwrites(guild, client, category, authorId) {
PermissionFlagsBits.ViewChannel, const allow = [
PermissionFlagsBits.SendMessages, PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ReadMessageHistory, PermissionFlagsBits.SendMessages,
PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ReadMessageHistory,
]; PermissionFlagsBits.AttachFiles,
const overwrites = [ ];
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] }, const overwrites = [
{ id: authorId, allow }, { id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] }, { id: authorId, allow },
]; { id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] },
];
for (const scope of category.scope) {
const roleId = env.roles[scope]; for (const scope of category.scope) {
if (roleId) overwrites.push({ id: roleId, allow }); const roleId = env.roles[scope];
} if (roleId) overwrites.push({ id: roleId, allow });
return overwrites; }
} return overwrites;
}
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null; async function fetchTicketLogChannel(client) {
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null); if (!env.channels.ticketLogs) return null;
return channel?.isSendable() ? channel : null; const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
} return channel?.isSendable() ? channel : null;
}
async function logTicket(client, embed) {
const channel = await fetchTicketLogChannel(client); async function logTicket(client, embed) {
await channel?.send({ embeds: [embed] }); const channel = await fetchTicketLogChannel(client);
} await channel?.send({ embeds: [embed] });
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) { /** Opens a private channel for the ticket (M6-T03). */
const category = findCategory(categoryId); export async function createTicket(interaction, categoryId) {
if (!category) { const category = findCategory(categoryId);
throw new UserFacingError( if (!category) {
'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.', throw new UserFacingError(
); 'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.',
} );
if (!canUseCategory(interaction.member, category)) { }
throw new UserFacingError( if (!canUseCategory(interaction.member, category)) {
`La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`, throw new UserFacingError(
); `La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`,
} );
if (!env.channels.ticketCategory) { }
throw new UserFacingError( if (!env.channels.ticketCategory) {
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !', throw new UserFacingError(
); 'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
} );
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null); const guild = interaction.guild;
if (parent?.type !== ChannelType.GuildCategory) { const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
throw new UserFacingError( if (parent?.type !== ChannelType.GuildCategory) {
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.', throw new UserFacingError(
); '`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
} );
}
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username), const channel = await guild.channels.create({
type: ChannelType.GuildText, name: channelName(category.id, interaction.user.username),
parent: parent.id, type: ChannelType.GuildText,
topic: `Ticket ${category.label} — ${interaction.user.tag}`, parent: parent.id,
permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id), topic: `Ticket ${category.label} — ${interaction.user.tag}`,
reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`, permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id),
}); reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`,
});
let ticket;
try { let ticket;
ticket = { try {
id: createTicketRow({ ticket = {
guildId: guild.id, id: createTicketRow({
channelId: channel.id, guildId: guild.id,
categoryId: category.id, channelId: channel.id,
authorId: interaction.user.id, categoryId: category.id,
}), authorId: interaction.user.id,
guild_id: guild.id, }),
channel_id: channel.id, guild_id: guild.id,
category_id: category.id, channel_id: channel.id,
author_id: interaction.user.id, category_id: category.id,
claimed_by: null, author_id: interaction.user.id,
status: 'open', claimed_by: null,
}; status: 'open',
} catch (error) { };
// The unique index rejects a second open ticket for the same author and category. } catch (error) {
await channel.delete('Ticket en doublon').catch(() => {}); // The unique index rejects a second open ticket for the same author and category.
log.warn('Duplicate ticket rejected', error); await channel.delete('Ticket en doublon').catch(() => {});
throw new UserFacingError( log.warn('Duplicate ticket rejected', error);
'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.', throw new UserFacingError(
); 'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.',
} );
}
await channel.send({
content: `<@${ticket.author_id}>`, await channel.send({
embeds: [ticketEmbed(ticket, category)], content: `<@${ticket.author_id}>`,
components: ticketButtons(), embeds: [ticketEmbed(ticket, category)],
}); components: ticketButtons(),
});
logEvent({
guildId: guild.id, logEvent({
type: 'ticket.created', guildId: guild.id,
actorId: ticket.author_id, type: 'ticket.created',
payload: { ticketId: ticket.id, categoryId: category.id }, actorId: ticket.author_id,
}); payload: { ticketId: ticket.id, categoryId: category.id },
await logTicket( });
interaction.client, await logTicket(
baseEmbed(COLORS.ticket) interaction.client,
.setTitle('🎫 Ticket ouvert') baseEmbed(COLORS.ticket)
.setDescription(`<#${channel.id}> — ${category.label}`) .setTitle('🎫 Ticket ouvert')
.addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }), .setDescription(`<#${channel.id}> — ${category.label}`)
); .addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
} return channel;
}
/** Resolves the ticket of the current channel, or throws a user facing error. */
export async function getChannelTicket(interaction) { /** Resolves the ticket of the current channel, or throws a user facing error. */
const ticket = getTicketByChannel(interaction.channelId); export async function getChannelTicket(interaction) {
if (!ticket) { const ticket = getTicketByChannel(interaction.channelId);
throw new UserFacingError( if (!ticket) {
'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.', throw new UserFacingError(
); 'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.',
} );
if (ticket.status !== 'open') { }
throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.'); if (ticket.status !== 'open') {
} throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.');
return ticket; }
} return ticket;
}
export async function claimTicket(interaction) {
const ticket = await getChannelTicket(interaction); export async function claimTicket(interaction) {
if (ticket.claimed_by === interaction.user.id) { const ticket = await getChannelTicket(interaction);
throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.'); if (ticket.claimed_by === interaction.user.id) {
} throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.');
}
claimTicketRow(ticket.id, interaction.user.id);
logEvent({ claimTicketRow(ticket.id, interaction.user.id);
guildId: ticket.guild_id, logEvent({
type: 'ticket.claimed', guildId: ticket.guild_id,
actorId: interaction.user.id, type: 'ticket.claimed',
payload: { ticketId: ticket.id }, actorId: interaction.user.id,
}); payload: { ticketId: ticket.id },
});
await interaction.reply({
embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)], await interaction.reply({
}); embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)],
await logTicket( });
interaction.client, await logTicket(
baseEmbed(COLORS.ticket) interaction.client,
.setTitle('🎫 Ticket pris en charge') baseEmbed(COLORS.ticket)
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`) .setTitle('🎫 Ticket pris en charge')
.addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }), .setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
); .addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }),
} );
}
/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
export async function closeTicket(interaction, reason = null) { /** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
const ticket = await getChannelTicket(interaction); export async function closeTicket(interaction, reason = null) {
const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF; const ticket = await getChannelTicket(interaction);
if (interaction.user.id !== ticket.author_id && !isStaff) { const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF;
throw new PermissionDeniedError( if (interaction.user.id !== ticket.author_id && !isStaff) {
'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.', throw new PermissionDeniedError(
); 'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.',
} );
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
logEvent({ closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
guildId: ticket.guild_id, logEvent({
type: 'ticket.closed', guildId: ticket.guild_id,
actorId: interaction.user.id, type: 'ticket.closed',
payload: { ticketId: ticket.id, reason }, actorId: interaction.user.id,
}); payload: { ticketId: ticket.id, reason },
});
await interaction.reply({
embeds: [ const deleteChannel = readSetting('tickets.deleteChannelOnClose', ticket.guild_id);
successEmbed( await interaction.reply({
`Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`, embeds: [
), successEmbed(
], deleteChannel
}); ? `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`
await logTicket( : `Ticket fermé par <@${interaction.user.id}> — merci ! Le salon reste consultable, mais plus personne ne peut y écrire.`,
interaction.client, ),
baseEmbed(COLORS.ticket) ],
.setTitle('🎫 Ticket fermé') });
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`) await logTicket(
.addFields( interaction.client,
{ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }, baseEmbed(COLORS.ticket)
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true }, .setTitle('🎫 Ticket fermé')
{ name: 'Motif', value: reason || 'Non précisé' }, .setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
), .addFields(
); { name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
const channel = interaction.channel; { name: 'Motif', value: reason || 'Non précisé' },
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref(); ),
} );
/** Grants a staff member access to the ticket channel (M6-T07). */ const channel = interaction.channel;
export async function addParticipant(interaction, userId) { if (deleteChannel) {
const ticket = await getChannelTicket(interaction); setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
if (userId === ticket.author_id || userId === ticket.claimed_by) { return;
throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.'); }
}
// Archived instead of deleted: the author keeps read access, nobody can write.
await interaction.channel.permissionOverwrites.edit(userId, { await channel?.permissionOverwrites
ViewChannel: true, .edit(ticket.author_id, { SendMessages: false })
SendMessages: true, .catch(() => log.debug('Could not lock the closed ticket channel', { ticketId: ticket.id }));
ReadMessageHistory: true, }
});
/** Grants a staff member access to the ticket channel (M6-T07). */
logEvent({ export async function addParticipant(interaction, userId) {
guildId: ticket.guild_id, const ticket = await getChannelTicket(interaction);
type: 'ticket.participant.added', if (userId === ticket.author_id || userId === ticket.claimed_by) {
actorId: interaction.user.id, throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.');
payload: { ticketId: ticket.id, userId }, }
});
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] }); await interaction.channel.permissionOverwrites.edit(userId, {
} ViewChannel: true,
SendMessages: true,
/** Routes the buttons posted in ticket channels. */ ReadMessageHistory: true,
export async function handleTicketComponent(interaction) { });
switch (interaction.customId) {
case 'ticket:claim': logEvent({
await claimTicket(interaction); guildId: ticket.guild_id,
return; type: 'ticket.participant.added',
case 'ticket:close': actorId: interaction.user.id,
await closeTicket(interaction); payload: { ticketId: ticket.id, userId },
return; });
default: await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] });
log.debug(`Ignored unknown ticket component ${interaction.customId}`); }
}
} /** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:claim':
await claimTicket(interaction);
return;
case 'ticket:close':
await closeTicket(interaction);
return;
default:
log.debug(`Ignored unknown ticket component ${interaction.customId}`);
}
}
File diff suppressed because it is too large. Load diff
+99 -99
View File
@@ -1,99 +1,99 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js';
/** Discord label and custom id limits. */ /** Discord label and custom id limits. */
const LABEL_MAX = 80; const LABEL_MAX = 80;
export const POLL_CHOICES_MAX = 10; export const POLL_CHOICES_MAX = 10;
function truncate(text, max) { function truncate(text, max) {
return text.length > max ? `${text.slice(0, max - 1)}…` : text; return text.length > max ? `${text.slice(0, max - 1)}…` : text;
} }
/** Builds a row of link buttons, skipping links without a URL (M12-T03). */ /** Builds a row of link buttons, skipping links without a URL (M12-T03). */
export function linkButtons(links) { export function linkButtons(links) {
const buttons = links const buttons = links
.filter((link) => link.url) .filter((link) => link.url)
.slice(0, 5) .slice(0, 5)
.map((link) => new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel(link.label).setURL(link.url)); .map((link) => new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel(link.label).setURL(link.url));
return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : []; return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : [];
} }
/** Claim / close controls posted in a ticket channel (M6-T05 / M6-T06). */ /** Claim / close controls posted in a ticket channel (M6-T05 / M6-T06). */
export function ticketButtons() { export function ticketButtons() {
return [ return [
new ActionRowBuilder().addComponents( new ActionRowBuilder().addComponents(
new ButtonBuilder() new ButtonBuilder()
.setCustomId('ticket:claim') .setCustomId('ticket:claim')
.setLabel('Prendre en charge') .setLabel('Prendre en charge')
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId('ticket:close').setLabel('Fermer').setStyle(ButtonStyle.Danger), new ButtonBuilder().setCustomId('ticket:close').setLabel('Fermer').setStyle(ButtonStyle.Danger),
), ),
]; ];
} }
/** /**
* Control panel posted in a temporary voice channel (M14-T05): * Control panel posted in a temporary voice channel (M14-T05):
* buttons for the whole channel, select menus for a specific member. * buttons for the whole channel, select menus for a specific member.
*/ */
export function voicePanelComponents({ locked = false } = {}) { export function voicePanelComponents({ locked = false } = {}) {
return [ return [
new ActionRowBuilder().addComponents( new ActionRowBuilder().addComponents(
new ButtonBuilder() new ButtonBuilder()
.setCustomId('voice:rename') .setCustomId('voice:rename')
.setLabel('Renommer') .setLabel('Renommer')
.setEmoji('✏️') .setEmoji('✏️')
.setStyle(ButtonStyle.Secondary), .setStyle(ButtonStyle.Secondary),
new ButtonBuilder() new ButtonBuilder()
.setCustomId('voice:limit') .setCustomId('voice:limit')
.setLabel('Limiter') .setLabel('Limiter')
.setEmoji('👥') .setEmoji('👥')
.setStyle(ButtonStyle.Secondary), .setStyle(ButtonStyle.Secondary),
new ButtonBuilder() new ButtonBuilder()
.setCustomId('voice:lock') .setCustomId('voice:lock')
.setLabel(locked ? 'Déverrouiller' : 'Verrouiller') .setLabel(locked ? 'Déverrouiller' : 'Verrouiller')
.setEmoji(locked ? '🔓' : '🔒') .setEmoji(locked ? '🔓' : '🔒')
.setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary), .setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary),
new ButtonBuilder() new ButtonBuilder()
.setCustomId('voice:claim') .setCustomId('voice:claim')
.setLabel('Réclamer') .setLabel('Réclamer')
.setEmoji('👑') .setEmoji('👑')
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
new ButtonBuilder() new ButtonBuilder()
.setCustomId('voice:delete') .setCustomId('voice:delete')
.setLabel('Supprimer') .setLabel('Supprimer')
.setEmoji('🗑️') .setEmoji('🗑️')
.setStyle(ButtonStyle.Danger), .setStyle(ButtonStyle.Danger),
), ),
memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'), memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'),
memberSelect('voice:kick', 'Exclure un membre du salon...'), memberSelect('voice:kick', 'Exclure un membre du salon...'),
memberSelect('voice:transfer', 'Transférer la propriété du salon...'), memberSelect('voice:transfer', 'Transférer la propriété du salon...'),
]; ];
} }
function memberSelect(customId, placeholder) { function memberSelect(customId, placeholder) {
return new ActionRowBuilder().addComponents( return new ActionRowBuilder().addComponents(
new UserSelectMenuBuilder() new UserSelectMenuBuilder()
.setCustomId(customId) .setCustomId(customId)
.setPlaceholder(placeholder) .setPlaceholder(placeholder)
.setMinValues(1) .setMinValues(1)
.setMaxValues(1), .setMaxValues(1),
); );
} }
/** One button per choice, 5 per row at most (M10-T02). */ /** One button per choice, 5 per row at most (M10-T02). */
export function pollButtons(pollId, choices) { export function pollButtons(pollId, choices) {
const rows = []; const rows = [];
for (let start = 0; start < Math.min(choices.length, POLL_CHOICES_MAX); start += 5) { for (let start = 0; start < Math.min(choices.length, POLL_CHOICES_MAX); start += 5) {
rows.push( rows.push(
new ActionRowBuilder().addComponents( new ActionRowBuilder().addComponents(
choices.slice(start, start + 5).map((choice, offset) => choices.slice(start, start + 5).map((choice, offset) =>
new ButtonBuilder() new ButtonBuilder()
.setCustomId(`poll:${pollId}:${start + offset}`) .setCustomId(`poll:${pollId}:${start + offset}`)
.setLabel(truncate(choice, LABEL_MAX)) .setLabel(truncate(choice, LABEL_MAX))
.setStyle(ButtonStyle.Secondary), .setStyle(ButtonStyle.Secondary),
), ),
), ),
); );
} }
return rows; return rows;
} }
+55 -55
View File
@@ -1,55 +1,55 @@
import { EmbedBuilder } from 'discord.js'; import { EmbedBuilder } from 'discord.js';
import { BOT_NAME, COLORS } from '../config/constants.js'; import { BOT_NAME, COLORS } from '../config/constants.js';
/** /**
* Bot voice — one tone everywhere (M12-T02). Every user-facing string in the project follows * Bot voice — one tone everywhere (M12-T02). Every user-facing string in the project follows
* these rules, so the messages stay consistent as commands are added: * these rules, so the messages stay consistent as commands are added:
* *
* - Informal French, short sentences, active voice; never a reproach or irony. * - Informal French, short sentences, active voice; never a reproach or irony.
* - The title states the outcome, the description says what to do next. * - The title states the outcome, the description says what to do next.
* - One emoji per title, never decorative inside the body. * - One emoji per title, never decorative inside the body.
* - No gendered agreement on a person: "tu es propriétaire", "ce membre", "l'équipe", * - No gendered agreement on a person: "tu es propriétaire", "ce membre", "l'équipe",
* "la personne" — never "il / elle", "cher / chère", "ravi·e". * "la personne" — never "il / elle", "cher / chère", "ravi·e".
* - An error explains the cause, recalls the rule and offers the way out. * - An error explains the cause, recalls the rule and offers the way out.
* - Same vocabulary across modules: équipe, membre, salon, ticket, motif. * - Same vocabulary across modules: équipe, membre, salon, ticket, motif.
*/ */
export const TONE = Object.freeze({ export const TONE = Object.freeze({
success: '✅ C’est fait', success: '✅ C’est fait',
error: '❌ Oups', error: '❌ Oups',
warning: '⚠️ Attention', warning: '⚠️ Attention',
advice: '💡 Bon à savoir', advice: '💡 Bon à savoir',
}); });
/** Base embed with the shared FWS-Bot visual identity (M12-T02). */ /** Base embed with the shared FWS-Bot visual identity (M12-T02). */
export function baseEmbed(color = COLORS.primary) { export function baseEmbed(color = COLORS.primary) {
return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp(); return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp();
} }
export function infoEmbed(title, description) { export function infoEmbed(title, description) {
return baseEmbed(COLORS.info).setTitle(title).setDescription(description); return baseEmbed(COLORS.info).setTitle(title).setDescription(description);
} }
export function successEmbed(description, { title = TONE.success } = {}) { export function successEmbed(description, { title = TONE.success } = {}) {
return baseEmbed(COLORS.success).setTitle(title).setDescription(description); return baseEmbed(COLORS.success).setTitle(title).setDescription(description);
} }
export function warningEmbed(description, { title = TONE.warning } = {}) { export function warningEmbed(description, { title = TONE.warning } = {}) {
return baseEmbed(COLORS.warning).setTitle(title).setDescription(description); return baseEmbed(COLORS.warning).setTitle(title).setDescription(description);
} }
export function errorEmbed(description, { title = TONE.error } = {}) { export function errorEmbed(description, { title = TONE.error } = {}) {
return baseEmbed(COLORS.error).setTitle(title).setDescription(description); return baseEmbed(COLORS.error).setTitle(title).setDescription(description);
} }
/** Uniform list marker, so every embed lists things the same way. */ /** Uniform list marker, so every embed lists things the same way. */
export function bullets(lines) { export function bullets(lines) {
return lines return lines
.filter(Boolean) .filter(Boolean)
.map((line) => `• ${line}`) .map((line) => `• ${line}`)
.join('\n'); .join('\n');
} }
/** Adds the "what you can do now" line that most replies end with. */ /** Adds the "what you can do now" line that most replies end with. */
export function withHint(description, hint) { export function withHint(description, hint) {
return hint ? `${description}\n\n${hint}` : description; return hint ? `${description}\n\n${hint}` : description;
} }
+18 -18
View File
@@ -1,18 +1,18 @@
/** In-memory guard against duplicate actions within a time window (M13-T08). */ /** In-memory guard against duplicate actions within a time window (M13-T08). */
export function createCooldown(windowMs) { export function createCooldown(windowMs) {
const entries = new Map(); const entries = new Map();
return { return {
/** Returns true when the key is free, and locks it for `windowMs`. */ /** Returns true when the key is free, and locks it for `windowMs`. */
acquire(key) { acquire(key) {
const now = Date.now(); const now = Date.now();
const expiresAt = entries.get(key); const expiresAt = entries.get(key);
if (expiresAt && expiresAt > now) return false; if (expiresAt && expiresAt > now) return false;
entries.set(key, now + windowMs); entries.set(key, now + windowMs);
return true; return true;
}, },
release(key) { release(key) {
entries.delete(key); entries.delete(key);
}, },
}; };
} }
+19 -19
View File
@@ -1,19 +1,19 @@
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** /**
* Retries an async operation with exponential backoff (M13-T05). * Retries an async operation with exponential backoff (M13-T05).
* `shouldRetry` decides whether an error is transient. * `shouldRetry` decides whether an error is transient.
*/ */
export async function withRetry( export async function withRetry(
operation, operation,
{ retries = 2, baseDelayMs = 500, shouldRetry = () => true } = {}, { retries = 2, baseDelayMs = 500, shouldRetry = () => true } = {},
) { ) {
for (let attempt = 0; ; attempt += 1) { for (let attempt = 0; ; attempt += 1) {
try { try {
return await operation(attempt); return await operation(attempt);
} catch (error) { } catch (error) {
if (attempt >= retries || !shouldRetry(error)) throw error; if (attempt >= retries || !shouldRetry(error)) throw error;
await sleep(baseDelayMs * 2 ** attempt); await sleep(baseDelayMs * 2 ** attempt);
} }
} }
} }
+224
View File
@@ -0,0 +1,224 @@
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { countVotes, listPolls } from '../../database/repositories/poll-repository.js';
import { closeTicket, listTickets } from '../../database/repositories/ticket-repository.js';
import { listVoiceChannels } from '../../database/repositories/voice-repository.js';
import { listBotStatuses } from '../../database/repositories/bot-status-repository.js';
import { closePollById } from '../../services/polls/poll-service.js';
import {
addBotStatus,
applyStatusIfAlone,
clampRotation,
getRotationSeconds,
removeBotStatus,
saveRotationSeconds,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import {
deleteVoiceChannel,
listTriggerSummaries,
removeVoiceTriggerConfig,
saveVoiceTrigger,
setTriggerEnabled,
} from '../../services/voice/voice-service.js';
import { badRequest, notFound } from '../http.js';
/** Tickets, polls, temporary voice channels and bot presence (M16-T05). */
const guildId = () => env.discord.guildId;
export function registerCommunityRoutes(router) {
// --- Tickets ---------------------------------------------------------------
router.get(
'/api/community/tickets',
({ query }) => ({
categories: TICKET_CATEGORIES,
tickets: listTickets({
guildId: guildId(),
status: query.get('status'),
authorId: query.get('authorId'),
limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200),
}),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/tickets/:id/close',
async ({ params, body, actor, context }) => {
const id = Number.parseInt(params.id, 10);
const reason = String(body.reason ?? '').trim() || 'Clôturé depuis le tableau de bord';
const changes = closeTicket(id, { closedBy: actor.userId, reason });
if (changes === 0) throw notFound('Ticket introuvable ou déjà clôturé.');
const ticket = listTickets({ guildId: guildId(), limit: 200 }).find((row) => row.id === id);
if (ticket?.channel_id && context.client) {
const channel = await context.client.channels.fetch(ticket.channel_id).catch(() => null);
await channel?.delete(`Ticket #${id} clôturé depuis le tableau de bord`).catch(() => null);
}
logEvent({ guildId: guildId(), type: 'ticket.close', actorId: actor.userId, payload: { id, reason } });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Polls -----------------------------------------------------------------
router.get(
'/api/community/polls',
({ query }) => ({
polls: listPolls({
guildId: guildId(),
status: query.get('status'),
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100),
}).map((poll) => ({
...poll,
choices: JSON.parse(poll.choices),
counts: countVotes(poll.id),
})),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/polls/:id/close',
async ({ params, actor, context }) => {
// `closePollById` raises a `UserFacingError` when the poll is gone or already closed.
const id = Number.parseInt(params.id, 10);
await closePollById(context.client, id);
logEvent({ guildId: guildId(), type: 'poll.close', actorId: actor.userId, payload: { id } });
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Temporary voice channels ---------------------------------------------
router.get(
'/api/community/voice',
({ context }) => {
const guild = context.client?.guilds?.cache?.get(guildId());
return {
triggers: listTriggerSummaries(guildId()),
channels: listVoiceChannels(guildId()).map((row) => {
const channel = guild?.channels?.cache?.get(row.channel_id);
return {
...row,
locked: Boolean(row.locked),
alive: Boolean(channel),
members: channel?.members?.size ?? 0,
};
}),
defaults: {
triggerId: env.channels.voiceTrigger,
categoryId: env.channels.voiceCategory,
emptyGraceMs: env.voice.emptyGraceMs,
},
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.put(
'/api/community/voice/triggers/:triggerId',
({ params, body, actor }) => {
if (!/^\d{17,20}$/.test(params.triggerId)) throw badRequest('Identifiant de salon invalide.');
const trigger = saveVoiceTrigger(
guildId(),
{
triggerId: params.triggerId,
label: body.label === undefined ? undefined : String(body.label),
categoryId: body.categoryId === undefined ? undefined : String(body.categoryId),
template: body.template === undefined ? undefined : String(body.template),
userLimit: body.userLimit === undefined ? undefined : Number.parseInt(body.userLimit, 10),
},
actor.userId,
);
return { trigger };
},
{ access: ACCESS_LEVELS.DEV },
);
router.post(
'/api/community/voice/triggers/:triggerId/toggle',
({ params, body }) => ({
trigger: setTriggerEnabled(guildId(), params.triggerId, Boolean(body.enabled)),
}),
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/voice/triggers/:triggerId',
({ params }) => {
removeVoiceTriggerConfig(guildId(), params.triggerId);
return { ok: true };
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/voice/channels/:channelId',
async ({ params, context, actor }) => {
const channel = await context.client?.channels?.fetch(params.channelId).catch(() => null);
if (!channel) throw notFound('Salon introuvable.');
await deleteVoiceChannel(channel, `Supprimé depuis le tableau de bord par ${actor.username}`);
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Bot presence ----------------------------------------------------------
router.get(
'/api/community/statuses',
() => ({
statuses: listBotStatuses(),
intervalSeconds: getRotationSeconds(guildId()),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/community/statuses',
({ body, actor, context }) => {
const status = addBotStatus({
text: String(body.text ?? ''),
type: String(body.type ?? 'watching'),
url: body.url ? String(body.url) : null,
createdBy: actor.userId,
});
// Applies straight away when it is the only status, like `/status add` does.
if (context.client) applyStatusIfAlone(context.client);
return { status };
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/community/statuses/:id',
// The service raises a `UserFacingError` for an unknown id or a no-op toggle.
({ params, body }) => ({
status: toggleBotStatus(Number.parseInt(params.id, 10), Boolean(body.enabled)),
}),
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/community/statuses/:id',
({ params }) => ({ removed: removeBotStatus(Number.parseInt(params.id, 10)) }),
{ access: ACCESS_LEVELS.DEV },
);
router.put(
'/api/community/statuses/interval',
({ body, actor }) => {
const seconds = clampRotation(Number.parseInt(body.seconds ?? 0, 10), { strict: true });
saveRotationSeconds(seconds, guildId(), actor.userId);
return { intervalSeconds: seconds, restartRequired: true };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+224
View File
@@ -0,0 +1,224 @@
import { randomBytes } from 'node:crypto';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { badRequest, notFound } from '../http.js';
import {
diffValues,
maskValues,
mergeValues,
readEnvFile,
renderEnvFile,
secretStatus,
writeEnvFile,
} from '../services/env-file.js';
import { SECTIONS, VARIABLES, crossCheck, requiredKeys, validateAll } from '../services/env-schema.js';
/**
* Step by step `.env` wizard (M16-T09).
*
* Reachable by a bootstrap session, because its whole purpose is to run before
* the bot has a working configuration.
*/
const log = createLogger('web:configuration');
const WIZARD = { access: ACCESS_LEVELS.OWNER, setup: true };
/** Values currently loaded in the process, used to prefill a first run. */
const runningValues = () => ({
NODE_ENV: env.nodeEnv,
LOG_LEVEL: env.logLevel,
LOG_DIR: env.logDir,
LOG_RETENTION_DAYS: String(env.logRetentionDays),
DISCORD_CLIENT_ID: env.discord.clientId,
DISCORD_GUILD_ID: env.discord.guildId,
GITEA_URL: env.gitea.url,
GITEA_OWNER: env.gitea.owner,
GITEA_REPO: env.gitea.repo,
DATABASE_PATH: env.database.path,
});
function currentValues() {
const file = readEnvFile();
const defaults = Object.fromEntries(
VARIABLES.filter((variable) => variable.default !== undefined).map((v) => [v.key, v.default]),
);
return { file, values: { ...defaults, ...runningValues(), ...file.values } };
}
function report(values) {
const errors = validateAll(values);
const missing = requiredKeys().filter((key) => !String(values[key] ?? '').trim());
return {
errors,
warnings: crossCheck(values),
missingRequired: missing,
valid: Object.keys(errors).length === 0,
};
}
export function registerConfigurationRoutes(router) {
router.get(
'/api/configuration',
() => {
const { file, values } = currentValues();
return {
sections: SECTIONS,
variables: VARIABLES,
exists: file.exists,
unknownKeys: Object.keys(file.unknown),
values: maskValues(values),
secrets: secretStatus(values),
...report(values),
};
},
WIZARD,
);
/** Live feedback while the form is being filled, nothing is written. */
router.post(
'/api/configuration/validate',
({ body }) => {
const { values } = currentValues();
const next = mergeValues(values, body.values ?? {});
return { ...report(next), diff: diffValues(values, next) };
},
WIZARD,
);
router.post(
'/api/configuration/preview',
({ body }) => {
const { file, values } = currentValues();
const next = mergeValues(values, body.values ?? {});
// Secrets are blanked out: the preview may be copied or screenshotted.
const safe = { ...next };
for (const variable of VARIABLES) {
if (variable.type === 'secret' && safe[variable.key]) safe[variable.key] = '••••••••';
}
return { content: renderEnvFile(safe, file.unknown) };
},
WIZARD,
);
router.post(
'/api/configuration/save',
({ body, actor }) => {
const { file, values } = currentValues();
const next = mergeValues(values, body.values ?? {});
const status = report(next);
// A partial save is allowed while the wizard is still being walked through,
// but a malformed value never reaches the file.
if (!status.valid && body.force !== true) {
throw badRequest('Certaines valeurs sont invalides.', status.errors);
}
const diff = diffValues(values, next);
if (diff.length === 0) return { ...status, diff, written: false };
const { backup } = writeEnvFile(next, { unknown: file.unknown });
log.info('Configuration saved from the wizard', {
actor: actor.userId ?? 'setup',
changed: diff.map((entry) => entry.key),
});
return {
...status,
diff,
written: true,
backup,
restartRequired: diff.some((entry) => entry.restartRequired),
};
},
WIZARD,
);
router.post(
'/api/configuration/generate',
({ body }) => {
const kind = String(body.kind ?? 'hex32');
const sizes = { hex16: 16, hex32: 32 };
if (!(kind in sizes)) throw badRequest('Type de secret inconnu.');
return { value: randomBytes(sizes[kind]).toString('hex') };
},
WIZARD,
);
/**
* Tries the credentials the user just typed, before they are written to disk.
* Nothing is stored and the value never appears in the response.
*/
router.post(
'/api/configuration/test/:service',
async ({ params, body }) => {
const values = mergeValues(currentValues().values, body.values ?? {});
if (params.service === 'discord') {
const token = String(values.DISCORD_TOKEN ?? '');
if (!token) return { ok: false, detail: 'Aucun token à tester.' };
try {
const response = await fetch('https://discord.com/api/v10/users/@me', {
headers: { Authorization: `Bot ${token}` },
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) {
return {
ok: false,
detail:
response.status === 401
? 'Token refusé par Discord. Vérifie que tu as bien copié le token du bot (et non le client secret).'
: `Discord a répondu ${response.status}.`,
};
}
const user = await response.json();
return {
ok: true,
detail: `Token valide : ${user.username} (${user.id}).`,
applicationId: user.id,
};
} catch (error) {
return { ok: false, detail: `Discord injoignable : ${error.message}` };
}
}
if (params.service === 'gitea') {
const url = String(values.GITEA_URL ?? '').replace(/\/+$/, '');
const token = String(values.GITEA_TOKEN ?? '');
if (!url || !token) return { ok: false, detail: 'URL ou jeton manquant.' };
try {
const response = await fetch(`${url}/api/v1/user`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) return { ok: false, detail: `Gitea a répondu ${response.status}.` };
const user = await response.json();
const owner = String(values.GITEA_OWNER ?? '');
let detail = `Jeton valide pour « ${user.login} ».`;
let organizationReachable = true;
if (owner) {
const orgResponse = await fetch(`${url}/api/v1/orgs/${encodeURIComponent(owner)}`, {
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
organizationReachable = orgResponse.ok;
detail += orgResponse.ok
? ` Organisation « ${owner} » accessible.`
: ` En revanche l’organisation « ${owner} » est inaccessible (${orgResponse.status}).`;
}
// The token itself works: an unreachable organization is a warning, not a failure.
return { ok: true, warning: !organizationReachable, detail };
} catch (error) {
return { ok: false, detail: `Gitea injoignable : ${error.message}` };
}
}
throw notFound('Service inconnu.');
},
WIZARD,
);
}
+254
View File
@@ -0,0 +1,254 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import {
createTarget,
getDeployment,
getTarget,
listDeployments,
listTargets,
removeTarget,
updateTarget,
} from '../../database/repositories/deploy-repository.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { splitRepository } from '../../services/gitea/gitea-admin.js';
import { badRequest, forbidden, notFound } from '../http.js';
import { assertRunnable, describeTarget, runDeployment } from '../services/deploy-service.js';
/** Deploy targets and deployment history (M16-T06 / M16-T07). */
const KINDS = ['webhook', 'command', 'gitea-action'];
const guildId = () => env.discord.guildId;
/** A target's config may hold a shared secret, which never leaves the server. */
const publicTarget = (target) => ({
id: target.id,
name: target.name,
repository: target.repository,
environment: target.environment,
kind: target.kind,
autoDeploy: target.auto_deploy,
enabled: target.enabled,
summary: describeTarget(target),
config: {
url: target.config.url ?? null,
method: target.config.method ?? null,
command: target.config.command ?? null,
cwd: target.config.cwd ?? null,
workflow: target.config.workflow ?? null,
ref: target.config.ref ?? null,
hasSecret: Boolean(target.config.secret),
},
createdBy: target.created_by,
createdAt: target.created_at,
updatedAt: target.updated_at,
});
function readTargetPayload(body, { partial = false } = {}) {
const config = {};
const payload = {};
const kind = body.kind === undefined && partial ? undefined : String(body.kind ?? '');
if (kind !== undefined) {
if (!KINDS.includes(kind)) throw badRequest(`Type de cible attendu : ${KINDS.join(', ')}.`);
payload.kind = kind;
}
if (body.name !== undefined) {
const name = String(body.name).trim();
if (!/^[\w .-]{2,60}$/.test(name)) throw badRequest('Nom de cible invalide (2 à 60 caractères).');
payload.name = name;
}
if (body.repository !== undefined) {
const repository = String(body.repository).trim();
if (!splitRepository(repository)) throw badRequest('Dépôt attendu au format `organisation/depot`.');
payload.repository = repository;
}
if (body.environment !== undefined) {
const environment = String(body.environment).trim();
if (!/^[\w-]{2,30}$/.test(environment)) throw badRequest('Nom d’environnement invalide.');
payload.environment = environment;
}
if (body.autoDeploy !== undefined) payload.auto_deploy = Boolean(body.autoDeploy);
if (body.enabled !== undefined) payload.enabled = Boolean(body.enabled);
if (body.config && typeof body.config === 'object') {
const source = body.config;
if (source.url !== undefined) {
const url = String(source.url).trim();
if (url && !/^https?:\/\//.test(url)) throw badRequest('L’URL du webhook doit être en http(s).');
config.url = url;
}
if (source.method !== undefined) {
const method = String(source.method).toUpperCase();
if (!['POST', 'PUT', 'PATCH'].includes(method)) throw badRequest('Méthode HTTP non autorisée.');
config.method = method;
}
if (source.secret !== undefined) config.secret = String(source.secret);
if (source.headers !== undefined && typeof source.headers === 'object') config.headers = source.headers;
if (source.command !== undefined) config.command = String(source.command);
if (source.cwd !== undefined) config.cwd = String(source.cwd);
if (source.workflow !== undefined) config.workflow = String(source.workflow);
if (source.ref !== undefined) config.ref = String(source.ref);
if (source.inputs !== undefined && typeof source.inputs === 'object') config.inputs = source.inputs;
payload.config = config;
}
return payload;
}
/** Command targets execute shell on the host, so they stay Owner-only. */
function assertMayManage(actor, kind) {
if (kind !== 'command') return;
if (!env.web.allowCommandDeploys) {
throw forbidden('Les cibles de type commande sont désactivées (`WEB_ALLOW_COMMAND_DEPLOYS`).');
}
if (actor.accessLevel < ACCESS_LEVELS.OWNER) {
throw forbidden('Seul le niveau Owner peut gérer une cible de type commande.');
}
}
export function registerDeploymentRoutes(router) {
router.get(
'/api/deploy/targets',
({ query }) => ({
targets: listTargets({ guildId: guildId(), repository: query.get('repository') }).map(publicTarget),
commandDeploysAllowed: env.web.allowCommandDeploys,
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/deploy/targets',
({ body, actor }) => {
const payload = readTargetPayload(body);
if (!payload.name || !payload.repository || !payload.kind) {
throw badRequest('`name`, `repository` et `kind` sont obligatoires.');
}
assertMayManage(actor, payload.kind);
const target = createTarget({
guildId: guildId(),
name: payload.name,
repository: payload.repository,
environment: payload.environment ?? 'production',
kind: payload.kind,
config: payload.config ?? {},
autoDeploy: payload.auto_deploy ?? false,
enabled: payload.enabled ?? true,
createdBy: actor.userId,
});
logEvent({
guildId: guildId(),
type: 'web.deploy.target.create',
actorId: actor.userId,
payload: { name: target.name, kind: target.kind },
});
return publicTarget(target);
},
{ access: ACCESS_LEVELS.DEV },
);
router.patch(
'/api/deploy/targets/:id',
({ params, body, actor }) => {
const current = getTarget(Number.parseInt(params.id, 10));
if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.');
const payload = readTargetPayload(body, { partial: true });
assertMayManage(actor, payload.kind ?? current.kind);
// A partial config patch must not wipe the secret already stored.
if (payload.config) payload.config = { ...current.config, ...payload.config };
const updated = updateTarget(current.id, payload);
logEvent({
guildId: guildId(),
type: 'web.deploy.target.update',
actorId: actor.userId,
payload: { name: updated.name },
});
return publicTarget(updated);
},
{ access: ACCESS_LEVELS.DEV },
);
router.delete(
'/api/deploy/targets/:id',
({ params, actor }) => {
const current = getTarget(Number.parseInt(params.id, 10));
if (!current || current.guild_id !== guildId()) throw notFound('Cible introuvable.');
removeTarget(current.id);
logEvent({
guildId: guildId(),
type: 'web.deploy.target.delete',
actorId: actor.userId,
payload: { name: current.name },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
/** Dry run: checks the target without contacting anything. */
router.post(
'/api/deploy/targets/:id/check',
({ params }) => {
const target = getTarget(Number.parseInt(params.id, 10));
if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.');
try {
assertRunnable(target);
return { ok: true, summary: describeTarget(target) };
} catch (error) {
return { ok: false, reason: error.message };
}
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/deploy/targets/:id/run',
async ({ params, body, actor, context }) => {
const target = getTarget(Number.parseInt(params.id, 10));
if (!target || target.guild_id !== guildId()) throw notFound('Cible introuvable.');
assertMayManage(actor, target.kind);
const deployment = await runDeployment(context.client, target, {
ref: body.ref ? String(body.ref) : null,
releaseTag: body.releaseTag ? String(body.releaseTag) : null,
source: 'web',
triggeredBy: actor.userId,
});
return deployment;
},
{ access: ACCESS_LEVELS.DEV },
);
router.get(
'/api/deployments',
({ query }) => ({
deployments: listDeployments({
guildId: guildId(),
repository: query.get('repository'),
status: query.get('status'),
targetId: query.get('targetId') ? Number.parseInt(query.get('targetId'), 10) : null,
limit: Math.min(Number.parseInt(query.get('limit') ?? '30', 10), 100),
}),
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/deployments/:id',
({ params }) => {
const deployment = getDeployment(Number.parseInt(params.id, 10));
if (!deployment || deployment.guild_id !== guildId()) throw notFound('Déploiement introuvable.');
return deployment;
},
{ access: ACCESS_LEVELS.STAFF },
);
}
+404
View File
@@ -0,0 +1,404 @@
import { ChannelType, REST, Routes } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { canActOn, getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
countByAction,
listActions,
recordAction,
} from '../../database/repositories/moderation-repository.js';
import {
listNotificationChannels,
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { sendModerationLog } from '../../services/moderation/moderation-service.js';
import { badRequest, forbidden, notFound } from '../http.js';
/** Discord server management from the dashboard (M16-T05). */
const log = createLogger('web:discord');
const guildId = () => env.discord.guildId;
function guildOf(context) {
const guild = context.client?.guilds?.cache?.get(guildId());
if (!guild) throw badRequest('Le bot n’est connecté à aucun serveur pour l’instant.');
return guild;
}
/** Resolves the caller as a guild member so the role hierarchy can be enforced. */
async function actingMember(guild, actor) {
if (!actor.userId) throw forbidden('Cette action demande une session Discord, pas un jeton d’API.');
const member = await guild.members.fetch(actor.userId).catch(() => null);
if (!member) throw forbidden('Ton compte n’est plus membre du serveur.');
return member;
}
const CHANNEL_KINDS = {
[ChannelType.GuildText]: 'text',
[ChannelType.GuildVoice]: 'voice',
[ChannelType.GuildCategory]: 'category',
[ChannelType.GuildAnnouncement]: 'announcement',
[ChannelType.GuildStageVoice]: 'stage',
[ChannelType.GuildForum]: 'forum',
};
const summarizeMember = (member) => ({
id: member.id,
username: member.user.username,
displayName: member.displayName,
avatar: member.displayAvatarURL({ size: 64 }),
bot: member.user.bot,
joinedAt: member.joinedAt?.toISOString() ?? null,
createdAt: member.user.createdAt?.toISOString() ?? null,
roles: member.roles.cache.filter((role) => role.id !== member.guild.id).map((role) => role.id),
accessLevel: getAccessLevel(member),
accessLabel: ACCESS_LABELS[getAccessLevel(member)],
timeoutUntil: member.communicationDisabledUntil?.toISOString() ?? null,
});
export function registerDiscordRoutes(router) {
router.get(
'/api/discord/guild',
async ({ context }) => {
const guild = guildOf(context);
await guild.channels.fetch().catch(() => null);
return {
id: guild.id,
name: guild.name,
description: guild.description,
icon: guild.iconURL({ size: 256 }),
banner: guild.bannerURL({ size: 512 }),
ownerId: guild.ownerId,
memberCount: guild.memberCount,
createdAt: guild.createdAt?.toISOString() ?? null,
boostTier: guild.premiumTier,
boostCount: guild.premiumSubscriptionCount,
verificationLevel: guild.verificationLevel,
features: guild.features,
channels: guild.channels.cache
.map((channel) => ({
id: channel.id,
name: channel.name,
kind: CHANNEL_KINDS[channel.type] ?? 'other',
parentId: channel.parentId,
position: channel.rawPosition,
nsfw: channel.nsfw ?? false,
topic: channel.topic ?? null,
}))
.sort((a, b) => a.position - b.position),
roles: guild.roles.cache
.filter((role) => role.id !== guild.id)
.map((role) => ({
id: role.id,
name: role.name,
color: role.hexColor,
position: role.position,
managed: role.managed,
mentionable: role.mentionable,
memberCount: role.members.size,
}))
.sort((a, b) => b.position - a.position),
mapping: {
roles: env.roles,
channels: env.channels,
},
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/discord/members',
async ({ context, query }) => {
const guild = guildOf(context);
const search = (query.get('q') ?? '').trim().toLowerCase();
const limit = Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200);
const members = await guild.members.fetch().catch(() => guild.members.cache);
const matched = members
.filter((member) =>
search === ''
? true
: member.user.username.toLowerCase().includes(search) ||
member.displayName.toLowerCase().includes(search) ||
member.id === search,
)
.first(limit);
return { total: guild.memberCount, members: matched.map(summarizeMember) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/discord/members/:id',
async ({ context, params }) => {
const guild = guildOf(context);
const member = await guild.members.fetch(params.id).catch(() => null);
if (!member) throw notFound('Membre introuvable sur le serveur.');
return {
...summarizeMember(member),
history: listActions({ guildId: guild.id, targetId: member.id, limit: 50 }),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.post(
'/api/discord/members/:id/roles',
async ({ context, params, body, actor }) => {
const guild = guildOf(context);
const actorMember = await actingMember(guild, actor);
const member = await guild.members.fetch(params.id).catch(() => null);
if (!member) throw notFound('Membre introuvable sur le serveur.');
if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.');
const roleId = String(body.roleId ?? '');
const role = guild.roles.cache.get(roleId);
if (!role) throw badRequest('Rôle introuvable.');
if (role.position >= actorMember.roles.highest.position && guild.ownerId !== actorMember.id) {
throw forbidden('Ce rôle est au-dessus du tien.');
}
const action = body.action === 'remove' ? 'remove' : 'add';
if (action === 'add') await member.roles.add(role, `Tableau de bord — ${actor.username}`);
else await member.roles.remove(role, `Tableau de bord — ${actor.username}`);
recordAction({
guildId: guild.id,
action: 'role',
moderatorId: actor.userId,
targetId: member.id,
reason: `${action === 'add' ? 'Ajout' : 'Retrait'} du rôle ${role.name} depuis le tableau de bord`,
});
return { ok: true, roles: summarizeMember(member).roles };
},
{ access: ACCESS_LEVELS.DEV },
);
/** Applies a moderation action, mirroring what the slash commands do (M8). */
router.post(
'/api/discord/moderation',
async ({ context, body, actor }) => {
const guild = guildOf(context);
const actorMember = await actingMember(guild, actor);
const action = String(body.action ?? '');
if (!['warn', 'mute', 'kick', 'ban'].includes(action)) {
throw badRequest('Action attendue : warn, mute, kick ou ban.');
}
const member = await guild.members.fetch(String(body.userId ?? '')).catch(() => null);
if (!member) throw notFound('Membre introuvable sur le serveur.');
if (!canActOn(actorMember, member)) throw forbidden('Ce membre est au moins aussi haut placé que toi.');
const reason = String(body.reason ?? '').trim() || 'Non précisé';
const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null;
if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) {
throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.');
}
const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`;
if (action === 'mute') await member.timeout(durationMs, audit);
else if (action === 'kick') await member.kick(audit);
else if (action === 'ban') await member.ban({ reason: audit, deleteMessageSeconds: 0 });
recordAction({
guildId: guild.id,
action,
moderatorId: actor.userId,
targetId: member.id,
reason,
durationMs,
});
logEvent({
guildId: guild.id,
type: `moderation.${action}`,
actorId: actor.userId,
payload: { targetId: member.id, reason, durationMs, source: 'web' },
});
await sendModerationLog(context.client, guild, {
action,
targetId: member.id,
moderatorId: actor.userId,
reason,
durationMs,
});
return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/discord/moderation',
({ query }) => ({
actions: listActions({
guildId: guildId(),
targetId: query.get('userId'),
action: query.get('action'),
limit: Math.min(Number.parseInt(query.get('limit') ?? '50', 10), 200),
}),
totals: countByAction(guildId()),
}),
{ access: ACCESS_LEVELS.STAFF },
);
/** Publishes a message in a channel: announcements, maintenance notices. */
router.post(
'/api/discord/announce',
async ({ context, body, actor }) => {
const guild = guildOf(context);
const channelId = String(body.channelId ?? '') || env.channels.announcements;
if (!channelId) throw badRequest('Aucun salon de destination.');
const channel = await context.client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) throw badRequest('Salon introuvable ou non accessible en écriture.');
const content = String(body.content ?? '').trim();
const title = String(body.title ?? '').trim();
if (content === '' && title === '') throw badRequest('Le message est vide.');
const payload = body.asEmbed
? {
embeds: [
{
title: title || undefined,
description: content || undefined,
color: Number.parseInt(String(body.color ?? '0x1793d1'), 16) || 0x1793d1,
footer: { text: `Publié par ${actor.displayName ?? actor.username}` },
timestamp: new Date().toISOString(),
},
],
}
: { content: title ? `**${title}**\n${content}` : content };
const message = await channel.send(payload);
logEvent({
guildId: guild.id,
type: 'web.announce',
actorId: actor.userId,
payload: { channelId, messageId: message.id },
});
log.info('Announcement published from the dashboard', { channelId, actor: actor.userId });
return { ok: true, messageId: message.id, url: message.url };
},
{ access: ACCESS_LEVELS.STAFF },
);
// --- Notification routing --------------------------------------------------
router.get(
'/api/discord/notifications',
() => ({
overrides: listNotificationChannels(guildId()),
defaults: {
issues: env.channels.notifIssues,
pull_requests: env.channels.notifPullRequests,
commits: env.channels.notifCommits,
releases: env.channels.notifReleases,
errors: env.channels.notifErrors,
announcements: env.channels.announcements,
community: env.channels.logs,
},
}),
{ access: ACCESS_LEVELS.STAFF },
);
router.put(
'/api/discord/notifications/:type',
({ params, body, actor }) => {
const channelId = String(body.channelId ?? '').trim();
if (channelId === '') {
removeNotificationChannel(guildId(), params.type);
return { ok: true, removed: true };
}
if (!/^\d{17,20}$/.test(channelId)) throw badRequest('Identifiant de salon invalide.');
setNotificationChannel({
guildId: guildId(),
type: params.type,
channelId,
detailLevel: String(body.detailLevel ?? 'normal'),
});
logEvent({
guildId: guildId(),
type: 'web.notifications.update',
actorId: actor.userId,
payload: { type: params.type, channelId },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.STAFF },
);
/**
* Publishes the slash commands on the guild, what `npm run deploy:commands`
* does. Guild commands take effect immediately, so the result is visible in
* Discord as soon as this returns.
*/
router.post(
'/api/discord/commands/deploy',
async ({ context, actor }) => {
const commands = [...(context.client?.commands?.values() ?? [])];
if (commands.length === 0) throw badRequest('Aucune commande chargée : le bot n’est pas prêt.');
if (!env.discord.token || !env.discord.clientId || !env.discord.guildId) {
throw badRequest('`DISCORD_TOKEN`, `DISCORD_CLIENT_ID` et `DISCORD_GUILD_ID` sont requis.');
}
const body = commands.map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token);
try {
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), {
body,
});
} catch (error) {
log.error('Slash command deployment failed', error);
throw new ExternalApiError('discord', error.message ?? 'Publication refusée par Discord');
}
logEvent({
guildId: guildId(),
type: 'web.commands.deploy',
actorId: actor.userId,
payload: { count: body.length },
});
log.info('Slash commands deployed from the dashboard', { count: body.length, actor: actor.userId });
return { ok: true, count: body.length, names: body.map((command) => command.name).sort() };
},
{ access: ACCESS_LEVELS.OWNER },
);
/** Read-only inventory of the loaded slash commands and their required level. */
router.get(
'/api/discord/commands',
({ context }) => ({
commands: [...(context.client?.commands?.values() ?? [])]
.map((command) => {
// `toJSON()` flattens the builder, whose option objects are builders too.
const definition = command.data.toJSON();
return {
name: definition.name,
description: definition.description,
access: command.access ?? ACCESS_LEVELS.USER,
accessLabel: ACCESS_LABELS[command.access ?? ACCESS_LEVELS.USER],
subcommandAccess: command.subcommandAccess ?? null,
options: (definition.options ?? []).map((option) => ({
name: option.name,
description: option.description,
type: option.type,
})),
};
})
.sort((a, b) => a.name.localeCompare(b.name)),
}),
{ access: ACCESS_LEVELS.STAFF },
);
}
+72
View File
@@ -0,0 +1,72 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { registerAuthRoutes } from '../auth/routes.js';
import { openEventStream } from '../events.js';
import { VERSION, buildAt } from '../services/build-info.js';
import { registerCommunityRoutes } from './community.js';
import { registerConfigurationRoutes } from './configuration.js';
import { registerDeploymentRoutes } from './deployments.js';
import { registerDiscordRoutes } from './discord.js';
import { registerLogRoutes } from './logs.js';
import { registerOrganizationRoutes } from './organization.js';
import { registerOverviewRoutes } from './overview.js';
import { registerProjectRoutes } from './projects.js';
import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js';
import { registerSearchRoutes } from './search.js';
import { registerSettingsRoutes } from './settings.js';
import { registerStatusRoutes } from './status.js';
import { registerWikiRoutes } from './wiki.js';
/**
* Route registration order matters only for readability: the router matches on
* the full pattern, not on declaration order.
*/
export function registerApiRoutes(router, { setupOnly = false } = {}) {
// Liveness probe for a reverse proxy or an uptime monitor. Registered first so
// it answers even in bootstrap mode, when nothing else is mounted.
router.get(
'/api/health',
({ context }) => ({
status: context.client?.isReady?.() ? 'ok' : 'starting',
setupOnly: context.setupOnly,
uptimeMs: Date.now() - context.startedAt,
version: VERSION,
buildAt: buildAt(),
}),
{ public: true },
);
registerAuthRoutes(router);
registerConfigurationRoutes(router);
// The public documentation stays reachable even while the bot is being set up.
registerWikiRoutes(router);
// So does the status page: a bot still being configured is exactly what an
// uptime monitor, or a visitor, would want to be told.
registerStatusRoutes(router);
// Long-lived stream the pages listen to instead of polling (M16-T12).
router.get(
'/api/events',
({ request, response, actor }) => {
openEventStream(request, response, actor);
},
{ access: ACCESS_LEVELS.STAFF },
);
// In bootstrap mode the bot is not connected and the database may be empty:
// only the wizard makes sense.
if (setupOnly) return router;
registerOverviewRoutes(router);
registerOrganizationRoutes(router);
registerProjectRoutes(router);
registerRepositoryRoutes(router);
registerReleaseRoutes(router);
registerDeploymentRoutes(router);
registerDiscordRoutes(router);
registerCommunityRoutes(router);
registerSearchRoutes(router);
registerSettingsRoutes(router);
registerLogRoutes(router);
return router;
}
+96
View File
@@ -0,0 +1,96 @@
import { readFile, readdir, stat } from 'node:fs/promises';
import path from 'node:path';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { maskSecrets } from '../../core/logger.js';
import { getDatabase } from '../../database/index.js';
import { badRequest, notFound } from '../http.js';
/** Functional event log and technical log files (M16-T05). */
const LOG_FILE = /^\d{4}-\d{2}-\d{2}\.log$/;
export function registerLogRoutes(router) {
router.get(
'/api/logs/events',
({ query }) => {
const clauses = [];
const params = [];
const type = query.get('type');
if (type) {
clauses.push('type LIKE ?');
params.push(`${type}%`);
}
const actorId = query.get('actorId');
if (actorId) {
clauses.push('actor_id = ?');
params.push(actorId);
}
const limit = Math.min(Number.parseInt(query.get('limit') ?? '100', 10), 500);
params.push(limit);
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
const events = getDatabase()
.prepare(`SELECT * FROM event_logs ${where} ORDER BY id DESC LIMIT ?`)
.all(...params)
.map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null }));
return {
events,
types: getDatabase()
.prepare(
'SELECT type, COUNT(*) AS count FROM event_logs GROUP BY type ORDER BY count DESC LIMIT 40',
)
.all(),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/logs/files',
async () => {
const entries = await readdir(env.logDir).catch(() => []);
const files = [];
for (const name of entries.filter((entry) => LOG_FILE.test(entry))) {
const info = await stat(path.join(env.logDir, name)).catch(() => null);
if (info) files.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() });
}
return { directory: env.logDir, files: files.sort((a, b) => b.name.localeCompare(a.name)) };
},
{ access: ACCESS_LEVELS.DEV },
);
router.get(
'/api/logs/files/:name',
async ({ params, query }) => {
// The name pattern is the only thing standing between this route and the
// rest of the filesystem, so it is strict on purpose.
if (!LOG_FILE.test(params.name)) throw badRequest('Nom de fichier de log invalide.');
const content = await readFile(path.join(env.logDir, params.name), 'utf8').catch(() => null);
if (content === null) throw notFound('Fichier de log introuvable.');
const lines = Math.min(Number.parseInt(query.get('lines') ?? '300', 10), 2000);
const level = query.get('level');
const parsed = content
.split('\n')
.filter(Boolean)
.map((line) => {
try {
return JSON.parse(line);
} catch {
return { level: 'info', message: line };
}
})
.filter((entry) => !level || entry.level === level);
// `maskSecrets` already ran at write time; it runs again in case the file
// predates a secret rotation.
return { name: params.name, entries: JSON.parse(maskSecrets(JSON.stringify(parsed.slice(-lines)))) };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+179
View File
@@ -0,0 +1,179 @@
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { org } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { badRequest } from '../http.js';
/** Organization-wide management (M16-T04). */
const requireGitea = () => {
if (!isGiteaConfigured()) throw badRequest('Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`).');
};
const toMember = (member) => ({
id: member.id,
login: member.login ?? member.username,
fullName: member.full_name,
email: member.email,
avatar: member.avatar_url,
isAdmin: member.is_admin,
lastLogin: member.last_login,
createdAt: member.created,
});
export function registerOrganizationRoutes(router) {
router.get(
'/api/organization',
async () => {
requireGitea();
const [details, members, teams, repositories] = await Promise.all([
org.get(),
org.listMembers({ limit: 100 }).catch(() => []),
org.listTeams({ limit: 100 }).catch(() => []),
org.listRepos({ limit: 100 }).catch(() => []),
]);
return {
name: details.username ?? details.name,
fullName: details.full_name,
description: details.description,
website: details.website,
location: details.location,
email: details.email,
avatar: details.avatar_url,
visibility: details.visibility,
url: `${env.gitea.url}/${details.username ?? details.name}`,
members: members.map(toMember),
teams: teams.map((team) => ({
id: team.id,
name: team.name,
description: team.description,
permission: team.permission,
includesAllRepositories: team.includes_all_repositories,
canCreateOrgRepo: team.can_create_org_repo,
units: team.units,
})),
repositories: repositories.map((repository) => ({
id: repository.id,
fullName: repository.full_name,
name: repository.name,
description: repository.description,
private: repository.private,
archived: repository.archived,
fork: repository.fork,
template: repository.template,
defaultBranch: repository.default_branch,
stars: repository.stars_count,
forks: repository.forks_count,
watchers: repository.watchers_count,
openIssues: repository.open_issues_count,
openPulls: repository.open_pr_counter,
releases: repository.release_counter,
sizeKb: repository.size,
language: repository.language,
updatedAt: repository.updated_at,
createdAt: repository.created_at,
htmlUrl: repository.html_url,
hasIssues: repository.has_issues,
hasPullRequests: repository.has_pull_requests,
hasActions: repository.has_actions,
})),
};
},
{ access: ACCESS_LEVELS.STAFF },
);
router.patch(
'/api/organization',
async ({ body, actor }) => {
requireGitea();
const payload = {};
for (const field of ['full_name', 'description', 'website', 'location', 'visibility']) {
if (field in body) payload[field] = String(body[field] ?? '');
}
if (Object.keys(payload).length === 0) throw badRequest('Aucun champ modifiable fourni.');
await org.update(payload);
logEvent({
guildId: env.discord.guildId || null,
type: 'web.organization.update',
actorId: actor.userId,
payload: { fields: Object.keys(payload) },
});
return { ok: true };
},
{ access: ACCESS_LEVELS.OWNER },
);
router.get(
'/api/organization/teams/:id/members',
async ({ params }) => {
requireGitea();
const members = await org.listTeamMembers(Number.parseInt(params.id, 10));
return { members: members.map(toMember) };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/organization/labels',
async () => {
requireGitea();
return { labels: await org.listLabels() };
},
{ access: ACCESS_LEVELS.STAFF },
);
router.get(
'/api/organization/hooks',
async () => {
requireGitea();
const hooks = await org.listHooks().catch(() => []);
return {
hooks: hooks.map((hook) => ({
id: hook.id,
type: hook.type,
active: hook.active,
events: hook.events,
url: hook.config?.url,
createdAt: hook.created_at,
})),
};
},
{ access: ACCESS_LEVELS.DEV },
);
/** Creates a repository inside the organization (M16-T04). */
router.post(
'/api/organization/repositories',
async ({ body, actor }) => {
requireGitea();
const name = String(body.name ?? '').trim();
if (!/^[\w.-]{1,100}$/.test(name)) {
throw badRequest('Nom de dépôt invalide : lettres, chiffres, `.`, `-` et `_` uniquement.');
}
const created = await org.createRepo({
name,
description: String(body.description ?? ''),
private: Boolean(body.private),
auto_init: body.autoInit !== false,
default_branch: String(body.defaultBranch ?? 'main'),
gitignores: body.gitignores ?? undefined,
license: body.license ?? undefined,
readme: body.readme ?? undefined,
issue_labels: body.issueLabels ?? undefined,
});
logEvent({
guildId: env.discord.guildId || null,
type: 'web.repository.create',
actorId: actor.userId,
payload: { repository: created.full_name },
});
return { fullName: created.full_name, htmlUrl: created.html_url };
},
{ access: ACCESS_LEVELS.DEV },
);
}
+158
View File
@@ -0,0 +1,158 @@
import { version as discordJsVersion } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { getDatabase } from '../../database/index.js';
import {
countByStatus,
lastDeploymentPerEnvironment,
} from '../../database/repositories/deploy-repository.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { countVoiceChannels } from '../../database/repositories/voice-repository.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { org } from '../../services/gitea/gitea-admin.js';
/** Aggregated landing page of the dashboard (M16-T05). */
const guildId = () => env.discord.guildId;
function botSnapshot(client, startedAt) {
const guild = client?.guilds?.cache?.get(guildId()) ?? null;
return {
online: Boolean(client?.isReady?.()),
username: client?.user?.username ?? null,
discriminator: client?.user?.discriminator ?? null,
avatar: client?.user?.displayAvatarURL?.({ size: 128 }) ?? null,
ping: client?.ws?.ping ?? null,
uptimeMs: Date.now() - startedAt,
nodeVersion: process.version,
discordJsVersion,
memoryMb: Math.round(process.memoryUsage().rss / 1024 / 1024),
commands: client?.commands?.size ?? 0,
guild: guild
? {
id: guild.id,
name: guild.name,
icon: guild.iconURL?.({ size: 128 }) ?? null,
memberCount: guild.memberCount,
channelCount: guild.channels.cache.size,
roleCount: guild.roles.cache.size,
boostTier: guild.premiumTier,
createdAt: guild.createdAt?.toISOString() ?? null,
}
: null,
};
}
function databaseSnapshot() {
const database = getDatabase();
const tables = database
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
.all()
.map((row) => row.name);
const counts = Object.fromEntries(
tables.map((table) => [table, database.prepare(`SELECT COUNT(*) AS count FROM "${table}"`).get().count]),
);
const pageCount = database.prepare('PRAGMA page_count').get();
const pageSize = database.prepare('PRAGMA page_size').get();
return {
path: env.database.path,
tables: counts,
sizeBytes: (pageCount?.page_count ?? 0) * (pageSize?.page_size ?? 0),
migrations: database.prepare('SELECT name, applied_at FROM schema_migrations ORDER BY name').all(),
};
}
async function giteaSnapshot() {
if (!isGiteaConfigured()) return { configured: false };
const [organization, repositories] = await Promise.all([
org.get().catch(() => null),
org.listRepos({ limit: 50 }).catch(() => []),
]);
const totals = repositories.reduce(
(accumulator, repository) => ({
openIssues: accumulator.openIssues + (repository.open_issues_count ?? 0),
openPulls: accumulator.openPulls + (repository.open_pr_counter ?? 0),
stars: accumulator.stars + (repository.stars_count ?? 0),
forks: accumulator.forks + (repository.forks_count ?? 0),
sizeKb: accumulator.sizeKb + (repository.size ?? 0),
}),
{ openIssues: 0, openPulls: 0, stars: 0, forks: 0, sizeKb: 0 },
);
return {
configured: true,
url: env.gitea.url,
organization: organization && {
name: organization.username ?? organization.name,
fullName: organization.full_name,
description: organization.description,
website: organization.website,
location: organization.location,
avatar: organization.avatar_url,
visibility: organization.visibility,
},
repositoryCount: repositories.length,
...totals,
repositories: repositories
.slice()
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
.slice(0, 6)
.map((repository) => ({
fullName: repository.full_name,
description: repository.description,
private: repository.private,
archived: repository.archived,
stars: repository.stars_count,
openIssues: repository.open_issues_count,
openPulls: repository.open_pr_counter,
updatedAt: repository.updated_at,
htmlUrl: repository.html_url,
})),
};
}
function recentEvents(limit = 15) {
return getDatabase()
.prepare('SELECT id, type, actor_id, payload, created_at FROM event_logs ORDER BY id DESC LIMIT ?')
.all(limit)
.map((row) => ({ ...row, payload: row.payload ? JSON.parse(row.payload) : null }));
}
export function registerOverviewRoutes(router) {
router.get(
'/api/overview',
async ({ context }) => {
const id = guildId();
const gitea = await giteaSnapshot();
return {
bot: botSnapshot(context.client, context.startedAt),
gitea,
database: databaseSnapshot(),
activity: {
openTickets: id ? countOpenTickets(id) : 0,
polls: id ? countPolls(id) : 0,
voiceChannels: id ? countVoiceChannels(id) : 0,
moderation: id ? countByAction(id) : [],
deployments: id ? countByStatus(id) : [],
environments: id ? lastDeploymentPerEnvironment(id) : [],
},
events: recentEvents(),
features: {
webhooks: env.webhook.enabled,
commandDeploys: env.web.allowCommandDeploys,
restart: env.web.allowRestart,
gitea: isGiteaConfigured(),
},
links: env.links,
};
},
{ access: ACCESS_LEVELS.STAFF },
);
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more