- Each queued alert keeps an embed and a link button: the destination illustration as thumbnail, the tier, score and loot for a return, the difficulty and automatic departure for a new group. - The button and the message link open #/cards/expeditions/<id>, which scrolls to the player's expedition or group and highlights it; Discord login now returns to that link. - Without an https CARDS_PUBLIC_ORIGIN the link stays in the text, without button or thumbnail, which Discord would refuse. - Delivery docs name palico-bot's NOTIFICATIONS_API_KEY and its local-only route on port 3101. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lines
7.2 KiB
JavaScript
113 lines
7.2 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";
|
||
import { expeditionReturnedMessage, groupOpenedMessage } from "./alert-messages.js";
|
||
|
||
// 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);
|
||
},
|
||
|
||
// `message` : { content, embed?, link? } (alert-messages.js), ou un simple texte.
|
||
enqueueInTx(playerId, kind, message) {
|
||
const { content, embed = null, link = null } = typeof message === "string" ? { content: message } : message;
|
||
const extra = embed || link ? JSON.stringify({ ...(embed ? { embed } : {}), ...(link ? { link } : {}) }) : null;
|
||
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, extra_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, extra, this.now());
|
||
},
|
||
|
||
// Groupe ouvert : prévient les autres joueurs qui ont activé cette alerte.
|
||
queueGroupOpenedInTx(creatorId, setup, expeditionId) {
|
||
if (!this.alertsActive()) return;
|
||
const creator = this.db.prepare("SELECT display_name FROM players WHERE id = ?").get(creatorId);
|
||
const message = groupOpenedMessage({ creatorName: creator?.display_name, setup, expeditionId, origin: this.publicOrigin, catalog: this.cards.catalog });
|
||
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", message);
|
||
}
|
||
},
|
||
|
||
// Expéditions rentrées depuis le dernier passage : une alerte par joueur qui l'a activée, une seule fois par expédition. Les groupes
|
||
// dont l'inscription est échue partent d'abord : sans visite de joueur, leur retour serait sinon invisible au passage périodique.
|
||
queueReturnAlerts() {
|
||
if (!this.alertsActive()) return 0;
|
||
this.settleForming();
|
||
let queued = 0;
|
||
this.cards.database.transaction(() => {
|
||
const rows = this.db.prepare(`SELECT e.id, e.setup_json, e.result_json, m.reward_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);
|
||
const message = expeditionReturnedMessage({ setup, result: JSON.parse(row.result_json || "null"), reward: JSON.parse(row.reward_json || "null"), expeditionId: row.id, origin: this.publicOrigin, catalog: this.cards.catalog });
|
||
this.enqueueInTx(row.player_id, "expedition_returned", message);
|
||
queued += 1;
|
||
}
|
||
});
|
||
return queued;
|
||
},
|
||
|
||
// Messages à envoyer. Au moment de l'envoi, l'alerte doit encore être voulue : coupée par l'administration, ou désactivée par le
|
||
// joueur pour ce type de message, elle est abandonnée (marquée en échec, jamais renvoyée plus tard, quand elle serait périmée).
|
||
pendingAlerts(limit = 20) {
|
||
const pending = () => this.db.prepare(`SELECT o.id, o.kind, o.content, o.extra_json, o.attempts, p.discord_id, a.group_opened, a.expedition_returned FROM alert_outbox o
|
||
JOIN players p ON p.id = o.player_id LEFT JOIN player_alerts a ON a.player_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`).all();
|
||
const drop = this.db.prepare("UPDATE alert_outbox SET failed_at = ?, last_error = ? WHERE id = ?");
|
||
const wanted = [];
|
||
this.cards.database.transaction(() => {
|
||
const active = this.alertsActive();
|
||
for (const row of pending()) {
|
||
const allowed = row.kind === "group_opened" ? row.group_opened : row.kind === "expedition_returned" ? row.expedition_returned : 0;
|
||
if (!active) drop.run(this.now(), "alerts disabled", row.id);
|
||
else if (!allowed) drop.run(this.now(), "player opted out", row.id);
|
||
else if (wanted.length < limit) wanted.push({ id: row.id, content: row.content, extra: JSON.parse(row.extra_json || "{}"), attempts: row.attempts, discordId: row.discord_id });
|
||
}
|
||
});
|
||
return wanted;
|
||
},
|
||
|
||
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);
|
||
}
|
||
};
|