Move WebSocket message parsing to another file

Allows reusing the same code for the client app
This commit is contained in:
Rafostar
2020-12-15 18:19:24 +01:00
parent 4c6e5607fb
commit 8564cc9617
2 changed files with 34 additions and 17 deletions

30
clapper_src/webHelpers.js Normal file
View File

@@ -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];
}

View File

@@ -1,6 +1,6 @@
const { Soup, GObject } = imports.gi; const { Soup, GObject } = imports.gi;
const ByteArray = imports.byteArray;
const Debug = imports.clapper_src.debug; const Debug = imports.clapper_src.debug;
const WebHelpers = imports.clapper_src.webHelpers;
let { debug } = Debug; let { debug } = Debug;
@@ -118,23 +118,10 @@ class ClapperWebServer extends Soup.Server
_onWsMessage(connection, dataType, bytes) _onWsMessage(connection, dataType, bytes)
{ {
if(dataType !== Soup.WebsocketDataType.TEXT) const [success, parsedMsg] = WebHelpers.parseData(dataType, bytes);
return debug('ignoring non-text WebSocket message');
const msg = bytes.get_data(); if(success)
let parsedMsg = null; this.passMsgData(parsedMsg.action, parsedMsg.value);
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);
} }
_onWsClosed(connection) _onWsClosed(connection)