- Players turn on alerts one by one in their account: someone opens an expedition group, or one of their expeditions returns; both stay off until chosen. - Opening a group queues a direct message for each other subscribed player; every 30 seconds the server queues returned expeditions once and sends pending messages to palico-bot's direct message route. - Permanent refusals (unknown account, closed direct messages) or five failures stop retries; only real Discord accounts receive alerts, and sent rows are purged after 30 days. - CARDS_DISCORD_ALERTS_URL and CARDS_DISCORD_ALERTS_KEY enable the feature; Administration › Guilde can turn every alert off, and the privacy notice explains what is sent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
96 lines
5.6 KiB
JavaScript
96 lines
5.6 KiB
JavaScript
// Rôle : alertes Discord des Expéditions Sokko TCG : choix de chaque joueur, file des messages à envoyer (groupe ouvert, expédition de retour).
|
||
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) ; l'envoi lui-même est fait par discord-alerts.js.
|
||
import { randomUUID } from "node:crypto";
|
||
|
||
// Un vrai compte Discord : le compte de développement et les comptes supprimés n'ont pas d'identifiant numérique.
|
||
const DISCORD_ID_PATTERN = /^\d{17,20}$/;
|
||
export const MAX_ALERT_ATTEMPTS = 5;
|
||
const OUTBOX_RETENTION_MS = 30 * 24 * 3_600_000;
|
||
|
||
export const alertMethods = {
|
||
// Les alertes partent si le bot est configuré sur ce serveur et si l'administration ne les a pas coupées.
|
||
alertsActive(settings = this.settings) {
|
||
return Boolean(this.alertsAvailable) && settings.alerts.enabled;
|
||
},
|
||
|
||
alertPreferences(playerId) {
|
||
const row = this.db.prepare("SELECT group_opened, expedition_returned FROM player_alerts WHERE player_id = ?").get(playerId);
|
||
return { available: this.alertsActive(), groupOpened: Boolean(row?.group_opened), expeditionReturned: Boolean(row?.expedition_returned) };
|
||
},
|
||
|
||
setAlertPreferences(playerId, { groupOpened, expeditionReturned } = {}) {
|
||
if (typeof groupOpened !== "boolean" || typeof expeditionReturned !== "boolean") {
|
||
throw Object.assign(new Error("Choix d’alertes invalide."), { status: 400, code: "ALERTS_INVALID" });
|
||
}
|
||
this.db.prepare(`INSERT INTO player_alerts(player_id, group_opened, expedition_returned, updated_at) VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(player_id) DO UPDATE SET group_opened = excluded.group_opened, expedition_returned = excluded.expedition_returned, updated_at = excluded.updated_at`)
|
||
.run(playerId, Number(groupOpened), Number(expeditionReturned), this.now());
|
||
return this.cards.getState(playerId);
|
||
},
|
||
|
||
expeditionsLink() {
|
||
return this.publicOrigin ? ` ${this.publicOrigin}/#/cards/expeditions` : "";
|
||
},
|
||
|
||
enqueueInTx(playerId, kind, content) {
|
||
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, created_at) VALUES (?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, this.now());
|
||
},
|
||
|
||
// Groupe ouvert : prévient les autres joueurs qui ont activé cette alerte.
|
||
queueGroupOpenedInTx(creatorId, setup) {
|
||
if (!this.alertsActive()) return;
|
||
const creator = this.db.prepare("SELECT display_name FROM players WHERE id = ?").get(creatorId);
|
||
const content = `${creator?.display_name || "Un joueur"} ouvre un groupe d’expédition vers ${setup.destination.name} (${"★".repeat(setup.stars)}, ${setup.hours} h). Rejoignez-le sur le tableau de la Guilde :${this.expeditionsLink()}`;
|
||
for (const row of this.db.prepare(`SELECT p.id, p.discord_id FROM player_alerts a JOIN players p ON p.id = a.player_id
|
||
WHERE a.group_opened = 1 AND p.deleted_at IS NULL AND p.id != ?`).all(creatorId)) {
|
||
if (DISCORD_ID_PATTERN.test(row.discord_id)) this.enqueueInTx(row.id, "group_opened", content);
|
||
}
|
||
},
|
||
|
||
// Expéditions rentrées depuis le dernier passage : une alerte par joueur qui l'a activée, une seule fois par expédition.
|
||
queueReturnAlerts() {
|
||
if (!this.alertsActive()) return 0;
|
||
let queued = 0;
|
||
this.cards.database.transaction(() => {
|
||
const rows = this.db.prepare(`SELECT e.id, e.setup_json, m.player_id, p.discord_id, a.expedition_returned FROM expedition_members m
|
||
JOIN expeditions e ON e.id = m.expedition_id JOIN players p ON p.id = m.player_id LEFT JOIN player_alerts a ON a.player_id = m.player_id
|
||
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL AND m.alerted_at IS NULL`).all(this.now());
|
||
const mark = this.db.prepare("UPDATE expedition_members SET alerted_at = ? WHERE expedition_id = ? AND player_id = ?");
|
||
for (const row of rows) {
|
||
mark.run(this.now(), row.id, row.player_id);
|
||
if (!row.expedition_returned || !DISCORD_ID_PATTERN.test(row.discord_id)) continue;
|
||
const setup = JSON.parse(row.setup_json);
|
||
this.enqueueInTx(row.player_id, "expedition_returned", `Votre expédition vers ${setup.destination.name} est de retour ! Récupérez son butin :${this.expeditionsLink()}`);
|
||
queued += 1;
|
||
}
|
||
});
|
||
return queued;
|
||
},
|
||
|
||
pendingAlerts(limit = 20) {
|
||
return this.db.prepare(`SELECT o.id, o.content, o.attempts, p.discord_id FROM alert_outbox o JOIN players p ON p.id = o.player_id
|
||
WHERE o.sent_at IS NULL AND o.failed_at IS NULL AND p.deleted_at IS NULL ORDER BY o.created_at LIMIT ?`).all(limit)
|
||
.map((row) => ({ id: row.id, content: row.content, attempts: row.attempts, discordId: row.discord_id }));
|
||
},
|
||
|
||
markAlertSent(id) {
|
||
this.db.prepare("UPDATE alert_outbox SET sent_at = ?, attempts = attempts + 1 WHERE id = ?").run(this.now(), id);
|
||
},
|
||
|
||
// Échec : on réessaie plus tard, sauf si l'échec est définitif (compte inconnu, messages privés fermés) ou trop répété.
|
||
markAlertFailed(id, error, { permanent = false } = {}) {
|
||
const row = this.db.prepare("SELECT attempts FROM alert_outbox WHERE id = ?").get(id);
|
||
const attempts = (row?.attempts ?? 0) + 1;
|
||
this.db.prepare("UPDATE alert_outbox SET attempts = ?, last_error = ?, failed_at = ? WHERE id = ?")
|
||
.run(attempts, String(error).slice(0, 200), permanent || attempts >= MAX_ALERT_ATTEMPTS ? this.now() : null, id);
|
||
},
|
||
|
||
forgetAlertsInTx(playerId) {
|
||
this.db.prepare("DELETE FROM player_alerts WHERE player_id = ?").run(playerId);
|
||
this.db.prepare("DELETE FROM alert_outbox WHERE player_id = ?").run(playerId);
|
||
},
|
||
|
||
purgeAlertOutbox() {
|
||
this.db.prepare("DELETE FROM alert_outbox WHERE COALESCE(sent_at, failed_at) <= ?").run(this.now() - OUTBOX_RETENTION_MS);
|
||
}
|
||
};
|