diff options
author | Maximilian Hils <git@maximilianhils.com> | 2016-10-31 05:30:32 -0700 |
---|---|---|
committer | Maximilian Hils <git@maximilianhils.com> | 2016-11-08 17:54:27 +0100 |
commit | 85476d9915f23fc45e64b5242e804623f50cd20a (patch) | |
tree | 9fdca1d74c1bcf3f9dafc26cd4d2786c3ae8b81e /web/src/js/backends | |
parent | 62ca89649237cb0aff63b1fd3d7729b42134bdd1 (diff) | |
download | mitmproxy-85476d9915f23fc45e64b5242e804623f50cd20a.tar.gz mitmproxy-85476d9915f23fc45e64b5242e804623f50cd20a.tar.bz2 mitmproxy-85476d9915f23fc45e64b5242e804623f50cd20a.zip |
clean up mitmweb
Diffstat (limited to 'web/src/js/backends')
-rw-r--r-- | web/src/js/backends/websocket.js | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/web/src/js/backends/websocket.js b/web/src/js/backends/websocket.js new file mode 100644 index 00000000..aa890bb7 --- /dev/null +++ b/web/src/js/backends/websocket.js @@ -0,0 +1,68 @@ +import { fetchApi } from "../utils" + +export const CMD_RESET = 'reset' + +export default class WebsocketBackend { + constructor(store) { + this.activeFetches = {} + this.store = store + this.connect() + } + + connect() { + this.socket = new WebSocket(location.origin.replace('http', 'ws') + '/updates') + this.socket.addEventListener('open', () => this.onOpen()) + this.socket.addEventListener('close', () => this.onClose()) + this.socket.addEventListener('message', msg => this.onMessage(JSON.parse(msg.data))) + this.socket.addEventListener('error', error => this.onError(error)) + } + + onOpen() { + this.fetchData("settings") + this.fetchData("flows") + this.fetchData("events") + } + + fetchData(resource) { + let queue = [] + this.activeFetches[resource] = queue + fetchApi(`/${resource}`) + .then(res => res.json()) + .then(json => { + // Make sure that we are not superseded yet by the server sending a RESET. + if (this.activeFetches[resource] === queue) + this.receive(resource, json) + }) + } + + onMessage(msg) { + + if (msg.cmd === CMD_RESET) { + return this.fetchData(msg.resource) + } + if (msg.resource in this.activeFetches) { + this.activeFetches[msg.resource].push(msg) + } else { + let type = `${msg.resource}_${msg.cmd}`.toUpperCase() + this.store.dispatch({ type, ...msg }) + } + } + + receive(resource, msg) { + let type = `${resource}_RECEIVE`.toUpperCase() + this.store.dispatch({ type, [resource]: msg }) + let queue = this.activeFetches[resource] + delete this.activeFetches[resource] + queue.forEach(msg => this.onMessage(msg)) + } + + onClose() { + // FIXME + console.error("onClose", arguments) + } + + onError() { + // FIXME + console.error("onError", arguments) + } +} |