domotz-remote-pawn
Version:
Domotz Agent
83 lines (76 loc) • 3.11 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
**/
/**
*
* Created by Iacopo Papalini <ipapalini@domotz.com> on 08/09/15.
*/
module.exports.get = function (resourceLocator, onException, onSuccess) {
return function (req, res) {
var domotzAgent = resourceLocator.entities.agent;
var data = domotzAgent.get();
onSuccess(res, data);
};
};
module.exports.post = function (resourceLocator, onException, onSuccess) {
var configurator = resourceLocator.configurator;
var domotzAgent = resourceLocator.entities.agent;
var serviceReStarter = resourceLocator.utils.proc.gracefulShutdown;
var httpOutputCache = resourceLocator.httpOutCache;
var removeOtherSettingsFiles = configurator.removeOtherSettingsFiles;
var myConsole = resourceLocator.log.decorateLogs();
return function (request, response) {
if (!resourceLocator.status.isRestricted()) {
myConsole.warn('Attempt to activate agent that is not in restricted mode');
response.status(404).send('Not Found');
return;
}
var body;
try {
//if content type header is missing request.body is a Buffer
body = JSON.parse(request.body.toString());
} catch (e) {
body = request.body;
}
try {
var apiKeyHeader = 'x-api-key';
var apiKey = request.headers[apiKeyHeader];
var endpoint = body.endpoint;
if (endpoint === undefined) {
onException(response, { status: 400, message: '{"error": "Missing parameter: endpoint"}' });
return;
}
domotzAgent
.activateOnPublicApi(endpoint, apiKey, body)
.then(configurator.setConfigurationUrl)
.then(configurator.getConfiguration)
.then(configurator.writeConfiguration)
.then(httpOutputCache.resetCache)
.then(removeOtherSettingsFiles)
.then(function () {
setTimeout(serviceReStarter, 1700);
})
.then(function () {
onSuccess(response);
})
.catch(function (err) {
onException(response, err);
});
} catch (err) {
onException(response, { status: 400, message: err.message });
}
};
};