/
server.js
223 lines (203 loc) · 7.26 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
var http = require('http')
, util = require('util')
, fs = require('fs')
, url = require('url')
, cp = require('child_process')
, face = require('./face')
, servant = require('./deps/servant/lib/servant')
, choreo = require('./deps/choreographer/choreographer')
, redis = require('./deps/redis-node-client/lib/redis-client')
, _ = require('./deps/underscore-1.1.3')._
var HOST = 'mugshotapp.com';
var PORT = parseInt(process.argv[2])||8080;
var URL = 'http://' + HOST + ':' + PORT;
var DBNO = 5;
var MAX_SIZE = 5*1024*1024; // allow 5mb
function getOut(code, error, resp) {
if( error && !resp ) {
resp = error;
error = undefined;
}
resp.writeHead(code, { 'Content-Type': 'application/json' });
resp.end(JSON.stringify({
status: 'error',
message: error || 'Unknown error'
}));
}
function reply(faces, id, path, resp) {
if( typeof(faces) == 'string' ) {
getOut(415, faces == 'No Error' ? 'Unknown error' : faces, resp);
return;
}
var obj = {
status: 'success',
faces: faces,
id: id,
image_url: URL + '/image/'+require('path').basename(path),
share_url: URL + '/view/'+id
};
resp.writeHead(200, { 'Content-Type': 'application/json' });
resp.end(JSON.stringify(obj));
}
function addToRedis(path, callback) {
var client = redis.createClient();
client.on('connected', function() {
client.select(DBNO);
client.incr('mugshot:globalId', function(err, id) {
if( !err ) {
client.set('mugshot:image:' + id, path, function(err) {
callback(err, id);
});
}
else {
callback(err, null);
}
});
});
}
function withFile(callback) {
// TODO gen random filename
var filename = '/tmp/data/face.'+process.pid+'.'+parseInt(Math.random()*10000);
var stream = fs.createWriteStream(filename);
callback(stream);
}
function handleUrl(request, response) {
withFile(function(stream) {
var remote = "";
request.on('data', function(data) {
remote += data.toString();
});
request.on('end', function() {
var size = 0;
var error = false;
var parts = url.parse(remote);
var client = http.createClient(parseInt(parts.port)||80, parts.hostname);
client.on('error', function() {
getOut(500, response);
});
client.request('GET', parts.pathname || '/', {
'host' : parts.hostname
, 'user-agent' : 'Mugshot FaceDetector'
})
.on('response', function(remoteresponse) {
if( remoteresponse.statusCode != 200 ) {
getOut(500, "Remote server failed with status code " + remoteresponse.statusCode, response);
return;
}
remoteresponse.on('data', function(data) {
if( size > MAX_SIZE ) {
error = true;
remoteresponse.emit('error', 'File size exceeded');
remoteresponse.destroy();
return;
}
stream.write(data);
size += data.length;
})
.on('end', function() {
// the 'close' callback gets
// added only if error is false
// so this is ok
stream.end();
if( error )
return;
stream.on('close', function() {
addToRedis(stream.path, function(err, id) {
// we aren't concerned about the error
// because we can always reply with
// the list of faces right now even
// if we can't cache it
reply(face.faces(stream.path), id, stream.path, response);
});
});
})
.on('error', function() {
fs.unlink(stream.path);
if( error )
getOut(413, 'Maximum size allowed is '+MAX_SIZE+' bytes', response);
else
getOut(500, response);
});;
}).on('error', function() {
getOut(500, response);
}).end();
});
});
};
function handleFile(request, response) {
withFile(function(stream) {
var size = 0;
var error = false;
request.on('data', function(data) {
if( size > MAX_SIZE ) {
error = true;
request.emit('error', 'File size exceeded');
return;
}
stream.write(data);
size += data.length;
});
request.on('error', function() {
if( error ) {
getOut(413, 'Maximum size allowed is '+MAX_SIZE+' bytes', response);
fs.unlink(stream.path);
}
else
console.log("Request error ", arguments);
});
request.on('end', function() {
stream.end();
if( error )
return;
stream.on('close', function() {
addToRedis(stream.path, function(err, id) {
// we aren't concerned about the error
// because we can always reply with
// the list of faces right now even
// if we can't cache it
reply(face.faces(stream.path), id, stream.path, response);
});
});
});
});
};
var pageTemplate = _.template(fs.readFileSync('view.html', 'utf8'));
function viewInBrowser(request, response, id) {
var r = redis.createClient();
r.on('connected', function() {
r.select(DBNO);
r.get('mugshot:image:' + id, function(err, path) {
if( err || !path ) {
response.writeHead(404, { "content-type": "text/html" });
response.end("No such image.");
}
else {
response.writeHead(200, { "content-type": "text/html" });
response.write(pageTemplate({ image_url: URL + '/image/' + require('path').basename(path.toString()), faces: JSON.stringify(face.faces(path.toString())) }));
response.end();
}
});
});
}
var images = new servant.Servant('/tmp/data');
var static = new servant.Servant('.');
var router = choreo.router();
router.get('/view/*', viewInBrowser);
router.post('/file', handleFile);
router.post('/url', handleUrl);
router.get('/image/*', function(request, response) {
request.url = request.url.replace(/^\/image/, '');
images.serve(request, response);
});
router.get('/*', function(request, response) {
static.serve(request, response);
});
router.notFound(function(request, response) {
static.serve(request, response, function(err, obj) {
if(err) {
response.writeHead(404);
response.end("Page Not Found.");
}
});
});
http.createServer(router).listen(PORT);