apple_maps.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Apple Maps"""
  4. from json import loads
  5. from time import time
  6. from urllib.parse import urlencode
  7. from searx.network import get as http_get
  8. about = {
  9. "website": 'https://www.apple.com/maps/',
  10. "wikidata_id": 'Q276101',
  11. "official_api_documentation": None,
  12. "use_official_api": True,
  13. "require_api_key": False,
  14. "results": 'JSON',
  15. }
  16. token = {'value': '', 'last_updated': None}
  17. categories = ['map']
  18. paging = False
  19. search_url = "https://api.apple-mapkit.com/v1/search?{query}&mkjsVersion=5.72.53"
  20. def obtain_token():
  21. update_time = time() - (time() % 1800)
  22. try:
  23. # use duckduckgo's mapkit token
  24. token_response = http_get('https://duckduckgo.com/local.js?get_mk_token=1', timeout=2.0)
  25. actual_token = http_get(
  26. 'https://cdn.apple-mapkit.com/ma/bootstrap?apiVersion=2&mkjsVersion=5.72.53&poi=1',
  27. timeout=2.0,
  28. headers={'Authorization': 'Bearer ' + token_response.text},
  29. )
  30. token['value'] = loads(actual_token.text)['authInfo']['access_token']
  31. token['last_updated'] = update_time
  32. # pylint: disable=bare-except
  33. except:
  34. pass
  35. return token
  36. def init(_engine_settings=None):
  37. obtain_token()
  38. def request(query, params):
  39. if time() - (token['last_updated'] or 0) > 1800:
  40. obtain_token()
  41. params['url'] = search_url.format(query=urlencode({'q': query, 'lang': params['language']}))
  42. params['headers'] = {'Authorization': 'Bearer ' + token['value']}
  43. return params
  44. def response(resp):
  45. results = []
  46. resp_json = loads(resp.text)
  47. for result in resp_json['results']:
  48. box = result['displayMapRegion']
  49. results.append(
  50. {
  51. 'template': 'map.html',
  52. 'title': result['name'],
  53. 'latitude': result['center']['lat'],
  54. 'longitude': result['center']['lng'],
  55. 'url': result['placecardUrl'],
  56. 'boundingbox': [box['southLat'], box['northLat'], box['westLng'], box['eastLng']],
  57. 'geojson': {'type': 'Point', 'coordinates': [result['center']['lng'], result['center']['lat']]},
  58. 'address': {
  59. 'name': result['name'],
  60. 'house_number': result.get('subThoroughfare', {}),
  61. 'road': result.get('thoroughfare', {}),
  62. 'locality': result.get('locality', {}),
  63. 'postcode': result.get('postCode', {}),
  64. 'country': result.get('country', {}),
  65. },
  66. }
  67. )
  68. return results