2023-09-12 20:14:17 +02:00
|
|
|
import { setWebSocketConnected } from "app/slices/server"
|
2023-01-17 21:14:38 +01:00
|
|
|
import { reloadTree } from "app/slices/tree"
|
|
|
|
|
import { useAppDispatch } from "app/store"
|
|
|
|
|
import { useEffect } from "react"
|
|
|
|
|
import WebsocketHeartbeatJs from "websocket-heartbeat-js"
|
|
|
|
|
|
|
|
|
|
export const useWebSocket = () => {
|
|
|
|
|
const dispatch = useAppDispatch()
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const currentUrl = new URL(window.location.href)
|
|
|
|
|
const wsProtocol = currentUrl.protocol === "http:" ? "ws" : "wss"
|
|
|
|
|
const wsUrl = `${wsProtocol}://${currentUrl.hostname}:${currentUrl.port}/ws`
|
|
|
|
|
|
2023-09-12 20:22:34 +02:00
|
|
|
const ws = new WebsocketHeartbeatJs({
|
|
|
|
|
url: wsUrl,
|
|
|
|
|
pingMsg: "ping",
|
|
|
|
|
// ping interval, just under a minute to prevent firewalls from closing idle connections
|
|
|
|
|
pingTimeout: 55000,
|
|
|
|
|
})
|
2023-09-12 20:14:17 +02:00
|
|
|
ws.onopen = () => dispatch(setWebSocketConnected(true))
|
|
|
|
|
ws.onclose = () => dispatch(setWebSocketConnected(false))
|
2023-01-17 21:14:38 +01:00
|
|
|
ws.onmessage = event => {
|
|
|
|
|
const { data } = event
|
|
|
|
|
if (typeof data === "string") {
|
|
|
|
|
if (data.startsWith("new-feed-entries:")) dispatch(reloadTree())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => ws.close()
|
|
|
|
|
}, [dispatch])
|
|
|
|
|
}
|