-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (82 loc) · 2.53 KB
/
index.js
File metadata and controls
94 lines (82 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const Koa = require('koa');
const logger = require('koa-logger');
const koaBody = require('koa-body');
const koaRespond = require('koa-respond');
const Router = require('koa-router');
const cors = require('@koa/cors');
const sanitize = require('sanitize-filename');
const websockify = require('koa-websocket');
const fs = require('fs').promises;
require('dotenv').config();
const app = websockify(new Koa());
const robotServerID = process.env['ROBOT_SERVER_ID'];
let clients = [];
app.ws.use((ctx, next) =>
{
ctx.websocket.once('message', message =>
{
try
{
const data = JSON.parse(message.toString());
if(data.type === 'register' && !!data.id)
{
console.log(`${data.id} vs ${robotServerID}`);
if(data.id === robotServerID)
{
ctx.websocket.on('message', message =>
{
const data = JSON.parse(message.toString());
if(data.type === 'highlight')
{
const codeID = data.codeID;
for(const client of clients)
{
if(client.id === codeID)
{
client.ws.send(JSON.stringify({
type: 'highlight',
statement: data.statement
}));
}
}
}
});
}
else
{
clients.push({id: data.id, ws: ctx.websocket});
}
}
else
{
ctx.websocket.close();
}
}
catch(e)
{
ctx.websocket.close();
}
});
ctx.websocket.on('close', () =>
{
clients = clients.filter(c => c.ws !== ctx.websocket);
});
});
app.use(logger());
app.use(koaBody());
app.use(koaRespond());
app.use(cors());
const router = new Router();
router.post('/:id', async (ctx, next) =>
{
const data = ctx.request.body;
const id = sanitize(ctx.params['id']);
await fs.writeFile(`./code/${id}.js`, data);
ctx.ok();
next();
});
app.use(router.routes());
app.use(router.allowedMethods());
const port = Number(process.env['PORT']) || 5289;
app.listen(port);
console.log(`Started listening on ${port}!`);