78 lines
2.6 KiB
JavaScript
78 lines
2.6 KiB
JavaScript
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();
|
||
},
|
||
};
|
||
}
|