-
Notifications
You must be signed in to change notification settings - Fork 2
/
haypeaeye.js
519 lines (431 loc) · 17.3 KB
/
haypeaeye.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
var moment = require("moment");
var path = require('path');
var fs = require('fs');
var haypeaeyeTests = require('./haypeaeye-tester');
var apiDocsPath = path.join(__dirname, '/apidocs');
var DEFAULT_VIDEO_STREAM_CONTENT_TYPE = "video/mp4";
exports.DATE_FORMAT = "YYYY-MM-DD HH:mm"
var apiMethods = {};
exports.AUTH_REQUIRED = "required";
exports.AUTH_OPTIONAL = "optional";
exports.AUTH_NOT_REQUIRED = "notrequired";
exports.APP_TOKEN_ALWAYS_REQUIRED = "always";
exports.APP_TOKEN_NEVER_REQUIRED = "never";
exports.APP_TOKEN_PER_REQUEST_REQUIRED = "perrequest";
exports.String = "String";
exports.Number = "Number";
exports.Boolean = "Boolean";
exports.File = "File";
exports.Enum = "Enum";
exports.Array = "Array";
exports.Date = "Date";
exports.GET = "GET";
exports.POST = "POST";
exports.PUT = "PUT";
exports.DELETE = "DELETE";
exports.DOCS_SUFFIX = ".docs";
exports.DOCS_PATH = "/docs";
exports.DEFAULT_APP_TOKEN_NAME = "apptoken";
var settings = {
appTokenName: exports.DEFAULT_APP_TOKEN_NAME,
appTokenRequired: exports.APP_TOKEN_NEVER_REQUIRED,
authenticatorMethod: null,
documentationUrl: "/api/docs",
apiRoot: "/api",
applicationName: "Your app name",
authAttributes: [
{name: "appToken", description: "Token given to your app", type: exports.String},
{name: "userToken", description: "Unique token for your user", type: exports.String}
],
authInHeaders: false,
wrapWithStatusAndData: true
};
// Load the example request file if it exists
var examples = {};
fs.exists(haypeaeyeTests.TEST_EXAMPLES_FILE, function(exists) {
if (exists) {
fs.readFile(haypeaeyeTests.TEST_EXAMPLES_FILE, 'utf8', function (err, data) {
if (err) {
console.log("Could not load examples file for documentation");
} else {
try {
examples = JSON.parse(data);
console.log("Loaded examples data for API documentation");
} catch(e) {
console.log("Could not load examples data for API documentation");
console.log(e);
}
}
});
}
});
exports.addApiMethod = function(url, method, title, options, params, callback) {
// Process the url, to look for embedded params
var regExpStr = "";
if (url.indexOf(":") >= 0) {
var urlParams = [];
var currentParamName = "";
var foundParam = false;
for (var i = 0; i < url.length; i++) {
if (foundParam) {
if (url.charAt(i) == "/") {
// Add this param to the list
urlParams.push(currentParamName);
regExpStr = regExpStr + "([^\/]*)?/";
currentParamName = "";
foundParam = false;
} else {
currentParamName = currentParamName + url.charAt(i);
}
} else {
if (url.charAt(i) == ':') {
foundParam = true;
} else {
regExpStr = regExpStr + url.charAt(i);
}
}
}
// Do we have a trailing param (i.e. one at the end?)
if (foundParam) {
urlParams.push(currentParamName);
regExpStr = regExpStr + "([^\/]*)?";
}
// Add param number mappings to params
if (urlParams.length > 0) {
if (!params || params.length == 0) {
console.error("No parameters specified in API method that requires them " + url);
}
for (var i = 0; i < urlParams.length; i++) {
// See if we have a match in the user defined param list
var match = false;
for (var x = 0; x < params.length; x++) {
if (params[x].name == urlParams[i]) {
params[x].index = i;
match = true;
break;
}
}
if (!match) {
console.error("You have not specified a definition for the parameter '" + urlParams[i] + "'");
}
}
}
}
// See if we have any files in the params - i.e. does this method need to be multipart
var methodHasFiles = false;
if (params && params.length > 0) {
for (var i = 0; i < params.length; i++) {
if (params[i].type == exports.File) {
methodHasFiles = true;
break;
}
}
}
if (methodHasFiles && method != exports.POST) {
console.error("You have specified a method that takes files but is not POST - " + url);
}
apiMethods[method + "_" + url] = {
url: url,
method: method,
title: title,
params: params,
callback: callback,
options: options,
multipart: methodHasFiles
};
if (regExpStr != "") {
apiMethods[method + "_" + url].regexp = regExpStr;
}
};
exports.getAttributeFromRequest = function(req, attrName) {
return exports.getAttribute(req, attrName, req.method);
}
exports.getAttribute = function(req, attrName, methodType) {
if (req.params && req.params[attrName]) {
return req.params[attrName];
}
if (methodType == exports.GET) {
if (req.query[attrName] != null && req.query[attrName] != undefined) {
return req.query[attrName];
} else {
return null;
}
} else if (methodType == exports.POST || methodType == exports.PUT || methodType == exports.DELETE) {
if (req.body[attrName] != null && req.body[attrName] != undefined) {
return req.body[attrName];
} else if (req.files && req.files[attrName]) {
return req.files[attrName];
} else {
return null;
}
}
}
var getValuesForParams = function(method, req) {
var regExp = new RegExp(method.regexp, "i");
var array = req.path.match(regExp);
for (var i = 0; i < method.params.length; i++) {
var param = method.params[i];
if (param.index != undefined) {
req.params[param.name] = array[param.index + 1];
}
}
}
var callMethod = function(methodToCall, req, res) {
if (methodToCall.regexp) {
getValuesForParams(methodToCall, req);
}
if (methodToCall.params && methodToCall.params.length > 0) {
for (var i = 0; i < methodToCall.params.length; i++) {
var param = methodToCall.params[i];
// Is this param required?
if ((param.required || param.index != undefined) && (!exports.getAttribute(req, param.name, methodToCall.method))) {
// Check this isn't a false boolean
if (!(param.type && param.type == exports.Boolean)) {
res.status(400).send({status: "error", error: "Required attribute not present, '" + param.name + "'", field_errors: [{field: param.name, message: "You must provide a value"}]});
return;
}
}
var rawValue = exports.getAttribute(req, param.name, methodToCall.method);
if (rawValue != null) {
// Begin more detailed validations
if (param.type && param.type == exports.Number) {
if (isNaN(rawValue)) {
res.status(400).send({status: "error", error: "Attribute '" + param.name + "' is not a valid number", field_errors: [{field: param.name, message: "Invalid number"}]});
return;
}
}
// Dates
if (param.type && param.type == exports.Date && rawValue && rawValue != "") {
var dateValue = moment(rawValue, exports.DATE_FORMAT);
if (!dateValue.isValid()) {
res.status(400).send({status: "error", error: "Attribute '" + param.name + "' is not a valid date. Format should be YYYY-MM-DD HH:mm", field_errors: [{field: param.name, message: "Invalid date"}]});
return;
}
}
// Enums
if (param.type && param.type == exports.Enum && param.validValues && param.validValues.length > 0) {
// Check that the value the user entered is a valid value
var validValue = false;
for (var v = 0; v < param.validValues.length; v++) {
if (rawValue == param.validValues[v]) {
validValue = true;
break;
}
}
if (!validValue) {
res.status(400).send({status: "error", error: "Attribute '" + param.name + "' is not a valid value", field_errors: [{field: param.name, message: "Invalid value"}]});
return;
}
}
// Arrays
if (param.type && param.type == exports.Array) {
if (!(rawValue instanceof Array)) {
res.status(400).send({status: "error", error: "Attribute '" + param.name + "' is not a valid array", field_errors: [{field: param.name, message: "Invalid array"}]});
return;
}
}
}
}
}
methodToCall.callback(req, res);
}
exports.handleRequest = function(req, res, next) {
var htmlDocsUrl = settings.documentationUrl + "/html";
if (req.method == exports.GET && req.url.indexOf(htmlDocsUrl) >= 0) {
// HTML docs
if (req.url == htmlDocsUrl) {
res.redirect(settings.documentationUrl + "/html/index.html");
} else {
var strWithoutStartOfUrl = req.url.substr(req.url.indexOf(htmlDocsUrl) + htmlDocsUrl.length);
res.sendFile(apiDocsPath + strWithoutStartOfUrl);
}
} else if (req.method == exports.GET && req.url == settings.documentationUrl + "/settings") {
res.json(settings);
} else if (req.method == exports.GET && req.url == settings.documentationUrl) {
var docsJson = [];
for (var key in apiMethods) {
var methodJson = apiMethods[key];
if (examples && examples[methodJson.method + "_" + methodJson.url]) {
methodJson.examples = examples[methodJson.method + "_" + methodJson.url];
}
docsJson.push(methodJson);
}
res.json(docsJson);
} else {
var url = req.path;
var showDocs = false;
// Check if we're showing the docs
if (url.indexOf(exports.DOCS_SUFFIX) == url.length - exports.DOCS_SUFFIX.length) {
showDocs = true;
url = url.substr(0, url.indexOf(exports.DOCS_SUFFIX));
}
var foundMethod = apiMethods[req.method + "_" + url];
if (!foundMethod) {
// See if we can regexp match it (i.e. there might be params in the url)
for (var key in apiMethods) {
if (apiMethods[key].regexp) {
var regexp = new RegExp(apiMethods[key].regexp, "i");
if (req.method == apiMethods[key].method && regexp.test(url)) {
foundMethod = apiMethods[key];
}
}
}
}
if (foundMethod) {
if (showDocs) {
// We are showing docs for this method/url
res.json(foundMethod);
} else {
// We are actually running the method
if (foundMethod.options && foundMethod.options.auth && (foundMethod.options.auth == exports.AUTH_OPTIONAL || foundMethod.options.auth == exports.AUTH_REQUIRED)) {
settings.authenticatorMethod(req, function(user) {
if (user) {
// We have an authed user
req.authUser = user;
callMethod(foundMethod, req, res);
} else if (foundMethod.options.auth == exports.AUTH_OPTIONAL) {
// Auth optional, so user not needed
callMethod(foundMethod, req, res);
} else {
// Auth required, and auth failed, so send error
res.status(401).send({error: "Invalid login credentials"});
}
});
} else {
callMethod(foundMethod, req, res);
}
}
} else {
next();
}
}
};
var applySetting = function(settingName, newSettings, validValues) {
if (newSettings[settingName]) {
if (validValues && validValues.length > 0) {
// Need to check value is valid
for (var i = 0; i < validValues.length; i++) {
if (validValues[i] == newSettings[settingName]) {
settings[settingName] = newSettings[settingName];
return;
}
}
// Value invalid, don't set
console.error("Invalid value '", newSettings[settingName] ,"' for setting '", settingName, "'. Value not set.");
} else {
// No need to check validity
settings[settingName] = newSettings[settingName];
}
}
}
// Useful for calling if you are uploading files, after you have done whatever you wanted to do with the file
exports.removeTempFiles = function(req) {
if (req.files) {
for (var fileFieldName in req.files) {
fs.unlink(req.files[fileFieldName].path);
}
}
}
exports.setSettings = function(settingsObj) {
applySetting("appToken", settingsObj, []);
applySetting("appTokenRequired", settingsObj, [exports.APP_TOKEN_ALWAYS_REQUIRED, exports.APP_TOKEN_NEVER_REQUIRED, exports.APP_TOKEN_PER_REQUEST_REQUIRED]);
applySetting("authenticatorMethod", settingsObj);
applySetting("documentationUrl", settingsObj);
applySetting("applicationName", settingsObj);
applySetting("authAttributes", settingsObj);
applySetting("apiRoot", settingsObj);
applySetting("apiRoot", settingsObj);
applySetting("wrapWithStatusAndData", settingsObj);
applySetting("authInHeaders", settingsObj);
}
// UTILITY METHODS FOR SENDING RESPONSES IN STANDARD FORMATS
exports.errorResponse = function (res, err, statusCode) {
var errorObj = {
error: "An error occurred"
}
if (settings.wrapWithStatusAndData) {
errorObj.status = "error"
}
if (err.fieldErrors) {
errorObj.field_errors = err.fieldErrors;
}
if (err === null) {
errorObj.error = "No results";
} else {
if (err.message) {
errorObj.error = err.message;
} else {
errorObj.error = err;
}
}
if (statusCode) {
errorObj.statusCode = statusCode;
res.status(statusCode).send(errorObj);
} else {
try {
res.status(500).send(errorObj);
} catch (e) {
// Done
}
}
};
exports.successResponse = function (res, data) {
if (settings.wrapWithStatusAndData) {
res.json({status: "ok", data: data});
} else {
res.json(data);
}
};
exports.
successOrErrorResponse = function (res, err, data) {
if (err) {
exports.errorResponse(res, err);
} else {
exports.successResponse(res, data);
}
};
exports.unauthorisedResponse = function (res, message) {
var errMessage = "Not logged in or authorised app"
if (message) {
errMessage = message;
}
res.status(401).send({status: "error", error: errMessage});
};
// Stream Video Utility Method
// Thanks to https://gist.github.com/paolorossi/1993068
exports.streamVideo = function(req, res, path, contentType) {
var contentTypeToUse = DEFAULT_VIDEO_STREAM_CONTENT_TYPE;
if (contentType && contentType != "") {
contentTypeToUse = contentType;
}
fs.exists(path, function(exists) {
if (exists) {
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers['range']) {
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total - 1;
var chunksize = (end - start) + 1;
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
res.writeHead(200, { 'Content-Length': total, 'Content-Type': contentTypeToUse});
fs.createReadStream(path).pipe(res);
}
}
else {
exports.errorResponse(res, "Invalid file path for streaming");
}
});
}
exports.runTests = function(filename, host, functions, callback) {
haypeaeyeTests.runTestsFromFile(filename, host, functions, callback);
}
exports.getStoredValuesFromTests = function() {
return haypeaeyeTests.getStoredValues();
}