forked from broomhead/curlbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleague_client.py
More file actions
332 lines (279 loc) · 12 KB
/
Copy pathleague_client.py
File metadata and controls
332 lines (279 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""
League data client for the club's WordPress site (DataBowl plugin).
The admin "Participants" / DataBowl Schedule & Scores screens read WordPress
post meta on the `leagues` post type. That meta is NOT exposed via REST
(meta keys aren't registered with show_in_rest, and the GF consumer key/secret
do not elevate wp/v2 access). HOWEVER, DataBowl renders the same meta into the
*public* league page HTML — no login required.
So this client:
1. Lists active leagues via wp/v2/leagues (gives id, title, link, day slug).
2. GETs each league's public page and parses two sections:
• "Standings" -> an HTML <table>; data-row count = number of teams.
• "Schedule & Scores"-> one <h6> per draw, e.g.
"June 16, 2026 7:45 pm Griffith - Poklitar - Sheet A ... Sheet D is open."
Date + time come straight from the header; a draw is upcoming when its
date >= today (club timezone). Played draws are in the past.
Sheets used per draw = count("Sheet X") - count("Sheet X is open").
Returns, per league: teams, day, time, ended, and a list of draws (with an
`upcoming` flag and `sheets_used`).
Read-only, unauthenticated. Uses a browser User-Agent so Cloudflare lets it
through (same workaround as gf_client).
"""
from __future__ import annotations
import re
import os
import json
import time
import logging
from datetime import datetime, timezone, timedelta
from typing import Any
import aiohttp
from bs4 import BeautifulSoup
log = logging.getLogger(__name__)
BASE_URL = os.environ.get("SITE_BASE_URL", "https://example.com")
LEAGUES_ENDPOINT = f"{BASE_URL}/wp-json/wp/v2/leagues"
TIMEOUT = aiohttp.ClientTimeout(total=20)
# Club timezone (America/Chicago). CDT = UTC-5 in summer; good enough for a
# date-only "is this draw in the future" comparison. Matches bot.py.
TIMEZONE_OFFSET = -5
# wp `league_category` slug -> day of week (fallback when no draws are listed).
DAY_BY_CATEGORY = {
"sunam": "Sunday",
"sunpm": "Sunday",
"sunday-development": "Sunday",
"tues": "Tuesday",
"thurs": "Thursday",
"friday-tgif": "Friday",
}
_BROWSER_HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/125.0.0.0 Safari/537.36"
),
"Accept": "text/html,application/json",
"Accept-Language": "en-US,en;q=0.9",
}
# "June 16, 2026 7:45 pm" at the start of a draw heading.
_DRAW_RE = re.compile(
r"^\s*([A-Z][a-z]+ \d{1,2},\s*\d{4})\s+(\d{1,2}:\d{2}\s*[ap]\.?m\.?)",
re.IGNORECASE,
)
_SHEET_RE = re.compile(r"Sheet [A-Z]\b", re.IGNORECASE)
_SHEET_OPEN_RE = re.compile(r"Sheet [A-Z]\s+is open", re.IGNORECASE)
def _now_club() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=TIMEZONE_OFFSET)
def _category_slug(league_post: dict) -> str | None:
"""Extract the league_category slug from a wp/v2/leagues post's class_list."""
for cls in league_post.get("class_list", []):
if cls.startswith("league_category-"):
return cls[len("league_category-"):]
return None
def _parse_draw_heading(text: str, today) -> dict | None:
"""Parse one Schedule & Scores <h6> into a draw dict, or None if not a draw."""
text = " ".join(text.split()) # collapse whitespace/newlines
m = _DRAW_RE.match(text)
if not m:
return None
date_str, time_str = m.group(1), m.group(2)
try:
draw_date = datetime.strptime(
re.sub(r"\s+", " ", date_str), "%B %d, %Y"
).date()
except ValueError:
return None
time_norm = time_str.lower().replace(".", "").replace(" ", "") # "7:45pm"
time_pretty = re.sub(r"([ap]m)$", r" \1", time_norm) # "7:45 pm"
sheets_total = len(_SHEET_RE.findall(text))
sheets_open = len(_SHEET_OPEN_RE.findall(text))
sheets_used = max(0, sheets_total - sheets_open)
return {
"date": draw_date.isoformat(),
"weekday": draw_date.strftime("%A"),
"time": time_pretty,
"upcoming": draw_date >= today,
"sheets_used": sheets_used,
}
def parse_league_html(html: str) -> dict[str, Any]:
"""Parse a league page's HTML into structured league info."""
soup = BeautifulSoup(html, "html.parser")
text_all = soup.get_text(" ", strip=True)
ended = "this league has ended" in text_all.lower()
# ── Teams: the Standings table ───────────────────────────────────────────
teams = None
team_names: list[str] = []
for table in soup.find_all("table"):
head = table.get_text(" ", strip=True).lower()
if "team name" in head or "win %" in head:
rows = table.find_all("tr")
data_rows = [
r for r in rows
if r.find_all("td") and not r.find_all("th")
]
teams = len(data_rows)
for r in data_rows:
cells = r.find_all("td")
if len(cells) >= 2:
team_names.append(cells[1].get_text(" ", strip=True))
break
# ── Draws: the Schedule & Scores <h6> headers ────────────────────────────
today = _now_club().date()
draws: list[dict] = []
for h in soup.find_all(["h6", "h5"]):
draw = _parse_draw_heading(h.get_text(" ", strip=True), today)
if draw:
draws.append(draw)
draws.sort(key=lambda d: d["date"])
upcoming = [d for d in draws if d["upcoming"]]
# Day + time: prefer real draw data, fall back to None (caller can use slug).
day = draws[0]["weekday"] if draws else None
time = None
if draws:
# most common time across draws
times = [d["time"] for d in draws if d["time"]]
if times:
time = max(set(times), key=times.count)
return {
"teams": teams,
"team_names": team_names,
"ended": ended,
"day": day,
"time": time,
"draws": draws,
"upcoming_draws": upcoming,
"next_draw": upcoming[0] if upcoming else None,
}
class LeagueClient:
"""Read-only client for the club's league pages."""
def __init__(self):
self._session: aiohttp.ClientSession | None = None
async def __aenter__(self):
self._session = aiohttp.ClientSession(headers=_BROWSER_HEADERS, timeout=TIMEOUT)
return self
async def __aexit__(self, *_):
if self._session:
await self._session.close()
async def active_leagues(self, per_page: int = 20) -> list[dict]:
"""
Return current league posts as lightweight dicts:
{id, title, slug, link, category, day}. Ordered newest-first by WP.
"""
params = {
"_fields": "id,title,slug,link,class_list",
"per_page": per_page,
"status": "publish",
}
async with self._session.get(LEAGUES_ENDPOINT, params=params) as r:
r.raise_for_status()
posts = await r.json()
out = []
for p in posts:
slug = _category_slug(p)
out.append({
"id": p["id"],
"title": p.get("title", {}).get("rendered", ""),
"slug": p.get("slug", ""),
"link": p.get("link", ""),
"category": slug,
"day": DAY_BY_CATEGORY.get(slug),
})
return out
async def league_info(self, link: str) -> dict[str, Any]:
"""Fetch a league page and parse teams / day / time / draws."""
async with self._session.get(link) as r:
r.raise_for_status()
html = await r.text()
return parse_league_html(html)
async def all_active_league_info(self) -> list[dict]:
"""Convenience: active leagues merged with parsed page info."""
leagues = await self.active_leagues()
results = []
for lg in leagues:
try:
info = await self.league_info(lg["link"])
except Exception as e: # noqa: BLE001
log.warning("Failed to parse league %s: %s", lg["link"], e)
info = {}
merged = {**lg, **info}
# Fall back to category-derived day if the page had no draws.
if not merged.get("day"):
merged["day"] = lg["day"]
results.append(merged)
return results
# ── JSON file cache ──────────────────────────────────────────────────────────
# The bot reads from this file instead of hitting the site on every request.
# It self-refreshes lazily: when the file is older than CACHE_TTL (or missing),
# the next call refetches and rewrites it. Override via env vars.
#
# In dev the repo is mounted into the container, so the cache survives restarts.
# In prod (no volume) it's ephemeral — fine, it just refetches once on boot.
# Force a refresh out-of-band with refresh_leagues.py (cron / scheduled task).
CACHE_PATH = os.environ.get("LEAGUE_CACHE_PATH", "league_cache.json")
CACHE_TTL = int(os.environ.get("LEAGUE_CACHE_TTL", "21600")) # seconds (6h)
def _read_cache(path: str, ttl: int) -> list[dict] | None:
"""Return cached leagues if the file exists and is younger than ttl, else None."""
try:
with open(path, "r", encoding="utf-8") as f:
blob = json.load(f)
age = time.time() - float(blob.get("fetched_at", 0))
if age <= ttl:
log.debug("League cache hit (age %.0fs)", age)
return blob.get("leagues")
log.debug("League cache stale (age %.0fs > ttl %ds)", age, ttl)
except (FileNotFoundError, json.JSONDecodeError, ValueError, KeyError):
pass
return None
def _write_cache(path: str, leagues: list[dict]) -> None:
"""Atomically write the cache file."""
payload = {
"fetched_at": time.time(),
"fetched_at_iso": datetime.now(timezone.utc).isoformat(),
"leagues": leagues,
}
tmp = f"{path}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
os.replace(tmp, path)
async def get_cached_leagues(
*, force: bool = False, cache_path: str = CACHE_PATH, ttl: int = CACHE_TTL
) -> list[dict]:
"""
Return active-league info, served from the JSON cache when fresh.
Refetches from the site (and rewrites the cache) when forced, when the
cache is missing, or when it's older than `ttl`. If a refetch fails but a
stale cache exists, the stale data is returned rather than raising.
"""
if not force:
cached = _read_cache(cache_path, ttl)
if cached is not None:
return cached
try:
async with LeagueClient() as lc:
leagues = await lc.all_active_league_info()
_write_cache(cache_path, leagues)
return leagues
except Exception as e: # noqa: BLE001 — fall back to stale cache on network errors
log.warning("League refetch failed (%s); trying stale cache", e)
try:
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f).get("leagues", [])
except (FileNotFoundError, json.JSONDecodeError):
raise e
def draw_to_datetime(draw: dict) -> datetime | None:
"""Combine a draw's date ('YYYY-MM-DD') and time ('7:45 pm') into a datetime."""
date_str = draw.get("date")
time_str = (draw.get("time") or "").strip().upper() # "7:45 PM"
if not date_str:
return None
if not time_str:
return datetime.strptime(date_str, "%Y-%m-%d")
try:
return datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %I:%M %p")
except ValueError:
return datetime.strptime(date_str, "%Y-%m-%d")
def leagues_on_weekday(leagues: list[dict], weekday: str) -> list[dict]:
"""Filter cached leagues to those that play on the given weekday (e.g. 'Tuesday')."""
return [
lg for lg in leagues
if not lg.get("ended") and (lg.get("day") == weekday)
]