1 | var fs = require('fs');
|
2 | var path = require('path');
|
3 | var url = require('url');
|
4 | var HTTPScout = require('./http_scout');
|
5 |
|
6 | var RegistrationResource = module.exports = function(fog, basedir) {
|
7 | this.scout = new HTTPScout();
|
8 | this.basedir = basedir;
|
9 | this.path = '/registration';
|
10 |
|
11 | fog.loadScouts([this.scout], function(){});
|
12 | };
|
13 |
|
14 | RegistrationResource.prototype.init = function(config) {
|
15 | config
|
16 | .path(this.path)
|
17 | .consumes('application/json')
|
18 | .post('/', this.register)
|
19 | };
|
20 |
|
21 | RegistrationResource.prototype.register = function(env, next) {
|
22 | var self = this;
|
23 |
|
24 | env.request.getBody(function(err, body) {
|
25 | body = JSON.parse(body.toString());
|
26 |
|
27 | var dir = path.join(self.basedir, 'drivers');
|
28 | var found;
|
29 | fs.readdir(dir, function(err, files) {
|
30 | files.forEach(function(file) {
|
31 | if (!/^.+\.js$/.test(file)) {
|
32 | return;
|
33 | }
|
34 |
|
35 | if (found) {
|
36 | return;
|
37 | }
|
38 | var fullPath = path.join(dir, file);
|
39 | var driver = require(fullPath);
|
40 | var instance = new driver();
|
41 |
|
42 | if (instance.type === body.device.type) {
|
43 | self.scout.drivers.push(instance.type);
|
44 | self.scout.driverFunctions.push(driver);
|
45 | found = driver;
|
46 | }
|
47 | });
|
48 |
|
49 | if (found) {
|
50 | self.scout.emit('discover', found, body.device);
|
51 | env.response.statusCode = 201;
|
52 | var currentUrl = env.helpers.url.current();
|
53 | var parsed = url.parse(currentUrl);
|
54 | var parsedPath = parsed.pathname.split('/');
|
55 | parsedPath.pop();
|
56 | parsedPath.push(body.target);
|
57 | parsedPath.push(body.device.name);
|
58 |
|
59 | parsed.pathname = parsedPath.join('/');
|
60 | var endpoint = url.format(parsed);
|
61 | env.response.setHeader('Location', endpoint);
|
62 | } else {
|
63 | env.response.statusCode = 404;
|
64 | }
|
65 |
|
66 | next(env);
|
67 | });
|
68 | });
|
69 | };
|