summaryrefslogtreecommitdiff
path: root/src/2b2w/webserver.ts
blob: fd6271829a71627e955df1667c48ced1bece8c57 (plain) (blame)
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
//this module exposes functions and variables to control the HTTP server.
import http from 'http'; //to serve the pages
import fs from 'fs'; //to read the webpages from disk

module.exports = {
    createServer: (port) => {
        http.createServer((req, res) => {
            if (req.url === "./") { // main wage of web app
                res.writeHead(200, {'Content-type': 'text/html'});
                res.write(fs.readFileSync('index.html'));
                res.end();
            } else if (req.url === "./index.css") {
                res.writeHead(200, {'Content-type': 'text/css'});
                res.write(fs.readFileSync('index.css'));
                res.end();
            } else if (module.exports.password == "" || req.headers.xpassword == module.exports.password) { // before anything, test if password is valid
                if (req.url === "/update") { // API endpoint to get position, ETA, and status in JSON format      
                    res.writeHead(200, {'Content-type': 'text/json'});
                    res.write("{\"username\": \""+ module.exports.username +"\",\"place\": \""+ module.exports.queuePlace +"\",\"ETA\": \""+ module.exports.ETA +"\", \"inQueue\": " + module.exports.isInQueue+", \"restartQueue\":"+ module.exports.restartQueue+"}")
                    res.end();
                } else if (req.url === "/start") { // API endpoint to start queuing
                    res.writeHead(200);
                    res.end();
                    module.exports.onstartcallback();
                } else if (req.url === "/stop") { // API endpoint to stop queuing
                    res.writeHead(200);
                    res.end();
                    module.exports.onstopcallback();
                } else if (req.url === "/togglerestart"){
                    module.exports.restartQueue = !module.exports.restartQueue;
                } else {
                    res.writeHead(404);
                    res.end();
                }
            } else {
                res.writeHead(403);
                res.end();
            }
        }).listen(port);
    },
    onstart: (callback) => { // function to set the action to do when starting
        module.exports.onstartcallback = callback;
    },
    onstop: (callback) => { // same but to stop
        module.exports.onstopcallback = callback;
    },
    queuePlace : "None", // place in queue
    ETA: "None", // ETA
    isInQueue: false, // am i in queue
    onstartcallback: null, // a save of the action to start
    onstopcallback: null, // same but to stop
    restartQueue: false, // when at the end of the queue, restart if no client is connected?
    password: "" // password for webapp
};