domotz-remote-pawn
Version:
Domotz Agent
94 lines (90 loc) • 3.39 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 14/09/15.
*/
var providers = {
maxmind: {
extractData: function (body) {
var dict = JSON.parse(body);
dict.location.country_code = dict.country.iso_code;
return dict.location;
},
request: {
url: "https://js.maxmind.com/geoip/v2.1/city/me",
headers: {
'Referer': 'https://www.maxmind.com/en/geoip2-javascript-demo',
'Origin': 'https://www.maxmind.com'
}
}
},
freegeoip: {
extractData: function (body) {
var dict = JSON.parse(body);
return {
"latitude": dict.latitude,
"longitude": dict.longitude,
"time_zone": dict.time_zone,
"country_code": dict.country_code
};
},
request: {
url: 'http://freegeoip.net/json/'
}
}
};
var fallbackData = {
latitude: 40.758895,
longitude: -73.985131,
provider: "Default",
time_zone: "America/New_York",
country_code: 'US'
};
module.exports.getLocationFromService = function (provider, resourceLocator, errorCallback, successCallback) {
if (providers[provider] === undefined) {
console.info("Provider %s not found, using fallback data", provider);
return successCallback(fallbackData);
}
var providerData = providers[provider];
var request = resourceLocator.request;
var _ = resourceLocator._;
console.info("Getting location from provider:" + provider);
console.debug("Calling :" + JSON.stringify(providerData.request));
request.get(providerData.request, function (error, response, body) {
if (error) {
console.debug("Error :" + JSON.stringify(error));
return errorCallback(error);
}
else if (response.statusCode < 200 || response.statusCode > 299) {
console.debug("Error :" + JSON.stringify(response));
return errorCallback({code: response.statusCode, message: body});
}
console.debug("Parsing data :" + JSON.stringify(body));
try {
var data = providerData.extractData(body);
if (_.isFinite(data.latitude) && _.isFinite(data.longitude) && _.isString(data.time_zone)) {
data.provider = provider;
return successCallback(data);
}
}
catch (error) {
console.error(JSON.stringify(error));
}
return errorCallback({message: "Invalid data: " + body, code: response.statusCode});
});
};