shared.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from typing import List, Tuple, Union, Dict
  2. import collections
  3. import logging
  4. import aiohttp
  5. from ..schemas import GenMethodEnum, CountryCode
  6. geonames_user = "terrassumptions"
  7. geonames_url = "http://api.geonames.org/countryCodeJSON"
  8. # Google API key, with access to Street View Static API
  9. # this can be safely committed due to permission restriction
  10. google_api_key = "AIzaSyAqjCYR6Szph0X0H_iD6O1HenFhL9jySOo"
  11. metadata_url = "https://maps.googleapis.com/maps/api/streetview/metadata"
  12. logger = logging.getLogger(__name__)
  13. aiohttp_client = aiohttp.ClientSession()
  14. async def point_has_streetview(lat, lng):
  15. """
  16. Returns True if the streetview metadata endpoint says a given point has
  17. data available, and False otherwise.
  18. This function calls the streetview metadata endpoint - there is no quota consumed.
  19. """
  20. params = {
  21. "key": google_api_key,
  22. "location": f"{lat},{lng}",
  23. }
  24. async with aiohttp_client.get(metadata_url, params=params) as response:
  25. body = await response.json()
  26. return body["status"] == "OK"
  27. async def reverse_geocode(lat, lng):
  28. params = {
  29. "lat": str(lat),
  30. "lng": str(lng),
  31. "username": geonames_user,
  32. }
  33. try:
  34. async with aiohttp_client.get(geonames_url, params=params) as response:
  35. body = await response.json()
  36. country_code = body.get("countryCode", None)
  37. if country_code is not None:
  38. country_code = country_code.lower()
  39. return country_code
  40. except:
  41. logger.exception("Failed to reverse geocode! Hopefully this isn't a guess and the generator data is accurate...")
  42. return None