.pragma library /* * Copyright (C) 2013 Canonical Ltd. * Copyright (C) 2024 Maciej Sopyło * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program 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 this program. If not, see . * * Authored by: Raúl Yeguas * Martin Borho * Andrew Starr-Bochicchio */ /** * Version of the response data format. * Increase this number to force a refresh. */ var RESPONSE_DATA_VERSION = 20230101; /** * Helper functions */ // Remove just the API key function trimAPIKey(data) { if (data === undefined) { return undefined; } const GEONAMES_KEY_PARAM = "username="; const geonamesIndex = data.indexOf(GEONAMES_KEY_PARAM); if (geonamesIndex > -1) { const ampIndex = data.indexOf("&", geonamesIndex); const rangeEnd = ampIndex > -1 ? ampIndex : data.length; data = `${data.slice(0, geonamesIndex)}removed_for_logging${data.slice(ampIndex)}`; } return data; } const GeoipApi = (() => { const BASE_URL = "http://geoip.ubuntu.com/lookup"; return { getLatLong(params, apiCaller, onSuccess, onError) { const request = { type: "geolookup", url: BASE_URL, }; function resultHandler(request, xmlDoc) { const coords = {}; const childNodes = xmlDoc.childNodes; for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].nodeName === "Latitude") { coords.lat = childNodes[i].firstChild.nodeValue; } else if (childNodes[i].nodeName === "Longitude") { coords.lon = childNodes[i].firstChild.nodeValue; } } onSuccess(coords); } function retryHandler(err) { console.log("geolookup retry of " + err.request.url); apiCaller(request, resultHandler, onError); } apiCaller(request, resultHandler, retryHandler); } } })(); const GeonamesApi = (() => { /** provides necessary methods for requesting and preparing data from Geonames.org */ const BASE_URL = "http://api.geonames.org/"; const USERNAME = "uweatherdev" const ADD_PARAMS = "&maxRows=25&featureClass=P" function _buildSearchResult(request, data) { const searchResult = { locations: [], request: request }; if (!data.geonames) { return searchResult; } data.geonames.forEach((location) => { searchResult.locations.push({ name: location.name, coord: { lat: location.lat, lon: location.lng, }, country: location.countryCode, countryName: location.countryName, timezone: location.timezone, adminName1: location.adminName1, adminName2: location.adminName2, adminName3: location.adminName3, services: { "geonames": location.geonameId, }, }); }); return searchResult; } return { search(mode, params, apiCaller, onSuccess, onError) { function retryHandler(err) { console.log("search retry of " + err.request.url); apiCaller(request, searchResponseHandler, onError); } function searchResponseHandler(request, data) { onSuccess(_buildSearchResult(request, data)); } let request; if (mode === "point") { request = { type: "search", url: BASE_URL + "findNearbyPlaceNameJSON?style=full&username=" + encodeURIComponent(USERNAME) + "&lat=" + encodeURIComponent(params.coords.lat) + "&lng=" + encodeURIComponent(params.coords.lon) + "&lang=" + encodeURIComponent(params.lang).replace("_","-") + ADD_PARAMS, }; } else { request = { type: "search", url: BASE_URL + "searchJSON?style=full&username=" + encodeURIComponent(USERNAME) + "&name_startsWith=" + encodeURIComponent(params.name) + "&lang=" + encodeURIComponent(params.lang).replace("_","-") + ADD_PARAMS, }; } apiCaller(request, searchResponseHandler, retryHandler); } } })(); const WeatherApi = ((_services) => { /** proxy for requesting weather apis, the passed _services are providing the respective api endpoints and formatters to build a uniform response object */ function _getService(name) { if (_services[name] !== undefined) { return _services[name]; } return _services["geonames"]; } function _sendRequest(request, onSuccess, onError) { const xhr = new XMLHttpRequest(); if (!xhr) { return; } xhr.open('GET', request.url, true); xhr.onreadystatechange = () => { try { if (xhr.readyState !== 4) { return; } if (xhr.status !== 200) { request.url = trimAPIKey(request.url); onError({ msg: "received error code, got " + xhr.status + ", details: " + xhr.responseText, request: request }); return; } if (xhr.responseXML) { onSuccess(request, xhr.responseXML.documentElement); } else { const json = JSON.parse(xhr.responseText); onSuccess(request, json); } } catch (e) { print("Exception: " + e); request.url = trimAPIKey(request.url); onError({ msg: "wrong response data format", request: request }); } }; xhr.send(null); } return { geoLookup(params, onSuccess, onError) { const service = _getService('geoip'); const geoNameService = _getService('geonames'); function lookupHandler(data) { print("Geolookup: " + JSON.stringify(data)); geoNameService.search("point", { coords: data }, _sendRequest, onSuccess, onError); } service.getLatLong(params, _sendRequest, lookupHandler, onError) }, search(mode, params, onSuccess, onError) { const service = _getService('geonames'); service.search(mode, params, _sendRequest, onSuccess, onError); }, } })({ "geonames": GeonamesApi, "geoip": GeoipApi }); function sendRequest(message, responseCallback) { // handles the response data function finished(result) { responseCallback({ action: message.action, result: result, }); } // handles errors function onError(err) { console.log(JSON.stringify(err, null, true)); responseCallback({ error: err }); } // perform the api calls if (message.action === "searchByName") { WeatherApi.search("name", message.params, finished, onError); } else if(message.action === "searchByPoint" || message.action === "searchByUrl") { WeatherApi.search("point", message.params, finished, onError); } else if(message.action === "getGeoIp") { WeatherApi.geoLookup(message.params, finished, onError); } }