LuminaWebsite/assets/map/js/services/TacticLiveService.js
Maaxxs df656209c9 Map tactics live: strokes appear for everyone while they are drawn, several people can draw at once
- Whoever has a tactic open sees the strokes of the others while they are being drawn (with the
  name at the pen tip); saved and erased shapes appear at once, and after changes to steps or the
  tactic the map reloads by itself. Several people can draw in parallel, also in the same step.
- The panel shows who is in the tactic (a click jumps to their step), dots in the step list show
  who is where and blink while someone draws there; the step bar shows "✏️ Name" for the shown step.
- The Discord bot relays it (live_tactics.py in the bot repo, only in memory): tactics_api.php
  issues a ticket (action live_token: account, display name, tactic, may draw, 30 minutes, signed
  with raids_api.key via HMAC-SHA256, tactic_live_ticket() in includes/tactics.php). The browser
  receives via Server-Sent Events and sends batched strokes (at most every 70 ms), saved/removed
  shapes, changes and its own step via POST (assets/map/js/services/TacticLiveService.js).
  Only who may edit the tactic may draw live. Saving still happens only on the website.
- On a lost connection the panel says so, the map reconnects with a fresh ticket (backoff up to
  15 s), reloads the tactic and hands in what was drawn meanwhile. Reloads triggered by the live
  view keep the current state on network errors instead of closing the tactic.
- Optional config raids_api.live_url for a public bot address that differs from raids_api.url.
- Privacy policy (live view: direct connection to the bot server, what others see, nothing stored),
  patch notes and README updated.

Needs the matching bot update (live_tactics.py, api.py, main.py), deployed on 2026-09-25.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 01:16:19 +02:00

285 lines
11 KiB
JavaScript

