70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
import logging
|
|
import time
|
|
|
|
import pendulum
|
|
from aiohttp import ClientSession
|
|
from gestion_sports.gestion_sports_connector import GestionSportsConnector
|
|
from models import BookingFilter, Club, User
|
|
from pendulum import DateTime
|
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class GestionSportsOperations:
|
|
def __init__(self, club: Club):
|
|
self.platform: GestionSportsConnector | None = None
|
|
self.club: Club = club
|
|
self.session: ClientSession | None = None
|
|
|
|
async def __aenter__(self):
|
|
self.session = ClientSession()
|
|
self.platform = GestionSportsConnector(self.session, self.club.url)
|
|
return self
|
|
|
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
await self.session.close()
|
|
|
|
async def book(self, user: User, booking_filter: BookingFilter) -> int | None:
|
|
if self.platform is None or user is None or booking_filter is None:
|
|
return None
|
|
|
|
await self.platform.land()
|
|
await self.platform.login(user, self.club)
|
|
wait_until_booking_time(self.club, booking_filter)
|
|
return await self.platform.book(booking_filter, self.club)
|
|
|
|
|
|
def wait_until_booking_time(club: Club, booking_filter: BookingFilter):
|
|
"""
|
|
Wait until the booking is open.
|
|
The booking filter contains the date and time of the booking.
|
|
The club has the information about when the booking is open for that date.
|
|
|
|
:param club: the club where to book a court
|
|
:param booking_filter: the booking information
|
|
"""
|
|
LOGGER.info("Waiting booking time")
|
|
booking_datetime = build_booking_datetime(booking_filter, club)
|
|
now = pendulum.now()
|
|
while now < booking_datetime:
|
|
time.sleep(1)
|
|
now = pendulum.now()
|
|
|
|
|
|
def build_booking_datetime(booking_filter: BookingFilter, club: Club) -> DateTime:
|
|
"""
|
|
Build the date and time when the booking is open for a given match date.
|
|
The booking filter contains the date and time of the booking.
|
|
The club has the information about when the booking is open for that date.
|
|
|
|
:param booking_filter: the booking information
|
|
:param club: the club where to book a court
|
|
:return: the date and time when the booking is open
|
|
"""
|
|
date_to_book = booking_filter.date
|
|
booking_date = date_to_book.subtract(days=club.booking_open_days_before)
|
|
|
|
booking_hour = club.booking_opening_time.hour
|
|
booking_minute = club.booking_opening_time.minute
|
|
|
|
return booking_date.at(booking_hour, booking_minute)
|