forked from pverkade/ariana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
226 lines (188 loc) · 6.17 KB
/
server.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
* Project Ariana
* server.js
*
* This file contains all code to run the node server to host Ariana.
*
*/
var connect = require('connect');
var serveStatic = require('serve-static');
var fs = require('fs');
var request = require('request');
var qs = require('querystring');
var gm = require('gm').subClass({ imageMagick: true });
// Init
var app = connect();
var server;
var indexPage;
var host = 'localhost';
var port = 3000;
// Handle POSIX signals
process.on('SIGINT', function() {
process.stdout.write("Stopping webserver. Bye\n");
server.close();
process.exit(0);
});
process.on('SIGHUP', function() {
fs.readFile(path + '/index.html', function(err, contents) {
if (err) throw err;
indexPage = contents;
process.stdout.write("Reloaded index file\n");
})
});
// Serve static file
app.use(serveStatic('build', {index: false}));
function readIndex(next) {
// Read index.html and listen
fs.readFile('build/index.html', "utf-8", next);
}
function startServer(host, port) {
server = app.listen(port, host, function() {
process.stdout.write("Listening on " + (host ? 'http://' + host + ':' : 'port ') + port + "\n");
});
}
/* This saves the inputbuffer into another image buffer. Format specifies the
* format of the output buffer, and can be either jpeg or png. Additionaly, the image
* will be flipped vertically.
*
* handler has as input: error, outputbuffer.
*
* quality can be optionally set for jpeg format.
*/
function saveImageAsBuffer(inputBuffer, format, handler, quality) {
if (format !== "jpeg" && format !== "png") {
handler("Bad format", null);
return;
}
var newImage = gm(inputBuffer).flip();
if (format === 'jpeg') {
newImage = newImage
.out("-background")
.out("white")
.flatten()
.compress('JPEG')
.quality(quality)
}
newImage.toBuffer(format, handler);
}
function testSaveImageAsBuffer(filename, format, quality) {
var buf = fs.readFileSync(filename);
saveImageAsBuffer(buf, format, function (err, buffer) {
if (err) {
console.log("error:", err);
return;
}
fs.writeFileSync("output" + "." + format, buffer);
}, quality);
}
function plainTextResponse(response, statuscode, text) {
response.writeHead(statuscode, {
"Content-Type": "text/plain; charset=utf-8"
});
response.end(text);
}
/* This function resends an image received from a post back, if
* a correct post was made to /save-image.
*
* The image size limit is roughly 100mb.
*
* Returns true if a response was send.
*/
function saveImageRouter(req, res) {
if (req.method == "POST" && req.url == "/save-image") {
var body = '';
req.on('data', function (data) {
body += data;
// kill connection if too much data (100mb).
if (body.length > 100 * 1e6) {
console.log("message is to long:", body.length);
req.connection.destroy();
}
});
req.on('end', function () {
var post = qs.parse(body);
if (!post['image-data'] || !post['filename'] || !post['format']) {
plainTextResponse(res, 400, "Image-data, filename or format is missing from request.");
return;
}
var data = post['image-data'],
filename = post['filename'],
format = post['format'],
quality = post['quality'];
if (format !== 'jpeg' && format !== 'png') {
plainTextResponse(res, 400, 'Bad image format.');
return;
}
else if (format === 'jpeg' && (isNaN(quality) || !(0 <= quality && quality <= 100))) {
plainTextResponse(res, 400, 'Quality not specified correctly.');
return;
}
var inputBuffer = new Buffer(data, 'base64');
saveImageAsBuffer(inputBuffer, format, function(err, buffer) {
if (err) {
console.log("error", err);
plainTextResponse(res, 500, "Internal Server Error");
return;
}
res.writeHead(200, {
"Content-Type": "Content-type: image/" + format ,
'Content-Disposition': 'attachment; filename="' + filename + "." + format+ '"'
});
res.end(buffer.toString("binary"), "binary");
}, quality);
});
return true;
}
return false;
}
/*
* Starts the servers and index.html is only loaded once at startup.
*/
function staticServe(host, port) {
readIndex(function(err, content) {
if (err) throw err;
app.use(function(req, res) {
if (saveImageRouter(req, res)) {
return;
}
if (req.url != "/" && req.url != "/index.html" && req.url != "/ariana" && req.url != "/drawtest") {
plainTextResponse(res, 404, "File not Found.");
return;
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(content);
});
startServer(host, port);
});
}
/*
* Starts the server. Every request for index.html receives an updated version.
*/
function dynamicServe(host, port) {
app.use(function(req, res) {
if (saveImageRouter(req, res)) {
return;
}
if (req.url != "/" && req.url != "/index.html" && req.url != "/ariana") {
plainTextResponse(res, 404, "File not found.");
return;
}
readIndex(function(err, content) {
if (err) {
plainTextResponse(res, 500, "Index not found.");
return;
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(content);
});
});
startServer(host, port);
}
if (process.argv.indexOf("--production") !== -1) {
console.log("Starting server in production mode...");
staticServe("0.0.0.0", 80);
}
else {
console.log("Starting server in development mode...");
dynamicServe(host, port);
}