With line, arrow, circle and area, the stroke being saved stayed the current draft until the save finished, and every mouse movement in that moment sent it live again - after "saved" had gone out. The others then saw the stroke with the drawer's name again until the bot dropped it after 20 s. Drawing quickly (short breaks between strokes) hit this almost every time. - A stroke that is being saved no longer follows the mouse and is never sent live again; the live service also ignores updates for strokes it has already ended. - Viewers remember finished strokes and ignore late updates for them. If someone leaves in the middle of a stroke (reason "left"), the others reload once to get what was saved meanwhile. - The bot (live_tactics.py) ignores late updates of finished strokes too, which also covers browsers still running the previous map version - deployed on 2026-09-25. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
290 lines
11 KiB
JavaScript
290 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.endedIds = []; // zuletzt abgeschlossene Striche - die gehen nie wieder raus
|
|
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.endedIds = [];
|
|
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) {
|
|
// Nachzuegler eines schon abgeschlossenen Strichs (z.B. Mausbewegung waehrend des Speicherns)
|
|
if (!this.tacticId || this.endedIds.includes(id)) 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;
|
|
}
|
|
this.endedIds.push(id);
|
|
if (this.endedIds.length > 50) this.endedIds.shift();
|
|
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'));
|
|
}
|
|
}
|