brittany-ferries/ferry/api.py
2023-09-11 07:00:20 +01:00

107 lines
3 KiB
Python

"""Interface with the Brittany Ferries API."""
from typing import Any, TypedDict
import requests
import json
from . import Vehicle
api_root_url = "https://www.brittany-ferries.co.uk/api/ferry/v1/"
ua = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0"
headers = {"User-Agent": ua}
class VehicleDict(TypedDict):
"""Description of vechicle in the format expected by the API."""
type: str
registrations: list[str]
height: int
length: int
extras: dict[str, None | bool]
def vehicle_dict(v: Vehicle, rear_mounted_bike_carrier: bool = False) -> VehicleDict:
"""Return vehicle detail in the format for the Brittany Ferries API."""
rmbc = True if rear_mounted_bike_carrier else None
return {
"type": v.type,
"registrations": [v.registration],
"height": v.height,
"length": v.length,
"extras": {"rearMountedBikeCarrier": rmbc},
}
def get_prices(
departure_port: str,
arrival_port: str,
from_date: str,
to_date: str,
vehicle: Vehicle,
adults: int = 2,
small_dogs: int = 1,
rear_mounted_bike_carrier: bool = False,
) -> dict[str, Any]:
"""Call Brittany Ferries API to get details of crossings."""
url = api_root_url + "crossing/prices"
post_data = {
"bookingReference": None,
"pets": {"smallDogs": small_dogs, "largeDogs": 0, "cats": 0},
"passengers": {"adults": adults, "children": 0, "infants": 0},
"vehicle": vehicle_dict(vehicle, rear_mounted_bike_carrier),
"departurePort": departure_port,
"arrivalPort": arrival_port,
"disability": None,
"sponsor": None,
"fromDate": f"{from_date}T00:00:00",
"toDate": f"{to_date}T23:59:59",
}
r = requests.post(url, json=post_data, headers=headers)
data: dict[str, Any] = r.json()
if "crossings" not in data:
print(json.dumps(data, indent=2))
return data
def get_accommodations(
departure_port: str,
arrival_port: str,
departure_date: str,
ticket_tier: str,
vehicle: Vehicle,
adults: int,
small_dogs: int,
rear_mounted_bike_carrier: bool = False,
) -> dict[str, Any]:
"""Grab cabin details."""
url = api_root_url + "crossing/accommodations"
post_data = {
"bookingReference": None,
"departurePort": departure_port,
"arrivalPort": arrival_port,
"departureDate": departure_date,
"passengers": {"adults": adults, "children": 0, "infants": 0},
"disability": None,
"vehicle": vehicle_dict(vehicle, rear_mounted_bike_carrier),
"petCabinsNeeded": True,
"ticketTier": ticket_tier,
"pets": {"smallDogs": small_dogs, "largeDogs": 0, "cats": 0},
"sponsor": None,
"offerType": "NONE",
}
json_data: dict[str, Any] = requests.post(
url, json=post_data, headers=headers
).json()
if "crossings" not in json_data:
print()
print(json.dumps(post_data, indent=2))
print()
print(json.dumps(json_data, indent=2))
return json_data