diff --git a/Bezerk.js b/Bezerk.js index 58b25e9..aef0525 100644 --- a/Bezerk.js +++ b/Bezerk.js @@ -20,7 +20,7 @@ BezerkWS.on('connection', (socket) => { function process (socket, message) { Logger('Attempting to process a message.') - var msg + let msg try { JSON.parse(message) } catch (e) { @@ -44,7 +44,9 @@ function process (socket, message) { Logger('Closing connection, invalid sharding info') return } // We're assuming only wildbeast is going to connect to bezerk as a shard, so we are not going to check for valid data + Logger('Accepted shard.') socket.shardInfo = msg.c + socket.type = 'shard' shards.push(socket) socket.send(JSON.stringify({ op: 'OK' @@ -55,12 +57,60 @@ function process (socket, message) { if (!msg.c) { socket.close() Logger('Closing socket, no subscriptions.') + return + } + if (!Array.isArray(msg.c)) { + socket.close() + Logger('Closing socket, invalid subscriptions.') } else { + Logger('Accepted listener') socket.subscriptions = msg.c + socket.type = 'listener' receivers.push(socket) socket.send(JSON.stringify({ op: 'OK' })) } + } else { + // This is where it's going to get fun. + if (receivers.indexOf(socket) === -1 && shards.indexOf(socket) === -1) { + socket.close() + Logger('Socket tried sending events without being identified first.') + return + } + if (socket.type === 'listener') { + if (msg.shard) { + Logger('Listener event defined a shard, trying to find it and send the message.') + for (let shard of shards) { + if (shard.shardInfo[0] === msg.shard) { + Logger('Shard found, sending payload.') + shard.send(msg) + } + } + } else { + Logger('Listener event did not define a shard, falling back to sending to all shards.') + for (let shard of shards) { + shard.send(msg) + } + } + } else { + if (!msg.op) { + socket.close() + Logger('Closing shard connection, no event passed.') + return + } + if (!msg.c) { + socket.close() + Logger('Closing shard connection, no data.') + } else { + Logger('Request accepted, attempting to send data to subscribed listeners.') + for (let listener of receivers) { + if (listener.indexOf(msg.c) > -1) { + Logger('Sending data.') + listener.send(msg) + } + } + } + } } } diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..8044db2 --- /dev/null +++ b/config.example.json @@ -0,0 +1,3 @@ +{ + "port": 1337 +} \ No newline at end of file diff --git a/package.json b/package.json index c5170b1..a7c60d0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "bezerk", "version": "1.0.0", - "description": "WildBeast websocket mmanager", + "description": "WildBeast websocket manager", "main": "Bezerk.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1"