1
0
mirror of synced 2024-11-14 14:17:35 +01:00
shadowtenpo/webmgr.js
2022-02-27 14:56:44 -08:00

95 lines
1.9 KiB
JavaScript

const http = require('http');
const url = require('url');
const fs = require('fs');
const ws = require('ws');
const mimetypes = require('./mime');
function WebManager(port) {
const server = http.createServer();
const wss = new ws.WebSocketServer({ noServer: true });
this.clients = [];
this.clientcnt = 0;
wss.on('connection', (ws, request) => {
var clientid = this.clientcnt;
this.clientcnt++;
this.clients.push(ws);
ws.on('message', msg => {
console.log(msg.toString('utf-8'));
});
ws.on('close', () => {
this.clients[clientid] = false;
});
ws.on('error', () => {
this.clients[clientid] = false;
});
});
server.on('request', (req, rsp) => {
const uri = url.parse(req.url).pathname;
if (uri == '/') {
filename = 'www/index.html';
} else {
filename = 'www' + uri;
}
var ext = filename.match(/\.\w+$/);
var mime = null;
if (ext) {
mime = mimetypes[ext[0]];
}
if (!mime) {
mime = 'application/octet-stream';
}
try {
if (!fs.existsSync(filename)) {
rsp.writeHead(404);
rsp.end('Not Found');
return;
}
var stat = fs.statSync(filename);
if (!stat) {
rsp.writeHead(403);
rsp.end('Forbidden');
return;
}
rsp.writeHead(200, {
'Content-Length': stat.size,
'Content-Type': mime,
});
rsp.end(fs.readFileSync(filename));
} catch (e) {
console.error(e);
rsp.writeHead(500);
rsp.end(e.toString());
}
});
server.on('upgrade', (request, socket, head) => {
const uri = url.parse(request.url).pathname;
if (uri == '/api') {
wss.handleUpgrade(request, socket, head, ws => {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
server.listen(port);
}
WebManager.prototype.log = function(msg) {
this.clients.forEach(ws => {
if (!ws) return;
ws.send(JSON.stringify({
t: 'log',
m: msg
}));
});
};
module.exports = WebManager;