padel/padel/combo.py

61 lines
1.8 KiB
Python
Raw Permalink Normal View History

2021-08-11 16:28:28 +02:00
from tennis import get_time_slots, get_club_address
from weather import WeatherAPI
2021-08-11 17:43:49 +02:00
from datetime import timedelta, datetime
2021-08-11 16:28:28 +02:00
import asyncio as aio
# Provided by my code monkey Lander
2021-08-11 16:42:34 +02:00
GOOD_CODES = [1000, 1003, 1006, 1009, 1150, 1153]
2021-08-11 16:28:28 +02:00
async def get_decent_timeslots(club_id, weather_api_key, days=1):
club_address = await get_club_address(club_id)
if club_address is None:
return None
weather_api = WeatherAPI(weather_api_key)
weather_forecasts, timeslots = await aio.gather(
weather_api.get_hourly_conditions(club_address, days=days),
2021-08-11 16:42:34 +02:00
get_time_slots(club_id, days=days),
2021-08-11 16:28:28 +02:00
)
# Filter out bad weather forecasts & sort them according to date & time
2021-08-11 16:42:34 +02:00
weather_forecasts = sorted(
filter(lambda x: x[2] in GOOD_CODES, weather_forecasts), key=lambda x: x[0]
)
2021-08-11 16:28:28 +02:00
2021-08-11 16:40:23 +02:00
# Convert weather_forecasts to dict for faster lookups
2021-08-11 16:42:34 +02:00
weather_forecasts = {
date_obj: weather_str for date_obj, weather_str, _ in weather_forecasts
}
2021-08-11 16:40:23 +02:00
2021-08-11 17:43:49 +02:00
# Filter out non-free timeslots or timeslots in the past
now = datetime.now()
timeslots = list(filter(lambda x: x[1] == 0 and x[2] > now, timeslots))
2021-08-11 16:40:23 +02:00
output = []
for field_name, _, start_time, duration in timeslots:
start_hour = start_time.replace(minute=0)
weather_names = []
valid = True
while start_hour < start_time + duration:
2021-08-11 16:42:34 +02:00
if weather_name := weather_forecasts.get(start_hour):
2021-08-11 16:40:23 +02:00
weather_names.append(weather_name)
# If we can't find any information about the timeslot, we assume
# it's bad
else:
valid = False
break
2021-08-11 16:42:34 +02:00
2021-08-11 16:40:23 +02:00
start_hour += timedelta(hours=1)
if valid:
output.append((field_name, start_time, duration, weather_names))
2021-08-11 16:28:28 +02:00
2021-08-11 16:40:23 +02:00
return output