aboutsummaryrefslogtreecommitdiff
path: root/server.js
blob: 9d641eba1c4156fcf221174a0c17c2d322e5ff34 (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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
const http	= require("http");
const fs	= require("fs");
const url	= require("url");

mainPage = "./index.html";
allowedPaths = [mainPage, "./index.css"];
path404 = "./404/index.html";

shifts = [
	//1:
	"Ruokailuvuoro 1",
	//2:
	"Ruokailuvuoro 2",
	//3:
	"Ruokailuvuoro 3"
];


http.createServer((req, res) =>
{
	let q = url.parse(req.url, true); //true?
	let path = "." + q.pathname;
	if (path == "./")
		path = "./index.html";

	console.log(path);

	if (!allowedPaths.includes(path))
		path = path404;

	switch(path)
	{
		case mainPage:
			buildMain(q.query, path).then(
				(data) =>
				{
					res.write(data);
					res.end();
				}
			);
			break;
		case path404:
			build404(path, q.pathname).then(
				data =>
				{
					res.write(data);
					res.end();
				}
			);
			break;
		default:
			buildDefault(path).then(
				data =>
				{
					res.write(data);
					res.end();
				}
			);
	}
}).listen(8080)

function openFile(path)
{
	return new Promise((resolve, reject) =>
	{
		fs.readFile(path, (err, data) =>
		{
			if (err)
				reject(err);
			resolve(data);
			return data;
		})
	});
}

function buildMain(query, path)
{
	return new Promise((resolve, reject) =>
	{
		openFile(path).then(
			data =>
			{
				data_string = data.toString("utf-8");
				if (query.index === undefined)
					resolve(data_string.replace("\\(result\\)", ""));
				resolve(data_string.replace("\\(result\\)", shifts[parseshift(query) - 1]));
			}
		);
	});
}


function build404(path, attemptpath)
{
	return new Promise((resolve, reject) =>
	{
		openFile(path).then(
			data =>
			{
				data_string = data.toString("utf-8");
				resolve(data_string.replace("\\(path\\)", attemptpath));
			}
		);
	});
}

function buildDefault(path)
{
	return new Promise((resolve, reject) =>
	{
		openFile(path).then(
			data =>
			{
				resolve(data.toString("utf-8"));
			}
		);
	});
}

function parseshift(index)
{
	//get index type
	is_teacher = isNaN(parseInt(index[index.length - 1]));
	is_course = !is_teacher;
	//read shiftfile
	openFile("shifts.txt").then(
		data =>  {}
	);
	//iterate over lines, search for day
	//iterate shifts for course / teacher
	//return the shift number
	return 1;
}

function getCharAmount(s, c)
{
	let n = 0;
	for (let c_i = 0; c_i < s.length; c_i++)
	{
		n += +(s[c_i] === c);
	}
	return n;
}