summaryrefslogtreecommitdiff
path: root/server/hornchat.profile.js
blob: 9b30cf16ff4eeefc7acbef6faacc3c2264b4a1b4 (plain)
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
require('./hornchat.serverlet.sync')

const WebSocket = require('ws');
const uuid = require('uuid-v4');
const _auth = require('./hornchat.serverlet.authentication');
const _process = require('./hornchat.profile.process');

const informTrackedUsers = require('./hornchat.profile.tracking');
setInterval(() => {
    informTrackedUsers();
}, 50)

const server = new WebSocket.Server({
    port: 8303
});

global.data = {};

server.on('connection', function (socket, req) {
    socket.ip = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0].trim() : req.socket.remoteAddress;

    socket.authenticated = null;
    socket.id = uuid();
    console.log("New connection: " + socket.id);
    data[socket.id] = {};
    data[socket.id]["socket"] = socket;

    require('./hornchat.serverlet.timeout')(socket);

    socket.on('close', () => {
        if (socket.id) {
            delete data[socket.id];
        }
    })

    socket.on('message', function (msg) {
        if (socket.authenticated === null) {
            _auth(socket, msg);
        } else {
            let d;
            try {
                d = JSON.parse(msg);
            } catch (e) {
                socket.send(JSON.stringify({error:"INVALID_DATA", fatal: false}));
                console.log("[" + socket.id + "] Received invalid data");
                return;
            }

            if (d.username) {
                _process(socket, d);
            } else {
                socket.send(JSON.stringify({error:"MISSING_OPERAND", fatal: false}));
                console.log("[" + socket.id + "] Missing 'username' value");
            }
        }
    });
});

console.log("Listening on port 8303");