A lot of features #1

Merged
kbe merged 11 commits from develop into main 2025-07-20 14:32:07 +00:00
Showing only changes of commit cba4299b9a - Show all commits

View File

@@ -62,11 +62,14 @@ logging.info("Logging enhanced with request library noise reduction")
class CrossFitBooker: class CrossFitBooker:
def __init__(self): def __init__(self) -> None:
self.auth_token = None """
self.user_id = None Initialize the CrossFitBooker with necessary attributes.
self.session = requests.Session() """
self.base_headers = { self.auth_token: Optional[str] = None
self.user_id: Optional[str] = None
self.session: requests.Session = requests.Session()
self.base_headers: Dict[str, str] = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0",
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"Nubapp-Origin": "user_apps", "Nubapp-Origin": "user_apps",
@@ -74,32 +77,42 @@ class CrossFitBooker:
self.session.headers.update(self.base_headers) self.session.headers.update(self.base_headers)
# Define mandatory parameters for API calls # Define mandatory parameters for API calls
self.mandatory_params = { self.mandatory_params: Dict[str, str] = {
"app_version": APP_VERSION, "app_version": APP_VERSION,
"device_type": DEVICE_TYPE, "device_type": DEVICE_TYPE,
"id_application": APPLICATION_ID, "id_application": APPLICATION_ID,
"id_category_activity": CATEGORY_ID "id_category_activity": CATEGORY_ID
} }
def get_auth_headers(self) -> Dict: def get_auth_headers(self) -> Dict[str, str]:
"""Return headers with authorization if available""" """
headers = self.base_headers.copy() Return headers with authorization if available.
Returns:
Dict[str, str]: Headers dictionary with authorization if available.
"""
headers: Dict[str, str] = self.base_headers.copy()
if self.auth_token: if self.auth_token:
headers["Authorization"] = f"Bearer {self.auth_token}" headers["Authorization"] = f"Bearer {self.auth_token}"
return headers return headers
def login(self) -> bool: def login(self) -> bool:
"""Authenticate and get the bearer token""" """
Authenticate and get the bearer token.
Returns:
bool: True if login is successful, False otherwise.
"""
try: try:
# First login endpoint # First login endpoint
login_params = { login_params: Dict[str, str] = {
"app_version": APP_VERSION, "app_version": APP_VERSION,
"device_type": DEVICE_TYPE, "device_type": DEVICE_TYPE,
"username": USERNAME, "username": USERNAME,
"password": PASSWORD "password": PASSWORD
} }
response = self.session.post( response: requests.Response = self.session.post(
"https://sport.nubapp.com/api/v4/users/checkUser.php", "https://sport.nubapp.com/api/v4/users/checkUser.php",
headers={"Content-Type": "application/x-www-form-urlencoded"}, headers={"Content-Type": "application/x-www-form-urlencoded"},
data=urlencode(login_params)) data=urlencode(login_params))
@@ -109,7 +122,7 @@ class CrossFitBooker:
return False return False
try: try:
login_data = response.json() login_data: Dict[str, Any] = response.json()
self.user_id = str(login_data["data"]["user"]["id_user"]) self.user_id = str(login_data["data"]["user"]["id_user"])
except KeyError as ke: except KeyError as ke:
logging.error(f"Key error during login: {str(ke)} - Response: {response.text}") logging.error(f"Key error during login: {str(ke)} - Response: {response.text}")
@@ -119,7 +132,7 @@ class CrossFitBooker:
return False return False
# Second login endpoint # Second login endpoint
response = self.session.post( response: requests.Response = self.session.post(
"https://sport.nubapp.com/api/v4/login", "https://sport.nubapp.com/api/v4/login",
headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}, headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
data=urlencode({ data=urlencode({
@@ -130,7 +143,7 @@ class CrossFitBooker:
if response.ok: if response.ok:
try: try:
login_data = response.json() login_data: Dict[str, Any] = response.json()
self.auth_token = login_data.get("token") self.auth_token = login_data.get("token")
except KeyError as ke: except KeyError as ke:
logging.error(f"Key error during login: {str(ke)} - Response: {response.text}") logging.error(f"Key error during login: {str(ke)} - Response: {response.text}")
@@ -156,34 +169,46 @@ class CrossFitBooker:
logging.error(f"Unexpected error during login: {str(e)}") logging.error(f"Unexpected error during login: {str(e)}")
return False return False
def get_available_sessions(self, start_date: datetime, end_date: datetime) -> Optional[Dict]: def get_available_sessions(self, start_date: datetime, end_date: datetime) -> Optional[Dict[str, Any]]:
"""Fetch available sessions from the API with comprehensive error handling""" """
Fetch available sessions from the API with comprehensive error handling.
Args:
start_date (datetime): Start date for fetching sessions.
end_date (datetime): End date for fetching sessions.
Returns:
Optional[Dict[str, Any]]: Dictionary containing available sessions if successful, None otherwise.
"""
if not self.auth_token or not self.user_id: if not self.auth_token or not self.user_id:
logging.error("Authentication required - missing token or user ID") logging.error("Authentication required - missing token or user ID")
return None return None
url = "https://sport.nubapp.com/api/v4/activities/getActivitiesCalendar.php" url: str = "https://sport.nubapp.com/api/v4/activities/getActivitiesCalendar.php"
# Prepare request with mandatory parameters # Prepare request with mandatory parameters
request_data = self.mandatory_params.copy() request_data: Dict[str, str] = self.mandatory_params.copy()
request_data.update({ request_data.update({
"id_user": self.user_id, "id_user": self.user_id,
"start_timestamp": start_date.strftime("%d-%m-%Y"), "start_timestamp": start_date.strftime("%d-%m-%Y"),
"end_timestamp": end_date.strftime("%d-%m-%Y") "end_timestamp": end_date.strftime("%d-%m-%Y")
}) })
# Add retry logic with exponential backoff # Add retry logic with exponential backoff and more informative error messages
for retry in range(RETRY_MAX): for retry in range(RETRY_MAX):
try: try:
try: try:
response = self.session.post( response: requests.Response = self.session.post(
url, url,
headers=self.get_auth_headers(), headers=self.get_auth_headers(),
data=urlencode(request_data), data=urlencode(request_data),
timeout=10 timeout=10
) )
except requests.exceptions.Timeout: except requests.exceptions.Timeout:
logging.error(f"Request timed out after 10 seconds for URL: {url}") logging.error(f"Request timed out after 10 seconds for URL: {url}. Retry {retry+1}/{RETRY_MAX}")
return None
except requests.exceptions.ConnectionError as e:
logging.error(f"Connection error for URL: {url} - Error: {str(e)}")
return None return None
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
logging.error(f"Request failed for URL: {url} - Error: {str(e)}") logging.error(f"Request failed for URL: {url} - Error: {str(e)}")
@@ -196,7 +221,7 @@ class CrossFitBooker:
if retry == RETRY_MAX - 1: if retry == RETRY_MAX - 1:
logging.error(f"Final retry failed: {str(e)}") logging.error(f"Final retry failed: {str(e)}")
raise # Propagate error raise # Propagate error
wait_time = RETRY_BACKOFF * (2 ** retry) wait_time: int = RETRY_BACKOFF * (2 ** retry)
logging.warning(f"Request failed (attempt {retry+1}/{RETRY_MAX}): {str(e)}. Retrying in {wait_time}s...") logging.warning(f"Request failed (attempt {retry+1}/{RETRY_MAX}): {str(e)}. Retrying in {wait_time}s...")
time.sleep(wait_time) time.sleep(wait_time)
else: else:
@@ -207,7 +232,7 @@ class CrossFitBooker:
# Handle response # Handle response
if response.status_code == 200: if response.status_code == 200:
try: try:
json_response = response.json() json_response: Dict[str, Any] = response.json()
return json_response return json_response
except ValueError: except ValueError:
logging.error("Failed to decode JSON response") logging.error("Failed to decode JSON response")
@@ -227,17 +252,32 @@ class CrossFitBooker:
else: else:
logging.error(f"Unexpected status code: {response.status_code}") logging.error(f"Unexpected status code: {response.status_code}")
return None return None
def book_session(self, session_id: str) -> bool: def book_session(self, session_id: str) -> bool:
"""Book a specific session with debug logging.""" """
Book a specific session with debug logging.
Args:
session_id (str): ID of the session to book.
Returns:
bool: True if booking is successful, False otherwise.
"""
return self._make_request( return self._make_request(
url="https://sport.nubapp.com/api/v4/activities/bookActivityCalendar.php", url="https://sport.nubapp.com/api/v4/activities/bookActivityCalendar.php",
data=self._prepare_booking_data(session_id), data=self._prepare_booking_data(session_id),
success_msg=f"Successfully booked session {session_id}" success_msg=f"Successfully booked session {session_id}"
) )
def _prepare_booking_data(self, session_id: str) -> Dict: def _prepare_booking_data(self, session_id: str) -> Dict[str, str]:
"""Prepare request data for booking a session""" """
Prepare request data for booking a session.
Args:
session_id (str): ID of the session to book.
Returns:
Dict[str, str]: Dictionary containing request data for booking a session.
"""
return { return {
**self.mandatory_params, **self.mandatory_params,
"id_activity_calendar": session_id, "id_activity_calendar": session_id,
@@ -247,11 +287,21 @@ class CrossFitBooker:
"booked_on": "3" "booked_on": "3"
} }
def _make_request(self, url: str, data: Dict, success_msg: str) -> bool: def _make_request(self, url: str, data: Dict[str, str], success_msg: str) -> bool:
"""Handle API requests with retry logic and response processing""" """
Handle API requests with retry logic and response processing.
Args:
url (str): URL for the API request.
data (Dict[str, str]): Data to send with the request.
success_msg (str): Message to log on successful request.
Returns:
bool: True if request is successful, False otherwise.
"""
for retry in range(RETRY_MAX): for retry in range(RETRY_MAX):
try: try:
response = self.session.post( response: requests.Response = self.session.post(
url, url,
headers=self.get_auth_headers(), headers=self.get_auth_headers(),
data=urlencode(data), data=urlencode(data),
@@ -259,7 +309,7 @@ class CrossFitBooker:
) )
if response.status_code == 200: if response.status_code == 200:
json_response = response.json() json_response: Dict[str, Any] = response.json()
if json_response.get("success", False): if json_response.get("success", False):
logging.info(success_msg) logging.info(success_msg)
return True return True
@@ -276,16 +326,25 @@ class CrossFitBooker:
if retry == RETRY_MAX - 1: if retry == RETRY_MAX - 1:
logging.error(f"Final retry failed: {str(e)}") logging.error(f"Final retry failed: {str(e)}")
raise # Propagate error raise # Propagate error
wait_time = RETRY_BACKOFF * (2 ** retry) wait_time: int = RETRY_BACKOFF * (2 ** retry)
logging.warning(f"Request failed (attempt {retry+1}/{RETRY_MAX}): {str(e)}. Retrying in {wait_time}s...") logging.warning(f"Request failed (attempt {retry+1}/{RETRY_MAX}): {str(e)}. Retrying in {wait_time}s...")
time.sleep(wait_time) time.sleep(wait_time)
logging.error(f"Failed to complete request after {RETRY_MAX} attempts") logging.error(f"Failed to complete request after {RETRY_MAX} attempts")
return False return False
def is_session_bookable(self, session: Dict, current_time: datetime) -> bool: def is_session_bookable(self, session: Dict[str, Any], current_time: datetime) -> bool:
"""Check if a session is bookable based on user_info, ignoring error codes.""" """
user_info = session.get("user_info", {}) Check if a session is bookable based on user_info, ignoring error codes.
Args:
session (Dict[str, Any]): Session data.
current_time (datetime): Current time for comparison.
Returns:
bool: True if the session is bookable, False otherwise.
"""
user_info: Dict[str, Any] = session.get("user_info", {})
# First check if can_join is true (primary condition) # First check if can_join is true (primary condition)
if user_info.get("can_join", False): if user_info.get("can_join", False):
@@ -293,12 +352,12 @@ class CrossFitBooker:
return True return True
# If can_join is False, check if there's a booking window # If can_join is False, check if there's a booking window
booking_date_str = user_info.get("unableToBookUntilDate", "") booking_date_str: str = user_info.get("unableToBookUntilDate", "")
booking_time_str = user_info.get("unableToBookUntilTime", "") booking_time_str: str = user_info.get("unableToBookUntilTime", "")
if booking_date_str and booking_time_str: if booking_date_str and booking_time_str:
try: try:
booking_datetime = datetime.strptime( booking_datetime: datetime = datetime.strptime(
f"{booking_date_str} {booking_time_str}", f"{booking_date_str} {booking_time_str}",
"%d-%m-%Y %H:%M" "%d-%m-%Y %H:%M"
) )
@@ -315,16 +374,25 @@ class CrossFitBooker:
# Default case: not bookable # Default case: not bookable
return False return False
def matches_preferred_session(self, session: Dict, current_time: datetime) -> bool: def matches_preferred_session(self, session: Dict[str, Any], current_time: datetime) -> bool:
"""Check if session matches one of your preferred sessions with fuzzy matching.""" """
Check if session matches one of your preferred sessions with fuzzy matching.
Args:
session (Dict[str, Any]): Session data.
current_time (datetime): Current time for comparison.
Returns:
bool: True if the session matches a preferred session, False otherwise.
"""
try: try:
session_time = parse(session["start_timestamp"]) session_time: datetime = parse(session["start_timestamp"])
if not session_time.tzinfo: if not session_time.tzinfo:
session_time = pytz.timezone(TIMEZONE).localize(session_time) session_time = pytz.timezone(TIMEZONE).localize(session_time)
day_of_week = session_time.weekday() day_of_week: int = session_time.weekday()
session_time_str = session_time.strftime("%H:%M") session_time_str: str = session_time.strftime("%H:%M")
session_name = session.get("name_activity", "").upper() session_name: str = session.get("name_activity", "").upper()
for preferred_day, preferred_time, preferred_name in PREFERRED_SESSIONS: for preferred_day, preferred_time, preferred_name in PREFERRED_SESSIONS:
# Exact match first # Exact match first
@@ -334,7 +402,7 @@ class CrossFitBooker:
return True return True
# Fuzzy match fallback (80% similarity) # Fuzzy match fallback (80% similarity)
ratio = difflib.SequenceMatcher( ratio: float = difflib.SequenceMatcher(
None, None,
session_name.lower(), session_name.lower(),
preferred_name.lower() preferred_name.lower()
@@ -352,22 +420,27 @@ class CrossFitBooker:
logging.error(f"Failed to check session: {str(e)} - Session: {session}") logging.error(f"Failed to check session: {str(e)} - Session: {session}")
return False return False
def run_booking_cycle(self, current_time: datetime): def run_booking_cycle(self, current_time: datetime) -> None:
"""Run one cycle of checking and booking sessions""" """
Run one cycle of checking and booking sessions.
Args:
current_time (datetime): Current time for comparison.
"""
# Calculate date range to check (next 3 days) # Calculate date range to check (next 3 days)
start_date = current_time.date() start_date: date = current_time.date()
end_date = start_date + timedelta(days=3) end_date: date = start_date + timedelta(days=3)
# Get available sessions # Get available sessions
sessions_data = self.get_available_sessions(start_date, end_date) sessions_data: Optional[Dict[str, Any]] = self.get_available_sessions(start_date, end_date)
if not sessions_data or not sessions_data.get("success", False): if not sessions_data or not sessions_data.get("success", False):
logging.error("No sessions available or error fetching sessions - Sessions Data: {sessions_data}") logging.error("No sessions available or error fetching sessions - Sessions Data: {sessions_data}")
return return
activities = sessions_data.get("data", {}).get("activities_calendar", []) activities: List[Dict[str, Any]] = sessions_data.get("data", {}).get("activities_calendar", [])
# Find sessions to book (prefered only) # Find sessions to book (prefered only)
sessions_to_book = [] sessions_to_book: List[Tuple[str, Dict[str, Any]]] = []
for session in activities: for session in activities:
if not self.is_session_bookable(session, current_time): if not self.is_session_bookable(session, current_time):
continue continue
@@ -382,17 +455,19 @@ class CrossFitBooker:
# Book sessions (preferred first) # Book sessions (preferred first)
sessions_to_book.sort(key=lambda x: 0 if x[0] == "Preferred" else 1) sessions_to_book.sort(key=lambda x: 0 if x[0] == "Preferred" else 1)
for session_type, session in sessions_to_book: for session_type, session in sessions_to_book:
session_time = datetime.strptime(session["start_timestamp"], "%Y-%m-%d %H:%M:%S") session_time: datetime = datetime.strptime(session["start_timestamp"], "%Y-%m-%d %H:%M:%S")
logging.info(f"Attempting to book {session_type} session at {session_time} ({session['name_activity']})") logging.info(f"Attempting to book {session_type} session at {session_time} ({session['name_activity']})")
if self.book_session(session["id_activity_calendar"]): if self.book_session(session["id_activity_calendar"]):
logging.info(f"Successfully booked {session_type} session at {session_time}") logging.info(f"Successfully booked {session_type} session at {session_time}")
else: else:
logging.error(f"Failed to book {session_type} session at {session_time} - Session: {session}") logging.error(f"Failed to book {session_type} session at {session_time} - Session: {session}")
def run(self): def run(self) -> None:
"""Main execution loop""" """
Main execution loop.
"""
# Set up timezone # Set up timezone
tz = pytz.timezone(TIMEZONE) tz: pytz.timezone = pytz.timezone(TIMEZONE)
# Initial login # Initial login
if not self.login(): if not self.login():
@@ -401,17 +476,18 @@ class CrossFitBooker:
while True: while True:
try: try:
current_time = datetime.now(tz) current_time: datetime = datetime.now(tz)
logging.info(f"Current time: {current_time}") logging.info(f"Current time: {current_time}")
# Run booking cycle at the target time or if it's a test # Run booking cycle at the target time or if it's a test, with optimized checking
if current_time.strftime("%H:%M") == TARGET_RESERVATION_TIME: if current_time.strftime("%H:%M") == TARGET_RESERVATION_TIME:
self.run_booking_cycle(current_time) self.run_booking_cycle(current_time)
# Wait a minute to avoid checking again immediately # Wait until the next booking window
time.sleep(60) wait_until = current_time + timedelta(minutes=60)
time.sleep((wait_until - current_time).total_seconds())
else: else:
# Check again in 30 seconds # Check again in 5 minutes
time.sleep(30) time.sleep(300)
except Exception as e: except Exception as e:
logging.error(f"Unexpected error in booking cycle: {str(e)} - Traceback: {traceback.format_exc()}") logging.error(f"Unexpected error in booking cycle: {str(e)} - Traceback: {traceback.format_exc()}")
time.sleep(60) # Wait before retrying after error time.sleep(60) # Wait before retrying after error