4
0

websocket.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {
  2. refreshServerConnectionLabel
  3. } from './marshaller.js'
  4. window.ws = null
  5. export function checkWebsocketConnection () {
  6. if (window.ws === null || window.ws.readyState === 3) {
  7. reconnectWebsocket()
  8. }
  9. }
  10. function reconnectWebsocket () {
  11. window.websocketAvailable = false
  12. const websocketConnectionUrl = new URL(window.location.toString())
  13. websocketConnectionUrl.hash = ''
  14. websocketConnectionUrl.pathname = '/websocket'
  15. if (window.location.protocol === 'https:') {
  16. websocketConnectionUrl.protocol = 'wss'
  17. } else {
  18. websocketConnectionUrl.protocol = 'ws'
  19. }
  20. window.websocketConnectionUrl = websocketConnectionUrl
  21. const ws = window.ws = new WebSocket(websocketConnectionUrl.toString())
  22. ws.addEventListener('open', websocketOnOpen)
  23. ws.addEventListener('message', websocketOnMessage)
  24. ws.addEventListener('error', websocketOnError)
  25. ws.addEventListener('close', websocketOnClose)
  26. }
  27. function websocketOnOpen (evt) {
  28. window.websocketAvailable = true
  29. window.ws.send('monitor')
  30. refreshServerConnectionLabel()
  31. window.refreshLoop()
  32. }
  33. function websocketOnMessage (msg) {
  34. // FIXME check msg status is OK
  35. const j = JSON.parse(msg.data)
  36. j.type = j.type.replace('olivetin.api.v1.', '')
  37. const e = new Event(j.type)
  38. e.payload = j.payload
  39. switch (j.type) {
  40. case 'EventOutputChunk':
  41. case 'EventConfigChanged':
  42. case 'EventExecutionFinished':
  43. case 'EventExecutionStarted':
  44. case 'EventEntityChanged':
  45. window.dispatchEvent(e)
  46. break
  47. default:
  48. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + j.type, true)
  49. }
  50. }
  51. function websocketOnError (err) {
  52. window.websocketAvailable = false
  53. window.refreshLoop()
  54. console.log('Websocket error is: ', err)
  55. window.showBigError('websocket-connection', 'connecting to the websocket', 'This often means the connection was closed, sometimes this can happen due to reverse proxy timeouts. Sometimes your web browser can provide helpful diagnostic information in the web developer console. The reason given by your browser is:' + err, true)
  56. refreshServerConnectionLabel()
  57. }
  58. function websocketOnClose () {
  59. window.websocketAvailable = false
  60. refreshServerConnectionLabel()
  61. }