|
| 1 | +import logging |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +import aiohttp |
| 5 | +from aiolimiter import AsyncLimiter |
| 6 | +from traveltimepy import Coordinates |
| 7 | + |
| 8 | +from traveltime_google_comparison.config import Mode |
| 9 | +from traveltime_google_comparison.requests.base_handler import ( |
| 10 | + BaseRequestHandler, |
| 11 | + RequestResult, |
| 12 | +) |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class HereApiError(Exception): |
| 18 | + pass |
| 19 | + |
| 20 | + |
| 21 | +class HereRequestHandler(BaseRequestHandler): |
| 22 | + HERE_ROUTES_URL = "https://router.hereapi.com/v8/routes" |
| 23 | + |
| 24 | + default_timeout = aiohttp.ClientTimeout(total=60) |
| 25 | + |
| 26 | + def __init__(self, api_key, max_rpm): |
| 27 | + self.api_key = api_key |
| 28 | + self._rate_limiter = AsyncLimiter(max_rpm // 60, 1) |
| 29 | + |
| 30 | + async def send_request( |
| 31 | + self, |
| 32 | + origin: Coordinates, |
| 33 | + destination: Coordinates, |
| 34 | + departure_time: datetime, |
| 35 | + mode: Mode, |
| 36 | + ) -> RequestResult: |
| 37 | + params = { |
| 38 | + "transportMode": get_here_specific_mode(mode), |
| 39 | + "origin": f"{origin.lat},{origin.lng}", |
| 40 | + "destination": f"{destination.lat},{destination.lng}", |
| 41 | + "return": "summary", |
| 42 | + "departureTime": departure_time.strftime("%Y-%m-%dT%H:%M:%S"), |
| 43 | + "apikey": self.api_key, |
| 44 | + } |
| 45 | + try: |
| 46 | + async with aiohttp.ClientSession( |
| 47 | + timeout=self.default_timeout |
| 48 | + ) as session, session.get(self.HERE_ROUTES_URL, params=params) as response: |
| 49 | + data = await response.json() |
| 50 | + if response.status == 200: |
| 51 | + first_route = data["routes"][0] |
| 52 | + |
| 53 | + if not first_route: |
| 54 | + raise HereApiError( |
| 55 | + "No route found between origin and destination." |
| 56 | + ) |
| 57 | + |
| 58 | + # I think for a simple routing request, there should only be one section. But just in case |
| 59 | + # I'm taking the sum of all sections |
| 60 | + total_duration = sum( |
| 61 | + section["summary"]["duration"] |
| 62 | + for section in first_route["sections"] |
| 63 | + ) |
| 64 | + |
| 65 | + return RequestResult(travel_time=total_duration) |
| 66 | + else: |
| 67 | + error_message = data.get("detailedError", "") |
| 68 | + logger.error( |
| 69 | + f"Error in HERE API response: {response.status} - {error_message}" |
| 70 | + ) |
| 71 | + return RequestResult(None) |
| 72 | + except Exception as e: |
| 73 | + logger.error(f"Exception during requesting HERE API, {e}") |
| 74 | + return RequestResult(None) |
| 75 | + |
| 76 | + |
| 77 | +def get_here_specific_mode(mode: Mode) -> str: |
| 78 | + if mode == Mode.DRIVING: |
| 79 | + return "car" |
| 80 | + elif mode == Mode.PUBLIC_TRANSPORT: |
| 81 | + return "bus" # HERE doesn't have a general mode for transit / PT |
| 82 | + # TODO: figure out how to compare PT modes accorss different providers |
| 83 | + |
| 84 | + else: |
| 85 | + raise ValueError(f"Unsupported mode: `{mode.value}`") |
0 commit comments