-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial support for ip-api geolocation
Needs paid API support before use with Neon services
- Loading branch information
1 parent
95038a9
commit c2e60e7
Showing
6 changed files
with
223 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework | ||
# All trademark and other rights reserved by their respective owners | ||
# Copyright 2008-2022 Neongecko.com Inc. | ||
# Contributors: Daniel McKnight, Guy Daniels, Elon Gasper, Richard Leeds, | ||
# Regina Bloomstine, Casimiro Ferreira, Andrii Pernatii, Kirill Hrymailo | ||
# BSD-3 License | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# 1. Redistributions of source code must retain the above copyright notice, | ||
# this list of conditions and the following disclaimer. | ||
# 2. Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# 3. Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from this | ||
# software without specific prior written permission. | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | ||
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR | ||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | ||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | ||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, | ||
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
import json | ||
|
||
from ovos_utils.log import LOG | ||
from neon_api_proxy.client import NeonAPI, request_api | ||
|
||
|
||
def get_location(ip_addr: str) -> dict: | ||
""" | ||
Get a dict location for the requested public IP Address | ||
@param ip_addr: Public IP address to geolocate | ||
@returns: dict location | ||
""" | ||
resp = request_api(NeonAPI.IP_API, {"ip": ip_addr}) | ||
if resp['status_code'] == 200: | ||
resp['content'] = json.loads(resp['content']) | ||
if resp['content']['status'] != "success": | ||
resp['status_code'] = 500 | ||
LOG.warning(f"Got failure response: {resp}") | ||
LOG.info(f"Got location: {resp['content']}") | ||
return resp['content'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework | ||
# All trademark and other rights reserved by their respective owners | ||
# Copyright 2008-2022 Neongecko.com Inc. | ||
# Contributors: Daniel McKnight, Guy Daniels, Elon Gasper, Richard Leeds, | ||
# Regina Bloomstine, Casimiro Ferreira, Andrii Pernatii, Kirill Hrymailo | ||
# BSD-3 License | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# 1. Redistributions of source code must retain the above copyright notice, | ||
# this list of conditions and the following disclaimer. | ||
# 2. Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# 3. Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from this | ||
# software without specific prior written permission. | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | ||
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR | ||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | ||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | ||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, | ||
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
import urllib.parse | ||
|
||
from datetime import timedelta | ||
from time import time, sleep | ||
from requests import Response | ||
from ovos_utils.log import LOG | ||
|
||
from neon_api_proxy.cached_api import CachedAPI | ||
|
||
|
||
class IpGeolocationAPI(CachedAPI): | ||
""" | ||
API for querying IP Geolocation (ip-api.com). | ||
""" | ||
|
||
def __init__(self, api_key=None, cache_seconds=604800): # Cache week | ||
super().__init__("ip_api") | ||
self.cache_timeout = timedelta(seconds=cache_seconds) | ||
if api_key: | ||
self.geolocate_api = "https://members.ip-api.com/json/" | ||
else: | ||
self.geolocate_api = "http://ip-api.com/json/" | ||
|
||
def handle_query(self, **kwargs) -> dict: | ||
""" | ||
Handles an incoming query and provides a response | ||
:param kwargs: | ||
'ip' - IP Address to location | ||
:return: dict containing `status_code`, `content`, `encoding` | ||
from URL response | ||
""" | ||
ip = kwargs.get('ip') | ||
try: | ||
# TODO: Build URL with API key | ||
response = self.get_with_cache_timeout(f"{self.geolocate_api}{ip}") | ||
return {"status_code": response.status_code, | ||
"content": response.content, | ||
"encoding": response.encoding} | ||
except Exception as e: | ||
return {"status_code": 500, | ||
"content": repr(e), | ||
"encoding": None} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework | ||
# All trademark and other rights reserved by their respective owners | ||
# Copyright 2008-2022 Neongecko.com Inc. | ||
# Contributors: Daniel McKnight, Guy Daniels, Elon Gasper, Richard Leeds, | ||
# Regina Bloomstine, Casimiro Ferreira, Andrii Pernatii, Kirill Hrymailo | ||
# BSD-3 License | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# 1. Redistributions of source code must retain the above copyright notice, | ||
# this list of conditions and the following disclaimer. | ||
# 2. Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# 3. Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from this | ||
# software without specific prior written permission. | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | ||
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR | ||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | ||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | ||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, | ||
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
import json | ||
import os | ||
import sys | ||
import unittest | ||
|
||
from requests import Response | ||
|
||
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) | ||
from neon_api_proxy.services.ip_geolocation_api import IpGeolocationAPI | ||
|
||
WA_IP = '50.47.222.4' | ||
DO_IP = '146.190.53.128' | ||
INVALID_IP = '10.0.0.1' | ||
|
||
|
||
class TestIpGeolocationAPI(unittest.TestCase): | ||
@classmethod | ||
def setUpClass(cls) -> None: | ||
cls.api = IpGeolocationAPI() | ||
|
||
def test_lookup(self): | ||
resp = self.api.handle_query(ip=WA_IP) | ||
self.assertEqual(resp['status_code'], 200, resp) | ||
location = json.loads(resp['content'].decode(resp['encoding'])) | ||
self.assertEqual(location['query'], WA_IP) | ||
self.assertEqual(location['country'], 'United States') | ||
self.assertEqual(location['regionName'], 'Washington') | ||
self.assertEqual(location['timezone'], 'America/Los_Angeles') | ||
self.assertAlmostEqual(location['lat'], 48.0, 0) | ||
self.assertAlmostEqual(location['lon'], -122.0, 0) | ||
|
||
resp = self.api.handle_query(ip=DO_IP) | ||
self.assertEqual(resp['status_code'], 200, resp) | ||
location = json.loads(resp['content'].decode(resp['encoding'])) | ||
self.assertEqual(location['query'], DO_IP) | ||
self.assertEqual(location['country'], 'United States') | ||
self.assertEqual(location['regionName'], 'California') | ||
self.assertEqual(location['timezone'], 'America/Los_Angeles') | ||
self.assertAlmostEqual(location['lat'], 37.0, 0) | ||
self.assertAlmostEqual(location['lon'], -122.0, 0) | ||
|
||
resp = self.api.handle_query(ip=INVALID_IP) | ||
self.assertEqual(resp['status_code'], 200, resp) | ||
location = json.loads(resp['content'].decode(resp['encoding'])) | ||
self.assertEqual(location['status'], 'fail') | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |