Verified Commit 2bea3af0 authored by Maxime FRIESS's avatar Maxime FRIESS 💙
Browse files

[Api] Broadcast received events

parent a0d9bc00
import { createServer } from 'http';
import HardConfig from './config/HardConfig.js';
import Gateway from './Gateway.js';
import Loggers from './utils/Logger.js';
class _API {
......@@ -14,18 +15,55 @@ class _API {
this.__server.listen(HardConfig.getHttpPort(), HardConfig.getHttpIp());
}
request(req, res) {
__log(req, code) {
const ip = HardConfig.getHttpProxy() ? req.headers['x-forwarded-for'].split(',')[0].trim() : req.socket.remoteAddress;
this.__logger.info(`Request from ${ip}: ${req.method} ${req.url} (${code})`);
}
handle_event(name, data) {
return Gateway.broadcastEvent(name, data);
}
request(req, res) {
if (this.__auth(req)) {
this.__logger.info(`Request from ${ip}: ${req.method} ${req.url}`);
res.writeHead(200);
res.end("Hello auth!\n");
let result = req.url.match("^/event/([a-z\.]+)$");
if (req.method == "POST" && result) {
let body = "";
req.setEncoding('utf8');
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
try {
let data = JSON.parse(body);
if (this.handle_event(result[1], data)) {
res.writeHead(200);
res.end();
this.__log(req, 200);
} else {
res.writeHead(400);
res.end();
this.__log(req, 400);
}
} catch (e) {
res.writeHead(400);
res.end();
this.__log(req, 400);
}
})
} else {
res.writeHead(404);
res.end();
this.__log(req, 404);
}
} else {
res.writeHead(401, {
"WWW-Authenticate": "Bearer"
});
res.end();
this.__log(req, 401);
}
}
......
......@@ -39,10 +39,14 @@ class Client {
return this.__id;
}
message(data) {
send(data) {
this.__ws.send(data);
}
message(data) {
}
heartbeat() {
this.__alive = true;
}
......
......@@ -51,9 +51,24 @@ class _Gateway {
}
}
broadcast(string) {
for (let k of Object.keys(this.__clients)) {
this.__clients[k].send(string);
}
}
removeClient(client) {
delete this.__clients[client.getId()];
}
broadcastEvent(name, data) {
const event_string = JSON.stringify({p: name, d: data}) + "\n";
this.broadcast(event_string);
this.__logger.info(`Broadcasted event ${name}: ${JSON.stringify(data)}`);
return true;
}
}
const Gateway = new _Gateway();
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment