inhaus-plugin-chat/resources/js/lib/sync.js
Friederich Loheide 2844452002 Nachrichten-Plugin 1.0.0: Direktnachrichten, Gruppen, Anhänge, GIFs, Emojis
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 16:34:53 +00:00

78 lines
2.6 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 { api } from './api';
/**
* Hält den Chat aktuell: fragt regelmäßig nach („Gibt es Neues?“) – häufig, solange die Seite
* sichtbar ist, selten im Hintergrund. Ist Echtzeit eingerichtet, löst ein Signal des
* Pusher-kompatiblen Dienstes die Abfrage sofort aus; das Nachfragen läuft dann nur noch als Rückfall.
*/
export function createSync({ realtime, userId, openId, lastId, onUpdate }) {
let cursor = null;
let timer = null;
let running = false;
let stopped = false;
let socket = null;
const interval = () => {
const visible = document.visibilityState === 'visible';
if (socket?.connection?.state === 'connected') return visible ? 20000 : 60000;
return visible ? (document.hasFocus() ? 3000 : 6000) : 30000;
};
async function tick() {
if (running || stopped) return;
running = true;
clearTimeout(timer);
try {
const data = await api.updates({ seit: cursor, offen: openId(), nach: lastId() });
cursor = data.cursor;
onUpdate(data);
} catch {
// Netzwerk kurz weg – nächster Versuch folgt
} finally {
running = false;
if (!stopped) timer = setTimeout(tick, interval());
}
}
const wake = () => document.visibilityState === 'visible' && tick();
document.addEventListener('visibilitychange', wake);
window.addEventListener('focus', wake);
if (realtime) {
import('pusher-js').then(({ default: Pusher }) => {
if (stopped) return;
socket = new Pusher(realtime.key, {
cluster: realtime.cluster,
...(realtime.host ? { wsHost: realtime.host, wsPort: realtime.port, wssPort: realtime.port, forceTLS: realtime.tls, enabledTransports: ['ws', 'wss'] } : {}),
channelAuthorization: {
endpoint: '/chat/api/echtzeit/anmelden',
headers: { 'X-XSRF-TOKEN': decodeURIComponent(document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/)?.[1] ?? ''), Accept: 'application/json' },
},
});
socket.subscribe(`private-chat-user-${userId}`).bind('update', () => tick());
}).catch(() => {});
}
tick();
return {
now: tick,
reset() {
cursor = null;
tick();
},
stop() {
stopped = true;
clearTimeout(timer);
document.removeEventListener('visibilitychange', wake);
window.removeEventListener('focus', wake);
socket?.disconnect();
},
};
}