refactor: does not notify if no session found
This commit is contained in:
@@ -55,7 +55,7 @@ class CrossFitBooker:
|
||||
if self.auth_token:
|
||||
h["Authorization"] = f"Bearer {self.auth_token}"
|
||||
return h
|
||||
|
||||
|
||||
# Public method expected by tests
|
||||
def get_auth_headers(self) -> Dict[str, str]:
|
||||
"""
|
||||
@@ -173,67 +173,13 @@ class CrossFitBooker:
|
||||
summary = self._fmt_session(s)
|
||||
except Exception:
|
||||
summary = f"{s.get('id_activity_calendar')} {s.get('name_activity')} at {s.get('start_timestamp')}"
|
||||
logging.debug(f"[session] {summary}")
|
||||
logging.debug(f"Session: {summary}")
|
||||
else:
|
||||
logging.debug(f"[get_available_sessions] raw_response_preview={str(r)[:500]}")
|
||||
else:
|
||||
logging.debug("[get_available_sessions] No response (None) from API")
|
||||
return r
|
||||
|
||||
def book_session(self, session_id: str) -> bool:
|
||||
# Debug payload composition (without secrets)
|
||||
safe_user_id = str(self.user_id) if self.user_id else None
|
||||
debug_payload = {
|
||||
**self.mandatory_params,
|
||||
"id_activity_calendar": session_id,
|
||||
"id_user": safe_user_id,
|
||||
"action_by": safe_user_id,
|
||||
"n_guests": "0",
|
||||
"booked_on": "1",
|
||||
"device_type": self.mandatory_params.get("device_type"),
|
||||
"token_present": bool(self.auth_token),
|
||||
}
|
||||
logging.debug(f"[book_session] URL=https://sport.nubapp.com/api/v4/activities/bookActivityCalendar.php "
|
||||
f"method=POST content_type=application/x-www-form-urlencoded "
|
||||
f"keys={list(debug_payload.keys())} "
|
||||
f"id_activity_calendar_present={bool(session_id)} "
|
||||
f"user_id_present={bool(safe_user_id)} token_present={debug_payload['token_present']}")
|
||||
data = {
|
||||
**self.mandatory_params,
|
||||
"id_activity_calendar": session_id,
|
||||
"id_user": self.user_id,
|
||||
"action_by": self.user_id,
|
||||
"n_guests": "0",
|
||||
"booked_on": "1",
|
||||
"device_type": self.mandatory_params["device_type"],
|
||||
"token": self.auth_token
|
||||
}
|
||||
r = self._post("https://sport.nubapp.com/api/v4/activities/bookActivityCalendar.php", data)
|
||||
if r and r.get("success", False):
|
||||
logging.info(f"Successfully booked session {session_id}")
|
||||
return True
|
||||
logging.error(f"Booking failed: {r}" if r is not None else "Booking call failed")
|
||||
return False
|
||||
|
||||
def get_booked_sessions(self) -> List[Dict[str, Any]]:
|
||||
data = {**self.mandatory_params, "id_user": self.user_id, "action_by": self.user_id}
|
||||
r = self._post("https://sport.nubapp.com/api/v4/activities/getBookedActivities.php", data)
|
||||
if r and r.get("success", False):
|
||||
return r.get("data", [])
|
||||
logging.error(f"Failed to retrieve booked sessions: {r}" if r is not None else "Call failed")
|
||||
return []
|
||||
|
||||
def is_session_bookable(self, session: Dict[str, Any], current_time: datetime) -> bool:
|
||||
ui = session.get("user_info", {})
|
||||
if ui.get("can_join", False): return True
|
||||
d, t = ui.get("unableToBookUntilDate", ""), ui.get("unableToBookUntilTime", "")
|
||||
if d and t:
|
||||
try:
|
||||
bd = pytz.timezone(TIMEZONE).localize(datetime.strptime(f"{d} {t}", "%d-%m-%Y %H:%M"))
|
||||
if current_time >= bd: return True
|
||||
except ValueError: pass
|
||||
return False
|
||||
|
||||
def matches_preferred_session(self, session: Dict[str, Any], current_time: datetime) -> bool:
|
||||
try:
|
||||
st = self._parse_local(session["start_timestamp"])
|
||||
@@ -246,77 +192,127 @@ class CrossFitBooker:
|
||||
logging.error(f"Failed to check session: {e} - Session: {session}")
|
||||
return False
|
||||
|
||||
async def run_booking_cycle(self, current_time: datetime) -> None:
|
||||
def is_session_bookable(self, session: Dict[str, Any], current_time: datetime) -> bool:
|
||||
"""
|
||||
Check if a session is bookable based on user_info.
|
||||
"""
|
||||
user_info: Dict[str, Any] = session.get("user_info", {})
|
||||
# First check if can_join is true (primary condition)
|
||||
if user_info.get("can_join", False):
|
||||
return True
|
||||
# If can_join is False, check if there's a booking window
|
||||
booking_date_str: str = user_info.get("unableToBookUntilDate", "")
|
||||
booking_time_str: str = user_info.get("unableToBookUntilTime", "")
|
||||
if booking_date_str and booking_time_str:
|
||||
try:
|
||||
booking_datetime: datetime = datetime.strptime(
|
||||
f"{booking_date_str} {booking_time_str}",
|
||||
"%d-%m-%Y %H:%M"
|
||||
)
|
||||
booking_datetime = pytz.timezone(TIMEZONE).localize(booking_datetime)
|
||||
|
||||
if current_time >= booking_datetime:
|
||||
return True # Booking window is open
|
||||
except ValueError:
|
||||
pass # Ignore invalid date formats
|
||||
# Default case: not bookable
|
||||
logging.debug(f"Session: {session.get('id_activity_calendar')} ({session.get('name_activity')}) is not bookable")
|
||||
return False
|
||||
|
||||
def book_session(self, session_id: str) -> bool:
|
||||
"""
|
||||
Book a specific session.
|
||||
"""
|
||||
url = "https://sport.nubapp.com/api/v4/activities/bookActivityCalendar.php"
|
||||
data = {
|
||||
**self.mandatory_params,
|
||||
"id_activity_calendar": session_id,
|
||||
"id_user": self.user_id,
|
||||
"action_by": self.user_id,
|
||||
"n_guests": "0",
|
||||
"booked_on": "1",
|
||||
"device_type": self.mandatory_params["device_type"],
|
||||
"token": self.auth_token
|
||||
}
|
||||
|
||||
for retry in range(RETRY_MAX):
|
||||
try:
|
||||
response: requests.Response = self.session.post(
|
||||
url,
|
||||
headers=self.get_auth_headers(),
|
||||
data=urlencode(data),
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
json_response: Dict[str, Any] = response.json()
|
||||
if json_response.get("success", False):
|
||||
logging.info(f"Successfully booked session {session_id}")
|
||||
return True
|
||||
else:
|
||||
logging.error(f"API returned success:false: {json_response} - Session ID: {session_id}")
|
||||
return False
|
||||
|
||||
logging.error(f"HTTP {response.status_code}: {response.text[:100]}")
|
||||
return False
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if retry == RETRY_MAX - 1:
|
||||
logging.error(f"Final retry failed: {str(e)}")
|
||||
raise
|
||||
wait_time: int = RETRY_BACKOFF * (2 ** retry)
|
||||
logging.warning(f"Request failed (attempt {retry+1}/{RETRY_MAX}): {str(e)}. Retrying in {wait_time}s...")
|
||||
time.sleep(wait_time)
|
||||
|
||||
logging.error(f"Failed to complete request after {RETRY_MAX} attempts")
|
||||
return False
|
||||
|
||||
# Script main entry point
|
||||
async def execute_cycle(self, current_time: datetime) -> None:
|
||||
start_date, end_date = current_time.date(), current_time.date() + timedelta(days=2)
|
||||
sessions_data = self.get_available_sessions(start_date, end_date)
|
||||
if not sessions_data or not sessions_data.get("success", False):
|
||||
logging.error("No sessions available or error fetching sessions")
|
||||
return
|
||||
activities: List[Dict[str, Any]] = sessions_data.get("data", {}).get("activities_calendar", [])
|
||||
sessions_to_book: List[Tuple[str, Dict[str, Any]]] = []
|
||||
upcoming_sessions: List[Dict[str, Any]] = []
|
||||
found_preferred_sessions: List[Dict[str, Any]] = []
|
||||
found_preferred_sessions: List[Tuple[str, Dict[str, Any]]] = []
|
||||
|
||||
# Debug: list all preferred sessions detected (bookable or not)
|
||||
preferred_debug: List[str] = []
|
||||
|
||||
for s in activities:
|
||||
st = self._parse_local(s["start_timestamp"])
|
||||
days_diff = (st.date() - current_time.date()).days
|
||||
for session in activities:
|
||||
start_timestamp = self._parse_local(session["start_timestamp"])
|
||||
days_diff = (start_timestamp.date() - current_time.date()).days
|
||||
if not (0 <= days_diff <= 2):
|
||||
continue
|
||||
|
||||
is_preferred = self.matches_preferred_session(s, current_time)
|
||||
if is_preferred:
|
||||
# Collect concise summaries to debug output
|
||||
try:
|
||||
preferred_debug.append(self._fmt_session(s, st))
|
||||
except Exception:
|
||||
preferred_debug.append(f"{s.get('id_activity_calendar')} {s.get('name_activity')} at {s.get('start_timestamp')}")
|
||||
is_preferred = self.matches_preferred_session(session, current_time)
|
||||
|
||||
if self.is_session_bookable(s, current_time):
|
||||
if is_preferred:
|
||||
sessions_to_book.append(("Preferred", s))
|
||||
found_preferred_sessions.append(s)
|
||||
else:
|
||||
if is_preferred:
|
||||
found_preferred_sessions.append(s)
|
||||
if days_diff == 1:
|
||||
upcoming_sessions.append(s)
|
||||
if self.is_session_bookable(session, current_time):
|
||||
session_type = "Preferred" if is_preferred else "Regular"
|
||||
found_preferred_sessions.append((session_type, session))
|
||||
|
||||
# Emit debug of preferred sessions
|
||||
if preferred_debug:
|
||||
logging.debug("[preferred_sessions] " + " | ".join(preferred_debug[:50]))
|
||||
else:
|
||||
logging.debug("[preferred_sessions] none found in window")
|
||||
|
||||
if not sessions_to_book and not upcoming_sessions:
|
||||
logging.info("No matching sessions found to book")
|
||||
if not found_preferred_sessions:
|
||||
logging.info("No preferred sessions bookable found in the booking window")
|
||||
return
|
||||
|
||||
for s in found_preferred_sessions:
|
||||
for session_type, s in found_preferred_sessions:
|
||||
details = self._fmt_session(s)
|
||||
await self.notifier.notify_session_booking(details)
|
||||
logging.info(f"Notified about found preferred session: {details}")
|
||||
logging.info(f"Notified about found {session_type.lower()} session: {details}")
|
||||
|
||||
for s in upcoming_sessions:
|
||||
details = self._fmt_session(s)
|
||||
await self.notifier.notify_upcoming_session(details, 1)
|
||||
logging.info(f"Notified about upcoming session: {details}")
|
||||
# Sort by preferred sessions first
|
||||
found_preferred_sessions.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 stype, s in sessions_to_book:
|
||||
st_dt = datetime.strptime(s["start_timestamp"], "%Y-%m-%d %H:%M:%S")
|
||||
logging.info(f"Attempting to book {stype} session at {st_dt} ({s['name_activity']})")
|
||||
if self.book_session(s["id_activity_calendar"]):
|
||||
for session_type, s in found_preferred_sessions:
|
||||
st_dt = self._parse_local(s["start_timestamp"])
|
||||
logging.info(f"Attempting to book {session_type} session at {st_dt} ({s['name_activity']})")
|
||||
if await self.book_session(s["id_activity_calendar"]):
|
||||
details = f"{s['name_activity']} at {st_dt.strftime('%Y-%m-%d %H:%M')}"
|
||||
await self.notifier.notify_session_booking(details)
|
||||
logging.info(f"Successfully booked {stype} session at {st_dt}")
|
||||
logging.info(f"Successfully booked {session_type} session at {st_dt}")
|
||||
else:
|
||||
logging.error(f"Failed to book {stype} session at {st_dt}")
|
||||
logging.error(f"Failed to book {session_type} session at {st_dt}")
|
||||
details = f"{s['name_activity']} at {st_dt.strftime('%Y-%m-%d %H:%M')}"
|
||||
await self.notifier.notify_impossible_booking(details)
|
||||
logging.info(f"Notified about impossible booking for {stype} session at {st_dt}")
|
||||
logging.info(f"Notified about impossible booking for {session_type} session at {st_dt}")
|
||||
|
||||
async def run(self) -> None:
|
||||
tz = pytz.timezone(TIMEZONE)
|
||||
@@ -331,7 +327,7 @@ class CrossFitBooker:
|
||||
now = datetime.now(tz)
|
||||
logging.info(f"Current time: {now}")
|
||||
if target_time <= now <= booking_window_end:
|
||||
await self.run_booking_cycle(now); time.sleep(60)
|
||||
await self.execute_cycle(now); time.sleep(60)
|
||||
else:
|
||||
time.sleep(300)
|
||||
except Exception as e:
|
||||
@@ -340,4 +336,4 @@ class CrossFitBooker:
|
||||
self.quit()
|
||||
|
||||
def quit(self) -> None:
|
||||
logging.info("Script interrupted by user. Quitting..."); exit(0)
|
||||
logging.info("Script interrupted by user. Quitting..."); exit(0)
|
||||
Reference in New Issue
Block a user