feat: retrieve sessions

This commit is contained in:
kbe
2025-07-18 01:44:20 +02:00
parent f0e44cb5ec
commit 7be123c755

View File

@@ -34,14 +34,11 @@ class CrossFitBooker:
self.session = requests.Session() self.session = requests.Session()
self.base_headers = { self.base_headers = {
"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",
"Accept": "application/json, text/plain, */*", "Content-Type": "application/x-www-form-urlencoded",
"Accept-Language": "en-GB,en;q=0.8,fr-FR;q=0.5,fr;q=0.3",
"Nubapp-Origin": "user_apps", "Nubapp-Origin": "user_apps",
"Origin": "https://box.resawod.com",
"Referer": "https://box.resawod.com/",
} }
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 = {
"app_version": APP_VERSION, "app_version": APP_VERSION,
@@ -67,7 +64,7 @@ class CrossFitBooker:
"username": USERNAME, "username": USERNAME,
"password": PASSWORD "password": PASSWORD
} }
response = self.session.post( 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"},
@@ -111,7 +108,7 @@ class CrossFitBooker:
return None return None
url = "https://sport.nubapp.com/api/v4/activities/getActivitiesCalendar.php" url = "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 = self.mandatory_params.copy()
request_data.update({ request_data.update({
@@ -122,11 +119,11 @@ class CrossFitBooker:
try: try:
# Debug output # Debug output
print("\n--- Request Details ---") # print("\n--- Request Details ---")
print(f"URL: {url}") # print(f"URL: {url}")
print(f"Headers: {json.dumps(self.get_auth_headers(), indent=2)}") # print(f"Headers: {json.dumps(self.get_auth_headers(), indent=2)}")
print(f"Payload: {request_data}") # print(f"Payload: {request_data}")
# Make the request # Make the request
response = self.session.post( response = self.session.post(
url, url,
@@ -136,20 +133,16 @@ class CrossFitBooker:
) )
# Debug raw response # Debug raw response
print("\n--- Response ---") # print("\n--- Response ---")
print(f"Status Code: {response.status_code}") # print(f"Status Code: {response.status_code}")
print(f"Headers: {response.headers}") # print(f"Headers: {response.headers}")
print(f"Content: {response.text}") # print(f"Content: {response.text}")
# Handle response # Handle response
if response.status_code == 200: if response.status_code == 200:
try: try:
json_response = response.json() json_response = response.json()
if json_response.get("success", False): return json_response
return json_response
else:
print(f"API reported failure: {json_response.get('message')}")
return None
except ValueError: except ValueError:
print("Failed to decode JSON response") print("Failed to decode JSON response")
return None return None
@@ -172,7 +165,7 @@ class CrossFitBooker:
except Exception as e: except Exception as e:
print(f"Unexpected error: {str(e)}") print(f"Unexpected error: {str(e)}")
return None return None
def book_session(self, session_id: str) -> bool: def book_session(self, session_id: str) -> bool:
"""Book a specific session""" """Book a specific session"""
if not self.auth_token or not self.user_id: if not self.auth_token or not self.user_id:
@@ -191,7 +184,7 @@ class CrossFitBooker:
"https://sport.nubapp.com/api/v4/activities/bookActivity.php", "https://sport.nubapp.com/api/v4/activities/bookActivity.php",
headers=self.get_auth_headers(), headers=self.get_auth_headers(),
data=urlencode(request_data)) data=urlencode(request_data))
if response.ok: if response.ok:
print(f"Successfully booked session {session_id}") print(f"Successfully booked session {session_id}")
return True return True
@@ -205,15 +198,15 @@ class CrossFitBooker:
def is_session_bookable(self, session: Dict, current_time: datetime) -> bool: def is_session_bookable(self, session: Dict, current_time: datetime) -> bool:
"""Check if a session is bookable based on user_info""" """Check if a session is bookable based on user_info"""
user_info = session.get("user_info", {}) user_info = session.get("user_info", {})
# First check if can_join is true # First check if can_join is true
if user_info.get("can_join", False): if user_info.get("can_join", False):
return True return True
# Otherwise check booking availability time # Otherwise check booking availability time
booking_date_str = user_info.get("unableToBookUntilDate", "") booking_date_str = user_info.get("unableToBookUntilDate", "")
booking_time_str = user_info.get("unableToBookUntilTime", "") booking_time_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(f"{booking_date_str} {booking_time_str}", "%d-%m-%Y %H:%M") booking_datetime = datetime.strptime(f"{booking_date_str} {booking_time_str}", "%d-%m-%Y %H:%M")
@@ -228,21 +221,21 @@ class CrossFitBooker:
try: try:
session_time = datetime.strptime(session["start_datetime"], "%Y-%m-%d %H:%M:%S") session_time = datetime.strptime(session["start_datetime"], "%Y-%m-%d %H:%M:%S")
session_time = pytz.timezone(TIMEZONE).localize(session_time) session_time = pytz.timezone(TIMEZONE).localize(session_time)
# Check if session is exactly 2 days from now # Check if session is exactly 2 days from now
two_days_from_now = current_time + timedelta(days=2) two_days_from_now = current_time + timedelta(days=2)
if session_time.date() != two_days_from_now.date(): if session_time.date() != two_days_from_now.date():
return False return False
# Get day of week (0=Monday, 6=Sunday) and time # Get day of week (0=Monday, 6=Sunday) and time
day_of_week = session_time.weekday() day_of_week = session_time.weekday()
session_time_str = session_time.strftime("%H:%M") session_time_str = session_time.strftime("%H:%M")
session_name = session.get("name_activity", "").upper() session_name = session.get("name_activity", "").upper()
# Check against preferred sessions # Check against preferred sessions
for preferred_day, preferred_time, preferred_name in PREFERRED_SESSIONS: for preferred_day, preferred_time, preferred_name in PREFERRED_SESSIONS:
if (day_of_week == preferred_day and if (day_of_week == preferred_day and
session_time_str == preferred_time and session_time_str == preferred_time and
preferred_name in session_name): preferred_name in session_name):
return True return True
return False return False
@@ -256,31 +249,31 @@ class CrossFitBooker:
# Calculate date range to check (next 3 days) # Calculate date range to check (next 3 days)
start_date = current_time.date() start_date = current_time.date()
end_date = start_date + timedelta(days=3) end_date = start_date + timedelta(days=3)
# Get available sessions # Get available sessions
sessions_data = self.get_available_sessions(start_date, end_date) sessions_data = 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):
print("No sessions available or error fetching sessions") print("No sessions available or error fetching sessions")
return return
activities = sessions_data.get("data", {}).get("activities_calendar", []) activities = sessions_data.get("data", {}).get("activities_calendar", [])
# Find sessions to book (both preferred and any available) # Find sessions to book (both preferred and any available)
sessions_to_book = [] sessions_to_book = []
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
if self.matches_preferred_session(session, current_time): if self.matches_preferred_session(session, current_time):
sessions_to_book.append(("Preferred", session)) sessions_to_book.append(("Preferred", session))
elif current_time.strftime("%H:%M") == TARGET_RESERVATION_TIME: elif current_time.strftime("%H:%M") == TARGET_RESERVATION_TIME:
# At booking time, consider all available sessions # At booking time, consider all available sessions
sessions_to_book.append(("Available", session)) sessions_to_book.append(("Available", session))
if not sessions_to_book: if not sessions_to_book:
print("No matching sessions found to book") print("No matching sessions found to book")
return return
# 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:
@@ -295,16 +288,16 @@ class CrossFitBooker:
"""Main execution loop""" """Main execution loop"""
# Set up timezone # Set up timezone
tz = pytz.timezone(TIMEZONE) tz = pytz.timezone(TIMEZONE)
# Initial login # Initial login
if not self.login(): if not self.login():
print("Failed to login, exiting") print("Failed to login, exiting")
return return
while True: while True:
current_time = datetime.now(tz) current_time = datetime.now(tz)
print(f"\nCurrent time: {current_time}") print(f"\nCurrent 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
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)
@@ -320,4 +313,4 @@ if __name__ == "__main__":
sessions = booker.get_available_sessions(datetime.strptime("21-07-2025", "%d-%m-%Y"), datetime.strptime("27-07-2025", "%d-%m-%Y")) sessions = booker.get_available_sessions(datetime.strptime("21-07-2025", "%d-%m-%Y"), datetime.strptime("27-07-2025", "%d-%m-%Y"))
# print(sessions) # print(sessions)
# booker.run_booking_cycle(datetime.now()) # booker.run_booking_cycle(datetime.now())
# booker.run() # booker.run()