2020-11-10 15:27:28 -09:00
|
|
|
import { baseUrl } from './utils'
|
2020-11-07 20:06:48 -09:00
|
|
|
import throttle from 'lodash.throttle'
|
2020-11-13 14:40:33 -09:00
|
|
|
import { processEvent, serverDown } from './actions'
|
2020-11-20 16:22:22 -09:00
|
|
|
import { REST_URL } from './consts'
|
2025-06-12 20:06:08 -08:00
|
|
|
import config from './config'
|
2020-11-07 20:06:48 -09:00
|
|
|
|
2023-05-17 07:22:36 -08:00
|
|
|
const newEventStream = async () => {
|
|
|
|
|
let url = baseUrl(`${REST_URL}/events`)
|
|
|
|
|
if (localStorage.getItem('token')) {
|
|
|
|
|
url = url + `?jwt=${localStorage.getItem('token')}`
|
2020-11-07 20:06:48 -09:00
|
|
|
}
|
2023-05-17 07:22:36 -08:00
|
|
|
return new EventSource(url)
|
2021-11-29 14:49:29 -09:00
|
|
|
}
|
|
|
|
|
|
2023-05-17 07:22:36 -08:00
|
|
|
const eventHandler = (dispatchFn) => (event) => {
|
2021-06-09 17:02:20 -08:00
|
|
|
const data = JSON.parse(event.data)
|
|
|
|
|
if (event.type !== 'keepAlive') {
|
2023-05-17 07:22:36 -08:00
|
|
|
dispatchFn(processEvent(event.type, data))
|
2021-06-09 17:02:20 -08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-17 07:22:36 -08:00
|
|
|
const throttledEventHandler = (dispatchFn) =>
|
|
|
|
|
throttle(eventHandler(dispatchFn), 100, { trailing: true })
|
2020-11-25 16:46:21 -09:00
|
|
|
|
2023-05-17 07:22:36 -08:00
|
|
|
const startEventStream = async (dispatchFn) => {
|
2021-06-13 08:46:36 -08:00
|
|
|
if (!localStorage.getItem('is-authenticated')) {
|
2021-11-29 14:49:29 -09:00
|
|
|
return Promise.resolve()
|
2020-11-09 11:59:21 -09:00
|
|
|
}
|
2023-05-17 07:22:36 -08:00
|
|
|
return newEventStream()
|
2020-12-13 10:44:57 -09:00
|
|
|
.then((newStream) => {
|
2023-05-17 07:22:36 -08:00
|
|
|
newStream.addEventListener('serverStart', eventHandler(dispatchFn))
|
|
|
|
|
newStream.addEventListener(
|
|
|
|
|
'scanStatus',
|
2023-12-18 10:56:03 -09:00
|
|
|
throttledEventHandler(dispatchFn),
|
2023-05-17 07:22:36 -08:00
|
|
|
)
|
|
|
|
|
newStream.addEventListener('refreshResource', eventHandler(dispatchFn))
|
2025-06-12 20:06:08 -08:00
|
|
|
if (config.enableNowPlaying) {
|
|
|
|
|
newStream.addEventListener('nowPlayingCount', eventHandler(dispatchFn))
|
|
|
|
|
}
|
2023-05-17 07:22:36 -08:00
|
|
|
newStream.addEventListener('keepAlive', eventHandler(dispatchFn))
|
2020-12-13 10:44:57 -09:00
|
|
|
newStream.onerror = (e) => {
|
2024-09-28 07:54:36 -08:00
|
|
|
// eslint-disable-next-line no-console
|
2020-12-13 10:44:57 -09:00
|
|
|
console.log('EventStream error', e)
|
2023-05-17 07:22:36 -08:00
|
|
|
dispatchFn(serverDown())
|
2020-12-13 10:44:57 -09:00
|
|
|
}
|
|
|
|
|
return newStream
|
|
|
|
|
})
|
|
|
|
|
.catch((e) => {
|
2024-09-28 07:54:36 -08:00
|
|
|
// eslint-disable-next-line no-console
|
2020-12-13 10:44:57 -09:00
|
|
|
console.log(`Error connecting to server:`, e)
|
|
|
|
|
})
|
2020-11-07 20:06:48 -09:00
|
|
|
}
|
2020-11-20 16:22:22 -09:00
|
|
|
|
2023-05-17 07:22:36 -08:00
|
|
|
export { startEventStream }
|