This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
189 lines (165 loc) · 5.22 KB
/
index.js
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const http = require('http');
const getRawBody = require('raw-body');
const localtunnel = require('localtunnel');
const url = require('url');
const { PORT, TOKEN, SUBDOMAIN } = require('./config');
const { Latissima } = require('./latissima');
const server = http.createServer(handleRequests);
let coffeeMachine;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
localtunnel(PORT, {subdomain: SUBDOMAIN}, function(err, tunnel) {
if (err) {
console.error(err);
process.exit(1);
}
// the assigned public url for your tunnel
// i.e. https://abcdefgjhij.localtunnel.me
console.log('Tunnel url:' + tunnel.url);
coffeeMachine = new Latissima();
coffeeMachine.on('ready', () => {
console.log(`Coffee machine initialized`);
});
});
});
function handleRequests(req, res) {
if (coffeeMachine.isTeapot) {
res.statusCode = 418;
res.statusMessage = "I'm a teapot";
res.write("I'm a teapot");
return res.end();
}
if (req.method === 'GET') {
console.log('GET');
res.setHeader('Safe', 'yes');
res.setHeader('Content-Type', 'message/coffeepot');
if (req.url.indexOf('/pot-0/') === 0) {
console.log('TYPE INFO');
// TODO: Implement status of coffee production
let data = [];
res.write(data.join('\n'));
} else if (req.url.indexOf('/pot-0') === 0) {
let data = ['isOn='+coffeeMachine.isOn]
res.write(data.join('\n'));
} else {
res.statusCode = 404;
}
return res.end();
}
if (req.method === 'POST' || req.method === 'BREW') {
// TODO once we have a proper status we should set this
res.setHeader('Safe', 'no');
if (!hasCorrectContentType(req)) {
res.statusCode = 415;
res.statusMessage = 'Unsupported Media Type';
res.end();
return;
}
if (!isAuthenticated(req)) {
res.statusCode = 401;
res.statusMessage = 'Unauthorized';
res.end();
return;
}
let additions = getAdditionsRequested(req)
let invalidAdditions = additions.filter(a => !isValidAddition(a));
if (invalidAdditions.length > 0) {
res.statusCode = 406;
res.statusMessage = 'Not Acceptable';
res.write(coffeeMachine.additions.join('; '));
return res.end();
}
additions = additions.filter(isValidAddition);
getRawBody(req, { encoding: 'utf-8' }, (err, body) => {
let command = parseCoffeeMessageBody(body);
if (err || !command) {
res.statusCode = 400;
res.statusMessage = 'Bad Request';
return res.end();
}
if (req.url.indexOf('/pot-0/') !== 0) {
if (req.url.indexOf('/pot-0' === 0)) {
if ((command === 'start' && !coffeeMachine.isOn) || (command === 'stop' && coffeeMachine.isOn)) {
coffeeMachine.pressPower().then(() => {
res.statusCode = 200;
res.write(command + 'ed');
return res.end();
});
} else {
res.statusCode = 400;
res.statusMessage = 'Bad Request';
return res.end();
}
} else {
res.statusCode = 404;
res.statusMessage = 'Not Found';
return res.end();
}
} else {
const typeEndpoint = url.parse(req.url).pathname.replace('/pot-0/', '');
// TODO: No difference at the moment between start and stop
// TODO: Need to handle additions
console.log('Pressing', typeEndpoint);
if (Latissima.Types[typeEndpoint]) {
console.log('Pressing');
coffeeMachine.press(Latissima.Types[typeEndpoint])
.then(() => {
console.log('Pressed');
res.statusCode = 200;
res.write(command+'ed');
return res.end();
});
} else {
res.statusCode = 404;
res.statusMessage = 'Not Found';
return res.end();
}
}
})
}
}
function isAuthenticated(req) {
const query = url.parse(req.url, true).query;
console.log(query);
if (query.token && query.token === TOKEN) {
return true;
}
return (req.headers['coffee-authorization'] || '').replace('Bearer ', '') === TOKEN;
}
function hasCorrectContentType(req) {
return req.headers['content-type'] === 'application/coffee-pot-command'
|| req.headers['content-type'] === 'text/plain';
}
function isValidAddition(addition) {
return coffeeMachine.additions.indexOf(addition) !== -1;
}
function getAdditionsRequested(req) {
let header = req.headers['accept-additions'];
let milkType = ['Cream', 'Half-and-half', 'Whole-milk', 'Part-Skim', 'Skim', 'Non-Dairy'];
let syrupType = ['Vanilla', 'Almond', 'Raspberry', 'Chocolate'];
let alcoholType = ['Whisky', 'Rum', 'Kahlua', 'Aquavit'];
let spiceType = []; /** NO LIST DEFINIED IN RFC */
let validTypes = [
'*',
...milkType,
...syrupType,
...alcoholType,
...spiceType
];
if (!header) {
return [];
}
return header.split(';')
.map(type => type.trim())
.filter(type => validTypes.indexOf(type) !== -1);
}
function parseCoffeeMessageBody(body) {
body = body
.toLowerCase()
.trim()
.replace(/coffee-message-body\s*=\s*/, '');
if (body === 'start' || body === 'stop') {
return body;
}
return null;
}