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