feat(gitea): add embeds, modals and the issue and pull request commands

Creating an issue or a pull request needs a title and a description, which do not fit in a slash command option, so the branches chosen as options are kept in memory for a few minutes until the modal is submitted.
This commit is contained in:
BlackAngelTV committed 2026-09-15 14:50:40 +02:00
1 parent 66be463ba3
commit 76d0bf9250
7 files changed
+470 -12

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim();
if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Pas de description.')
.addFields(
{ name: 'Auteur', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
);
if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Labels', value: labels.join(', ') });
return embed;
}
/** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Pas de description.')
.addFields(
{ name: 'Auteur', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
if (pull.html_url) embed.setURL(pull.html_url);
return embed;
}
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`)
.addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
);
if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
}
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed;
}
/** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits
.slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit dans cet événement.')
.addFields(
{ name: 'Auteur', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true },
);
if (remaining > 0) embed.addFields({ name: 'Et', value: `${remaining} autre(s) commit(s)` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
/** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
+148
View File
@@ -0,0 +1,148 @@
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() {
if (!isGiteaConfigured()) {
throw new UserFacingError('Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN`.');
}
}
function modal(id, title, fields) {
return new ModalBuilder()
.setCustomId(id)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true),
),
),
);
}
/** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) {
assertGiteaConfigured();
await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]),
);
}
/** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) {
assertGiteaConfigured();
const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]),
);
}
/** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error);
const detail =
error instanceof ExternalApiError && /not configured/.test(error.message)
? 'Gitea n’est pas configuré.'
: 'Gitea est momentanément indisponible. Réessaie dans quelques instants.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {});
} else {
await interaction.reply(payload).catch(() => {});
}
}
export async function submitIssueModal(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.issue.created',
actorId: interaction.user.id,
payload: { number: issue.number },
});
await interaction.editReply({
embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
export async function submitPullRequestModal(interaction) {
assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`);
if (!context) {
throw new UserFacingError('Session expirée : relance `/pr create` pour choisir à nouveau les branches.');
}
await interaction.deferReply();
try {
const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head,
base: context.base,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.pull_request.created',
actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base },
});
await interaction.editReply({
embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) {
switch (interaction.customId) {
case 'issue:create':
await submitIssueModal(interaction);
return;
case 'pr:create':
await submitPullRequestModal(interaction);
return;
default:
log.debug(`Ignored unknown modal ${interaction.customId}`);
}
}
+32
View File
@@ -0,0 +1,32 @@
/**
* 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).
* Entries expire on their own and disappear on restart.
*/
const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs });
return value;
}
/** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key);
if (!entry) return null;
entries.delete(key);
return entry.expiresAt > now ? entry.value : null;
}
export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
return entries.size;
}
export function pendingCount() {
return entries.size;
}