This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+74 -53
View File
@@ -10,9 +10,9 @@ from typing import Any, Optional, Tuple, Dict
import aiohttp
ELEVATION_URL = 'https://api.open-elevation.com/api/v1/lookup'
IP_API = 'http://ip-api.com/json'
IPAPI = 'https://ipapi.co/json/'
ELEVATION_URL = "https://api.open-elevation.com/api/v1/lookup"
IP_API = "http://ip-api.com/json"
IPAPI = "https://ipapi.co/json/"
# Constants from https://github.com/maurycyp/vincenty
# Earth ellipsoid according to WGS 84
@@ -29,13 +29,25 @@ CONVERGENCE_THRESHOLD = 1e-12
LocationInfo = collections.namedtuple(
"LocationInfo",
['ip', 'country_code', 'country_name', 'region_code', 'region_name',
'city', 'zip_code', 'time_zone', 'latitude', 'longitude',
'use_metric'])
[
"ip",
"country_code",
"country_name",
"region_code",
"region_name",
"city",
"zip_code",
"time_zone",
"latitude",
"longitude",
"use_metric",
],
)
async def async_detect_location_info(session: aiohttp.ClientSession) \
-> Optional[LocationInfo]:
async def async_detect_location_info(
session: aiohttp.ClientSession
) -> Optional[LocationInfo]:
"""Detect location information."""
data = await _get_ipapi(session)
@@ -45,14 +57,14 @@ async def async_detect_location_info(session: aiohttp.ClientSession) \
if data is None:
return None
data['use_metric'] = data['country_code'] not in (
'US', 'MM', 'LR')
data["use_metric"] = data["country_code"] not in ("US", "MM", "LR")
return LocationInfo(**data)
def distance(lat1: Optional[float], lon1: Optional[float],
lat2: float, lon2: float) -> Optional[float]:
def distance(
lat1: Optional[float], lon1: Optional[float], lat2: float, lon2: float
) -> Optional[float]:
"""Calculate the distance in meters between two points.
Async friendly.
@@ -69,8 +81,9 @@ def distance(lat1: Optional[float], lon1: Optional[float],
# Source: https://github.com/maurycyp/vincenty
# License: https://github.com/maurycyp/vincenty/blob/master/LICENSE
# pylint: disable=invalid-name
def vincenty(point1: Tuple[float, float], point2: Tuple[float, float],
miles: bool = False) -> Optional[float]:
def vincenty(
point1: Tuple[float, float], point2: Tuple[float, float], miles: bool = False
) -> Optional[float]:
"""
Vincenty formula (inverse method) to calculate the distance.
@@ -96,8 +109,9 @@ def vincenty(point1: Tuple[float, float], point2: Tuple[float, float],
for _ in range(MAX_ITERATIONS):
sinLambda = math.sin(Lambda)
cosLambda = math.cos(Lambda)
sinSigma = math.sqrt((cosU2 * sinLambda) ** 2 +
(cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ** 2)
sinSigma = math.sqrt(
(cosU2 * sinLambda) ** 2 + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ** 2
)
if sinSigma == 0.0:
return 0.0 # coincident points
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda
@@ -108,14 +122,12 @@ def vincenty(point1: Tuple[float, float], point2: Tuple[float, float],
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha
except ZeroDivisionError:
cos2SigmaM = 0
C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 *
cosSqAlpha))
C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha))
LambdaPrev = Lambda
Lambda = L + (1 - C) * FLATTENING * sinAlpha * (sigma + C * sinSigma *
(cos2SigmaM + C *
cosSigma *
(-1 + 2 *
cos2SigmaM ** 2)))
Lambda = L + (1 - C) * FLATTENING * sinAlpha * (
sigma
+ C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2))
)
if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD:
break # successful convergence
else:
@@ -124,12 +136,23 @@ def vincenty(point1: Tuple[float, float], point2: Tuple[float, float],
uSq = cosSqAlpha * (AXIS_A ** 2 - AXIS_B ** 2) / (AXIS_B ** 2)
A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))
B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))
deltaSigma = B * sinSigma * (cos2SigmaM +
B / 4 * (cosSigma * (-1 + 2 *
cos2SigmaM ** 2) -
B / 6 * cos2SigmaM *
(-3 + 4 * sinSigma ** 2) *
(-3 + 4 * cos2SigmaM ** 2)))
deltaSigma = (
B
* sinSigma
* (
cos2SigmaM
+ B
/ 4
* (
cosSigma * (-1 + 2 * cos2SigmaM ** 2)
- B
/ 6
* cos2SigmaM
* (-3 + 4 * sinSigma ** 2)
* (-3 + 4 * cos2SigmaM ** 2)
)
)
)
s = AXIS_B * A * (sigma - deltaSigma)
s /= 1000 # Conversion of meters to kilometers
@@ -139,8 +162,7 @@ def vincenty(point1: Tuple[float, float], point2: Tuple[float, float],
return round(s, 6)
async def _get_ipapi(session: aiohttp.ClientSession) \
-> Optional[Dict[str, Any]]:
async def _get_ipapi(session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]:
"""Query ipapi.co for location data."""
try:
resp = await session.get(IPAPI, timeout=5)
@@ -153,21 +175,20 @@ async def _get_ipapi(session: aiohttp.ClientSession) \
return None
return {
'ip': raw_info.get('ip'),
'country_code': raw_info.get('country'),
'country_name': raw_info.get('country_name'),
'region_code': raw_info.get('region_code'),
'region_name': raw_info.get('region'),
'city': raw_info.get('city'),
'zip_code': raw_info.get('postal'),
'time_zone': raw_info.get('timezone'),
'latitude': raw_info.get('latitude'),
'longitude': raw_info.get('longitude'),
"ip": raw_info.get("ip"),
"country_code": raw_info.get("country"),
"country_name": raw_info.get("country_name"),
"region_code": raw_info.get("region_code"),
"region_name": raw_info.get("region"),
"city": raw_info.get("city"),
"zip_code": raw_info.get("postal"),
"time_zone": raw_info.get("timezone"),
"latitude": raw_info.get("latitude"),
"longitude": raw_info.get("longitude"),
}
async def _get_ip_api(session: aiohttp.ClientSession) \
-> Optional[Dict[str, Any]]:
async def _get_ip_api(session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]:
"""Query ip-api.com for location data."""
try:
resp = await session.get(IP_API, timeout=5)
@@ -179,14 +200,14 @@ async def _get_ip_api(session: aiohttp.ClientSession) \
except (aiohttp.ClientError, ValueError):
return None
return {
'ip': raw_info.get('query'),
'country_code': raw_info.get('countryCode'),
'country_name': raw_info.get('country'),
'region_code': raw_info.get('region'),
'region_name': raw_info.get('regionName'),
'city': raw_info.get('city'),
'zip_code': raw_info.get('zip'),
'time_zone': raw_info.get('timezone'),
'latitude': raw_info.get('lat'),
'longitude': raw_info.get('lon'),
"ip": raw_info.get("query"),
"country_code": raw_info.get("countryCode"),
"country_name": raw_info.get("country"),
"region_code": raw_info.get("region"),
"region_name": raw_info.get("regionName"),
"city": raw_info.get("city"),
"zip_code": raw_info.get("zip"),
"time_zone": raw_info.get("timezone"),
"latitude": raw_info.get("lat"),
"longitude": raw_info.get("lon"),
}