From 8564cc96179c7915b02bc578cdd6a3c2a11e8eb5 Mon Sep 17 00:00:00 2001 From: Rafostar <40623528+Rafostar@users.noreply.github.com> Date: Tue, 15 Dec 2020 18:19:24 +0100 Subject: [PATCH] Move WebSocket message parsing to another file Allows reusing the same code for the client app --- clapper_src/webHelpers.js | 30 ++++++++++++++++++++++++++++++ clapper_src/webserver.js | 21 ++++----------------- 2 files changed, 34 insertions(+), 17 deletions(-) create mode 100644 clapper_src/webHelpers.js diff --git a/clapper_src/webHelpers.js b/clapper_src/webHelpers.js new file mode 100644 index 00000000..571e6726 --- /dev/null +++ b/clapper_src/webHelpers.js @@ -0,0 +1,30 @@ +const { Soup } = imports.gi; +const ByteArray = imports.byteArray; +const Debug = imports.clapper_src.debug; + +let { debug } = Debug; + +function parseData(dataType, bytes) +{ + if(dataType !== Soup.WebsocketDataType.TEXT) { + debug('ignoring non-text WebSocket message'); + return [false]; + } + + let parsedMsg = null; + const msg = bytes.get_data(); + + try { + parsedMsg = JSON.parse(ByteArray.toString(msg)); + } + catch(err) { + debug(err); + } + + if(!parsedMsg || !parsedMsg.action) { + debug('no "action" in parsed WebSocket message'); + return [false]; + } + + return [true, parsedMsg]; +} diff --git a/clapper_src/webserver.js b/clapper_src/webserver.js index 0824f344..72895564 100644 --- a/clapper_src/webserver.js +++ b/clapper_src/webserver.js @@ -1,6 +1,6 @@ const { Soup, GObject } = imports.gi; -const ByteArray = imports.byteArray; const Debug = imports.clapper_src.debug; +const WebHelpers = imports.clapper_src.webHelpers; let { debug } = Debug; @@ -118,23 +118,10 @@ class ClapperWebServer extends Soup.Server _onWsMessage(connection, dataType, bytes) { - if(dataType !== Soup.WebsocketDataType.TEXT) - return debug('ignoring non-text WebSocket message'); + const [success, parsedMsg] = WebHelpers.parseData(dataType, bytes); - const msg = bytes.get_data(); - let parsedMsg = null; - - try { - parsedMsg = JSON.parse(ByteArray.toString(msg)); - } - catch(err) { - debug(err); - } - - if(!parsedMsg || !parsedMsg.action) - return debug('no "action" in parsed WebSocket message'); - - this.passMsgData(parsedMsg.action, parsedMsg.value || 0); + if(success) + this.passMsgData(parsedMsg.action, parsedMsg.value); } _onWsClosed(connection)