/**
* TacticLiveService - Live-Ansicht einer Taktik: Striche der anderen erscheinen, waehrend sie
* entstehen, gespeicherte und geloeschte Zeichnungen sofort, dazu wer gerade dabei ist.
*
* Verteiler ist die Bot-API (live_tactics.py im Bot). Die Website stellt ein kurz gueltiges Ticket
* aus (tactics_api.php, Aktion live_token); damit empfaengt der Browser per Server-Sent Events und
* schickt eigene Ereignisse per POST. Gespeichert wird weiterhin nur ueber tactics_api.php - reisst
* die Verbindung ab, holt sich die Karte ein neues Ticket und laedt die Taktik frisch (hello).
*
* handlers: onEvent(event, tacticId), onStatus(status), onTicketError(error)
* status: off | connecting | live | offline | unavailable (Bot-API nicht eingerichtet)
*/
class TacticLiveService {
constructor(tacticService, handlers) {
this.service = tacticService;
this.handlers = handlers;
this.tacticId = null;
this.ticket = null;
this.source = null;
this.conn = null; // Kennung dieser Verbindung beim Verteiler (aus "hello")
this.status = 'off';
this.session = 0; // jede betretene Taktik zaehlt hoch - Rueckmeldungen der alten verfallen
this.generation = 0; // ebenso jede neue Verbindung (auch innerhalb einer Taktik)
this.retryDelay = 1000;
this.retryTimer = null;
this.outbox = []; // Ereignisse in Reihenfolge, die noch raus muessen
this.draft = null; // Strich, der gerade entsteht (wird gebuendelt verschickt)
this.sending = false;
this.flushTimer = null;
this.lastSend = 0;
}
/** Live-Ansicht dieser Taktik betreten (null: verlassen). */
join(tacticId) {
if (tacticId === this.tacticId) return;
this.leave();
if (!tacticId) return;
this.tacticId = tacticId;
this.connect();
}
leave() {
this.session++;
this.generation++;
clearTimeout(this.retryTimer);
clearTimeout(this.flushTimer);
this.flushTimer = null;
this.closeSource();
this.tacticId = null;
this.ticket = null;
this.conn = null;
this.outbox = [];
this.draft = null;
this.sending = false;
this.retryDelay = 1000;
this.setStatus('off');
}
closeSource() {
if (this.source) {
this.source.close();
this.source = null;
}
}
setStatus(status) {
if (status === this.status) return;
this.status = status;
this.handlers.onStatus(status);
}
async connect() {
const generation = ++this.generation;
this.closeSource();
this.conn = null;
// Nur beim ersten Mal "wird aufgebaut" - nach einem Abbruch bleibt es bis zum Erfolg bei "unterbrochen",
// beim Erneuern des Tickets bei "Live".
if (this.status === 'off') this.setStatus('connecting');
let ticket;
try {
ticket = await this.service.send('live_token', { tactic_id: this.tacticId });
} catch (e) {
if (generation !== this.generation) return;
if (e.data && e.data.live_unavailable) {
this.setStatus('unavailable');
return;
}
// Z.B. inzwischen privat oder geloescht - die Karte laedt neu und verlaesst die Taktik dann
this.handlers.onTicketError(e);
this.retry(generation);
return;
}
if (generation !== this.generation) return;
this.ticket = ticket;
const source = new EventSource(ticket.stream_url);
this.source = source;
source.onmessage = message => {
if (generation !== this.generation) return;
let event;
try {
event = JSON.parse(message.data);
} catch (e) {
return;
}
this.receive(event);
};
// Nicht den Automatismus des Browsers nehmen (der kaeme mit dem alten Ticket) - selbst neu verbinden.
source.onerror = () => {
if (generation !== this.generation) return;
this.closeSource();
this.conn = null;
this.retry(generation);
};
}
retry(generation) {
this.setStatus('offline');
clearTimeout(this.retryTimer);
const delay = this.retryDelay;
this.retryDelay = Math.min(this.retryDelay * 2, 15000);
this.retryTimer = setTimeout(() => {
if (generation === this.generation) this.connect();
}, delay);
}
receive(event) {
if (event.type === 'expired') {
// Ticket abgelaufen: mit einem neuen weiter (die Rechte werden dabei neu geprueft)
this.connect();
return;
}
if (event.type === 'hello') {
this.conn = event.conn;
this.retryDelay = 1000;
this.setStatus('live');
// Ein Strich, der gerade entsteht, geht nach einem Abbruch komplett neu raus.
if (this.draft) {
this.draft.sent = 0;
this.draft.dirty = true;
}
}
this.handlers.onEvent(event, this.tacticId);
if (event.type === 'hello') this.flush();
}
// ------------------------------------------------------------------
// Senden
// ------------------------------------------------------------------
canDraw() {
return !!(this.ticket && this.ticket.can_draw);
}
/**
* Sofort und unabhaengig von der Warteschlange - fuer Aenderungen, nach denen die Taktik evtl.
* gleich verlassen wird (z.B. geloescht): leave() verwirft die Warteschlange, das hier nicht.
*/
sendNow(event) {
if (!this.conn || !this.ticket) {
this.push(event);
return;
}
fetch(this.ticket.send_url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Live-Token': this.ticket.token },
body: JSON.stringify({ conn: this.conn, events: [event] }),
keepalive: true
}).catch(() => { /* dann laden die anderen spaetestens beim Neuverbinden frisch */ });
}
/** Ereignis in die Warteschlange (Reihenfolge bleibt erhalten). */
push(event) {
if (!this.tacticId) return;
this.outbox.push(event);
// Offline wird nicht endlos gesammelt - nach dem Neuverbinden laden die anderen ohnehin frisch.
if (this.outbox.length > 200) this.outbox.splice(0, this.outbox.length - 200);
this.schedule();
}
/**
* Strich, der gerade entsteht. growing: die Punkte werden nur hinten laenger (Stift) - dann geht
* nur der Nachschub raus; sonst (Linie, Pfeil, Kreis, Flaeche) immer der ganze Strich.
*/
updateDraft(id, stepId, shape, points, growing) {
if (!this.tacticId) return;
if (!this.draft || this.draft.id !== id) {
this.materializeDraft();
this.draft = { id, sent: 0 };
}
Object.assign(this.draft, { step: stepId, shape, points, growing, dirty: true });
this.schedule();
}
/** Strich abgeschlossen: Rest verschicken. cancelled: er wird nicht gespeichert und verschwindet bei allen. */
endDraft(id, cancelled) {
if (this.draft && this.draft.id === id) {
this.materializeDraft();
this.draft = null;
}
if (cancelled) this.push({ type: 'draft_end', id });
else this.schedule();
}
materializeDraft() {
const draft = this.draft;
if (!draft || !draft.dirty) return;
draft.dirty = false;
const append = draft.growing && draft.sent > 0 && draft.sent <= draft.points.length;
const points = append ? draft.points.slice(draft.sent) : draft.points.slice();
if (append && points.length === 0) return;
draft.sent = draft.points.length;
this.outbox.push({
type: 'draft', id: draft.id, step: draft.step, shape: draft.shape, append,
points: points.map(p => [Math.round(p[0] * 100) / 100, Math.round(p[1] * 100) / 100])
});
}
/** Hoechstens alle 70 ms ein Paket - so bleibt der Strich fluessig, ohne den Server zu fluten. */
schedule() {
if (this.flushTimer || this.sending) return;
const wait = Math.max(0, 70 - (Date.now() - this.lastSend));
this.flushTimer = setTimeout(() => {
this.flushTimer = null;
this.flush();
}, wait);
}
async flush() {
if (this.sending || !this.conn || !this.ticket) return;
this.materializeDraft();
if (this.outbox.length === 0) return;
const session = this.session;
const conn = this.conn;
const ticket = this.ticket;
const events = this.outbox.splice(0, 30);
this.sending = true;
this.lastSend = Date.now();
let status = 0;
try {
const response = await fetch(ticket.send_url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Live-Token': ticket.token },
body: JSON.stringify({ conn, events })
});
status = response.status;
} catch (e) {
status = -1; // Netz weg - der Empfangskanal merkt das auch und verbindet neu
}
// Inzwischen eine andere Taktik: leave() hat alles zurueckgesetzt, die alten Ereignisse verfallen.
if (session !== this.session) return;
this.sending = false;
if (status === 401 || status === 409) {
// Ticket abgelaufen bzw. der Verteiler kennt die Verbindung nicht (mehr) - nachreichen. Lief
// das Paket noch ueber eine alte Verbindung, genuegt das; sonst neu verbinden.
this.requeue(events);
if (conn === this.conn && ticket === this.ticket) {
this.connect();
return;
}
} else if (status === -1 || status === 429 || status >= 500) {
// Netz weg, zu viel auf einmal oder Server-Fehler: kurz warten, dann nachreichen
this.requeue(events);
this.flushTimer = setTimeout(() => {
this.flushTimer = null;
this.flush();
}, 1000);
return;
}
// Sonst (auch bei abgelehnten Daten) weiter mit dem Rest - live ist nur ein Hinweis, gespeichert
// ist schon auf der Website.
if (this.outbox.length || (this.draft && this.draft.dirty)) this.schedule();
}
/** Gespeicherte/geloeschte Zeichnungen und Aenderungen nach dem Neuverbinden nachreichen - Entwuerfe nicht. */
requeue(events) {
this.outbox.unshift(...events.filter(e => e.type !== 'draft'));
}
}