File size: 1,475 Bytes
4dfeffa | 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 | import re
import logging
from typing import List
from dataclasses import dataclass, field
from bs4 import BeautifulSoup, Tag
from .config import COMPLETED_PATTERN, EMBED_URL_BASE
logger = logging.getLogger(__name__)
ID_RE = re.compile(r"id=(\d+)")
@dataclass
class Activity:
cm_id: int
name: str
completed: bool = False
def parse_grade_report(html: str) -> List[Activity]:
soup = BeautifulSoup(html, "html.parser")
# Try specific selectors first, fall back to generic
rows: List[Tag] = soup.select("table.generaltable tr")
if not rows:
rows = soup.select("table tr")
activities: List[Activity] = []
seen_ids: set = set()
for row in rows:
link = row.select_one('a[href*="mod/h5pactivity"]')
if not link:
continue
href = link.get("href", "")
id_match = ID_RE.search(str(href))
if not id_match:
continue
cm_id = int(id_match.group(1))
if cm_id in seen_ids:
continue
seen_ids.add(cm_id)
name = link.get_text(strip=True)[:80]
# Detect completion: scan all td cells for a numeric score pattern
completed = False
for td in row.select("td"):
txt = td.get_text(strip=True)
if COMPLETED_PATTERN.match(txt):
completed = True
break
activities.append(Activity(cm_id=cm_id, name=name, completed=completed))
return activities
|