Files
FWS-DiscordBot/src/commands/fws/fws.js
T

239 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws');
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder()
.setName('fws')
.setDescription('Informations sur 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('status').setDescription('État des services et projets'))
.addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles'))
.addSubcommand((sub) =>
sub
.setName('changelog')
.setDescription('Nouveautés d’une version')
.addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'),
),
);
const officialLinks = () => [
{ label: 'Site', url: env.links.website },
{ label: 'Documentation', url: env.links.docs },
{ label: 'Dépôt FWS Arch', url: env.links.archRepo },
{ label: 'Gitea', url: env.gitea.url },
{ label: 'Discord', url: env.links.discordInvite },
];
/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
function readSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch (error) {
log.debug(`Could not read setting ${key}`, error);
return fallback;
}
}
const DEFAULT_PRESENTATION =
'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
async function latestRelease() {
try {
return await gitea.getLatestRelease();
} catch {
return asList(await gitea.listReleases(1))[0] ?? null;
}
}
async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: 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`.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
async function showStatus(interaction) {
await interaction.deferReply();
const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured
? await gitea
.listReleases(1)
.then(() => true)
.catch(() => false)
: false;
let openTickets = null;
try {
openTickets = countOpenTickets(interaction.guildId);
} catch (error) {
log.warn('Database unavailable while building /fws status', error);
}
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('🩺 État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Pas encore configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable pour le moment',
inline: false,
},
{
name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false,
},
{
name: 'Base SQLite',
value:
openTickets === null
? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false,
},
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
}
async function showChangelog(interaction) {
const version = interaction.options.getString('version');
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
});
} catch (error) {
if (version) {
log.warn(`Release ${version} not found`, error);
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
),
],
});
return;
}
await replyGiteaFailure(interaction, error);
}
}
/** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'info':
await showInfo(interaction);
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
case 'version':
await showVersion(interaction);
return;
case 'status':
await showStatus(interaction);
return;
case 'changelog':
await showChangelog(interaction);
return;
default:
return;
}
}