diff --git a/src/web/app/common/scripts/stream.js b/src/web/app/common/scripts/stream.js new file mode 100644 index 0000000000..b31e570444 --- /dev/null +++ b/src/web/app/common/scripts/stream.js @@ -0,0 +1,39 @@ +const ReconnectingWebSocket = require('reconnecting-websocket'); +const riot = require('riot'); + +module.exports = me => { + let state = 'initializing'; + const stateEv = riot.observable(); + const event = riot.observable(); + const host = CONFIG.api.url.replace('http', 'ws'); + const socket = new ReconnectingWebSocket(`${host}?i=${me.token}`); + + socket.onopen = () => { + state = 'connected'; + stateEv.trigger('connected'); + }; + + socket.onclose = () => { + state = 'reconnecting'; + stateEv.trigger('closed'); + }; + + socket.onmessage = message => { + try { + const message = JSON.parse(message.data); + if (message.type) { + event.trigger(message.type, message.body); + } + } catch (e) { + // noop + } + }; + + event.on('i_updated', me.update); + + return { + stateEv: stateEv, + getState: () => state, + event: event + }; +}; diff --git a/src/web/app/common/scripts/stream.ls b/src/web/app/common/scripts/stream.ls deleted file mode 100644 index c2c061603e..0000000000 --- a/src/web/app/common/scripts/stream.ls +++ /dev/null @@ -1,39 +0,0 @@ -# Stream -#================================ - -ReconnectingWebSocket = require \reconnecting-websocket -riot = require \riot - -module.exports = (me) ~> - state = \initializing - state-ev = riot.observable! - event = riot.observable! - - host = CONFIG.api.url.replace \http \ws - socket = new ReconnectingWebSocket "#{host}?i=#{me.token}" - - socket.onopen = ~> - state := \connected - state-ev.trigger \connected - - socket.onclose = ~> - state := \reconnecting - state-ev.trigger \closed - - socket.onmessage = (message) ~> - try - message = JSON.parse message.data - if message.type? - event.trigger message.type, message.body - catch - # ignore - - get-state = ~> state - - event.on \i_updated me.update - - { - state-ev - get-state - event - } diff --git a/src/web/app/desktop/scripts/stream.ls b/src/web/app/desktop/scripts/stream.ls index f84d6097a7..88dac16cb6 100644 --- a/src/web/app/desktop/scripts/stream.ls +++ b/src/web/app/desktop/scripts/stream.ls @@ -1,8 +1,8 @@ # Stream #================================ -stream = require '../../common/scripts/stream.ls' -get-post-summary = require '../../common/scripts/get-post-summary.ls' +stream = require '../../common/scripts/stream' +get-post-summary = require '../../common/scripts/get-post-summary' riot = require \riot module.exports = (me) ~> diff --git a/src/web/app/mobile/scripts/stream.ls b/src/web/app/mobile/scripts/stream.ls index b7810b49ae..28418d7788 100644 --- a/src/web/app/mobile/scripts/stream.ls +++ b/src/web/app/mobile/scripts/stream.ls @@ -1,7 +1,7 @@ # Stream #================================ -stream = require '../../common/scripts/stream.ls' +stream = require '../../common/scripts/stream' riot = require \riot module.exports = (me) ~>