hippofish/packages/client/src/stream.ts

47 lines
988 B
TypeScript
Raw Normal View History

2024-03-28 17:26:52 +01:00
import { Stream } from "firefish-js";
import { markRaw } from "vue";
2024-03-30 17:30:50 +01:00
import { url } from "@/config";
import { me } from "@/me";
let stream: Stream | null = null;
let timeoutHeartBeat: number | null = null;
2024-03-02 06:24:05 +01:00
export let isReloading = false;
export function useStream() {
if (stream != null) return stream;
stream = markRaw(
new Stream(
url,
2024-03-07 03:06:45 +01:00
me
? {
2024-03-07 03:06:45 +01:00
token: me.token,
}
: null,
),
);
timeoutHeartBeat = window.setTimeout(heartbeat, 1000 * 60);
return stream;
}
export function reloadStream() {
if (stream == null) return useStream();
if (timeoutHeartBeat != null) window.clearTimeout(timeoutHeartBeat);
isReloading = true;
stream.close();
stream.once("_connected_", () => (isReloading = false));
stream.stream.reconnect();
isReloading = false;
return stream;
}
function heartbeat(): void {
if (stream != null && document.visibilityState === "visible") {
stream.send("ping");
}
timeoutHeartBeat = window.setTimeout(heartbeat, 1000 * 60);
}