#!/usr/bin/env python3 from __future__ import annotations import html import json import os import re import threading import time from datetime import datetime, timezone from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.error import URLError from urllib.parse import parse_qs, urlparse from urllib.request import Request, urlopen from dotenv import load_dotenv from analyze import get_json, parse_form from notify_interesting_matches import ENV_FILE, InterestingMatch, collect_interesting_matches, top_teams_for_league from send_demo_model_style import generate_card from send_safe_matches_image import CARDS_DIR, send_photo, to_card_match HOST = "127.0.0.1" PORT = 8012 CARD_PATH = CARDS_DIR / "web_safe_matches_card.png" ICON_PATH = CARDS_DIR / "gabfoot_icon.png" SITE_ASSETS_DIR = Path(__file__).resolve().parent / "site_assets" DASHBOARD_HERO_IMAGE_PATH = SITE_ASSETS_DIR / "dashboard-hero.jpg" BOTOLA_LEAGUE_ID = 530 TEAM_CACHE: dict[int, dict] = {} APP_CACHE_DIR = Path(__file__).resolve().parent / ".cache" DASHBOARD_CACHE_FILE = APP_CACHE_DIR / "dashboard_cache.json" PREFERRED_PUBLIC_URL_FILE = APP_CACHE_DIR / "preferred_public_url.txt" DASHBOARD_CACHE_TTL_SECONDS = 15 * 60 DASHBOARD_CACHE_STALE_SECONDS = 6 * 3600 _DASHBOARD_CACHE: dict[str, dict[str, object]] = {} _CACHE_LOCK = threading.Lock() _REFRESH_IN_FLIGHT: set[str] = set() ARTICLE_IMAGE_CACHE: dict[str, str] = {} ARTICLE_IMAGE_LOCK = threading.Lock() ARTICLE_IMAGE_FETCH_ENABLED = os.getenv("GABFOOT_FETCH_ARTICLE_IMAGES", "").strip() == "1" UPDATES_FILE = Path(__file__).resolve().parent / "updates.json" def configured_public_url() -> str: candidates = [ os.getenv("GABFOOT_PUBLIC_URL", "").strip(), os.getenv("GABFOOT_SITE_URL", "").strip(), ] if PREFERRED_PUBLIC_URL_FILE.exists(): try: candidates.append(PREFERRED_PUBLIC_URL_FILE.read_text().strip()) except OSError: pass for candidate in candidates: if candidate.startswith("http://") or candidate.startswith("https://"): return candidate.rstrip("/") return "" def load_site_updates() -> list[dict[str, object]]: try: payload = json.loads(UPDATES_FILE.read_text(encoding="utf-8")) except OSError: return [] except json.JSONDecodeError: return [] if not isinstance(payload, list): return [] cleaned: list[dict[str, object]] = [] for entry in payload: if not isinstance(entry, dict): continue bullets = entry.get("bullets", []) if not isinstance(bullets, list): bullets = [] cleaned.append( { "date": str(entry.get("date", "")).strip(), "label": str(entry.get("label", "Produit")).strip() or "Produit", "title": str(entry.get("title", "")).strip(), "summary": str(entry.get("summary", "")).strip(), "bullets": [str(bullet).strip() for bullet in bullets if str(bullet).strip()], } ) return cleaned def request_scheme(handler: BaseHTTPRequestHandler) -> str: forwarded = handler.headers.get("X-Forwarded-Proto", "").split(",")[0].strip().lower() if forwarded in {"http", "https"}: return forwarded if os.getenv("PORT"): return "https" return "http" def request_host(handler: BaseHTTPRequestHandler) -> str: forwarded = handler.headers.get("X-Forwarded-Host", "").split(",")[0].strip() if forwarded: return forwarded host = handler.headers.get("Host", "").split(",")[0].strip() if host: return host return f"{HOST}:{PORT}" def request_base_url(handler: BaseHTTPRequestHandler) -> str: configured = configured_public_url() if configured: return configured return f"{request_scheme(handler)}://{request_host(handler)}" def absolute_url(base_url: str, path: str) -> str: normalized = path if path.startswith("/") else f"/{path}" return f"{base_url.rstrip('/')}{normalized}" def dashboard_cache_key(limit: int, min_percent: int) -> str: return f"{limit}:{min_percent}" def serialize_match(match: InterestingMatch) -> dict[str, object]: return { "match_id": match.match_id, "league_id": match.league_id, "league_name": match.league_name, "tournament_name": match.tournament_name, "kickoff_utc": match.kickoff_utc, "page_url": match.page_url, "home_name": match.home_name, "away_name": match.away_name, "home_id": match.home_id, "away_id": match.away_id, "home_form": match.home_form, "away_form": match.away_form, "home_points": match.home_points, "away_points": match.away_points, "home_history_score": match.home_history_score, "away_history_score": match.away_history_score, "h2h_edge": match.h2h_edge, "injuries_edge": match.injuries_edge, "home_rank": match.home_rank, "away_rank": match.away_rank, "home_goals_per_match": match.home_goals_per_match, "away_goals_per_match": match.away_goals_per_match, "home_conceded_per_match": match.home_conceded_per_match, "away_conceded_per_match": match.away_conceded_per_match, "home_key_player": match.home_key_player, "away_key_player": match.away_key_player, "prediction": match.prediction, "confidence": match.confidence, "sureness_percent": match.sureness_percent, "consensus_notes": match.consensus_notes, "interest_score": match.interest_score, "why": match.why, } def deserialize_match(payload: dict[str, object]) -> InterestingMatch: return InterestingMatch(**payload) def load_dashboard_cache() -> None: if not DASHBOARD_CACHE_FILE.exists(): return try: payload = json.loads(DASHBOARD_CACHE_FILE.read_text()) except Exception: return if not isinstance(payload, dict): return for key, entry in payload.items(): if isinstance(entry, dict): _DASHBOARD_CACHE[key] = entry def persist_dashboard_cache() -> None: APP_CACHE_DIR.mkdir(parents=True, exist_ok=True) DASHBOARD_CACHE_FILE.write_text(json.dumps(_DASHBOARD_CACHE, ensure_ascii=True, indent=2)) def compute_dashboard_payload(limit: int, min_percent: int) -> dict[str, object]: matches, card_path = build_card(limit=limit, min_percent=min_percent) botola = safe_botola_predictions() tennis = safe_tennis_world_matches() articles = safe_football_articles(matches, botola) return { "updated_at": time.time(), "limit": limit, "min_percent": min_percent, "has_card": bool(card_path and card_path.exists()), "matches": [serialize_match(match) for match in matches], "botola": botola, "tennis": tennis, "articles": articles, } def refresh_dashboard_cache(limit: int, min_percent: int) -> None: key = dashboard_cache_key(limit, min_percent) try: payload = compute_dashboard_payload(limit=limit, min_percent=min_percent) with _CACHE_LOCK: _DASHBOARD_CACHE[key] = payload persist_dashboard_cache() finally: with _CACHE_LOCK: _REFRESH_IN_FLIGHT.discard(key) def ensure_dashboard_refresh(limit: int, min_percent: int) -> None: key = dashboard_cache_key(limit, min_percent) with _CACHE_LOCK: if key in _REFRESH_IN_FLIGHT: return _REFRESH_IN_FLIGHT.add(key) thread = threading.Thread(target=refresh_dashboard_cache, args=(limit, min_percent), daemon=True) thread.start() def get_cached_dashboard_payload(limit: int, min_percent: int) -> tuple[dict[str, object] | None, bool]: key = dashboard_cache_key(limit, min_percent) now = time.time() with _CACHE_LOCK: entry = _DASHBOARD_CACHE.get(key) if entry: age = now - float(entry.get("updated_at", 0)) if age <= DASHBOARD_CACHE_TTL_SECONDS: return entry, False if age <= DASHBOARD_CACHE_STALE_SECONDS: ensure_dashboard_refresh(limit=limit, min_percent=min_percent) return entry, True ensure_dashboard_refresh(limit=limit, min_percent=min_percent) return None, True def get_fresh_dashboard_payload(limit: int, min_percent: int) -> dict[str, object]: payload = compute_dashboard_payload(limit=limit, min_percent=min_percent) key = dashboard_cache_key(limit, min_percent) with _CACHE_LOCK: _DASHBOARD_CACHE[key] = payload persist_dashboard_cache() return payload def get_team_payload(team_id: int) -> dict: if team_id not in TEAM_CACHE: TEAM_CACHE[team_id] = get_json(f"https://www.fotmob.com/api/teams?id={team_id}", timeout=35) return TEAM_CACHE[team_id] def find_meta_image(page_html: str) -> str: patterns = ( r']+property=["\']og:image["\'][^>]+content=["\']([^"\']+)', r']+content=["\']([^"\']+)["\'][^>]+property=["\']og:image["\']', r']+name=["\']twitter:image["\'][^>]+content=["\']([^"\']+)', r']+content=["\']([^"\']+)["\'][^>]+name=["\']twitter:image["\']', ) for pattern in patterns: match = re.search(pattern, page_html, re.IGNORECASE) if match: return html.unescape(match.group(1)).strip() return "" def resolve_article_image(article_url: str, fallback: str = "") -> str: article_url = article_url.strip() if not article_url: return fallback with ARTICLE_IMAGE_LOCK: if article_url in ARTICLE_IMAGE_CACHE: cached = ARTICLE_IMAGE_CACHE[article_url] return cached or fallback # Avoid blocking public routes on third-party article pages unless explicitly enabled. if not ARTICLE_IMAGE_FETCH_ENABLED: return fallback image_url = "" try: request = Request( article_url, headers={ "User-Agent": ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" ) }, ) with urlopen(request, timeout=3) as response: payload = response.read(300_000).decode("utf-8", "ignore") image_url = find_meta_image(payload) except (TimeoutError, URLError, ValueError, OSError): image_url = "" with ARTICLE_IMAGE_LOCK: ARTICLE_IMAGE_CACHE[article_url] = image_url return image_url or fallback def form_points(record: str) -> int: score = 0 for part in record.split(): if part.endswith("G"): score += int(part[:-1]) * 3 elif part.endswith("N"): score += int(part[:-1]) return score def botola_predictions(limit: int = 6) -> list[dict[str, object]]: payload = get_json(f"https://www.fotmob.com/api/leagues?id={BOTOLA_LEAGUE_ID}", timeout=40) table_rows = (payload.get("table") or [{}])[0].get("data", {}).get("table", {}).get("all", []) standings = {int(row["id"]): row for row in table_rows if row.get("id")} all_matches = payload.get("fixtures", {}).get("allMatches", []) pending = [match for match in all_matches if not match.get("status", {}).get("finished")] pending.sort(key=lambda item: item.get("status", {}).get("utcTime", "")) out: list[dict[str, object]] = [] for match in pending[:limit]: home = match.get("home", {}) away = match.get("away", {}) home_id = int(home.get("id", 0)) away_id = int(away.get("id", 0)) if not home_id or not away_id: continue home_payload = get_team_payload(home_id) away_payload = get_team_payload(away_id) home_record = parse_form(home_payload)["record"] away_record = parse_form(away_payload)["record"] home_row = standings.get(home_id, {}) away_row = standings.get(away_id, {}) home_score = ( form_points(home_record) + int(home_row.get("pts", 0)) + int(home_row.get("goalConDiff", 0)) + 2 ) away_score = ( form_points(away_record) + int(away_row.get("pts", 0)) + int(away_row.get("goalConDiff", 0)) ) delta = home_score - away_score if delta >= 6: prediction = "1" elif delta <= -6: prediction = "2" else: prediction = "X" confidence = max(54, min(84, 56 + abs(delta) * 2)) why = [] if home_row.get("idx") and away_row.get("idx"): why.append(f"Classement {home_row.get('idx')}e vs {away_row.get('idx')}e") if form_points(home_record) != form_points(away_record): side = home.get("shortName") if form_points(home_record) > form_points(away_record) else away.get("shortName") why.append(f"Forme recente pour {side}") if int(home_row.get("goalConDiff", 0)) != int(away_row.get("goalConDiff", 0)): side = home.get("shortName") if int(home_row.get("goalConDiff", 0)) > int(away_row.get("goalConDiff", 0)) else away.get("shortName") why.append(f"Difference de buts favorable a {side}") out.append( { "kickoff": fmt_kickoff(match.get("status", {}).get("utcTime", "")), "home": home.get("name", ""), "away": away.get("name", ""), "homeId": home_id, "awayId": away_id, "prediction": prediction, "confidence": confidence, "homeRecord": home_record, "awayRecord": away_record, "homeRank": home_row.get("idx"), "awayRank": away_row.get("idx"), "why": why[:3], "status": match.get("status", {}).get("reason", {}).get("short", ""), } ) return out def tennis_world_matches(limit: int = 8) -> list[dict[str, object]]: out: list[dict[str, object]] = [] for circuit in ("atp", "wta"): payload = get_json(f"https://site.api.espn.com/apis/site/v2/sports/tennis/{circuit}/scoreboard", timeout=40) for event in payload.get("events", [])[:2]: tournament = event.get("name") or event.get("shortName") or circuit.upper() for grouping in event.get("groupings", []): for competition in grouping.get("competitions", [])[:4]: status = competition.get("status", {}).get("type", {}) competitors = competition.get("competitors", []) if len(competitors) < 2: continue players = sorted(competitors, key=lambda item: item.get("order", 99)) p1 = players[0].get("athlete", {}).get("displayName", "Joueur 1") p2 = players[1].get("athlete", {}).get("displayName", "Joueur 2") lines1 = "-".join(str(int(s.get("value", 0))) for s in players[0].get("linescores", []) if s.get("value") is not None) or "-" lines2 = "-".join(str(int(s.get("value", 0))) for s in players[1].get("linescores", []) if s.get("value") is not None) or "-" venue = competition.get("venue", {}) out.append( { "tour": circuit.upper(), "tournament": tournament, "group": grouping.get("grouping", {}).get("displayName", ""), "player1": p1, "player2": p2, "score": f"{lines1} / {lines2}", "status": status.get("shortDetail") or status.get("description") or "", "state": status.get("state", ""), "venue": venue.get("fullName", ""), "court": venue.get("court", ""), } ) if len(out) >= limit: return out return out[:limit] def safe_botola_predictions(limit: int = 6) -> list[dict[str, object]]: try: return botola_predictions(limit=limit) except Exception: return [] def safe_tennis_world_matches(limit: int = 8) -> list[dict[str, object]]: try: return tennis_world_matches(limit=limit) except Exception: return [] def football_articles(matches: list[InterestingMatch], botola: list[dict[str, object]], limit: int = 12) -> list[dict[str, str]]: seen_team_ids: list[int] = [] for match in matches[:4]: for team_id in (match.home_id, match.away_id): if team_id not in seen_team_ids: seen_team_ids.append(team_id) for match in botola[:4]: for team_id in (int(match.get("homeId", 0)), int(match.get("awayId", 0))): if team_id and team_id not in seen_team_ids: seen_team_ids.append(team_id) seen_articles: set[str] = set() articles: list[dict[str, str]] = [] for team_id in seen_team_ids: payload = get_team_payload(team_id) team_name = payload.get("details", {}).get("name", "") team_logo = ( payload.get("details", {}).get("sportsTeamJSONLD", {}).get("logo") or payload.get("details", {}).get("logo") or "" ) items = (payload.get("overview", {}).get("newsSummary") or {}).get("items", []) for item in items[:4]: source = item.get("source", {}) or {} url = str(source.get("uri", "")).strip() title = str(source.get("title", "")).strip() summary = str(item.get("summary", "")).strip() source_name = str(source.get("sourceName", "Source")).strip() key = url or title if not key or key in seen_articles: continue seen_articles.add(key) article_image = resolve_article_image(url, fallback=str(team_logo).strip()) articles.append( { "team": team_name, "title": title or "Article football", "summary": summary or "Resume indisponible.", "url": url, "source": source_name, "image": article_image, "logo": str(team_logo).strip(), } ) if len(articles) >= limit: return articles return articles def safe_football_articles(matches: list[InterestingMatch], botola: list[dict[str, object]], limit: int = 12) -> list[dict[str, str]]: try: return football_articles(matches, botola, limit=limit) except Exception: return [] def interaction_script() -> str: return """ """ def render_pick_badge(prediction: str, percent: int) -> str: return f"""
{html.escape(prediction)} {percent}%
""" def render_favorite_button( match_id: int, title: str, kickoff: str, prediction: str, percent: int, detail_url: str, ) -> str: return f""" """ def pick_theme(prediction: str) -> str: normalized = prediction.strip().upper() if "1" in normalized and "2" not in normalized and "X" not in normalized: return "pick-home" if "2" in normalized and "1" not in normalized and "X" not in normalized: return "pick-away" if "X" in normalized and "1" not in normalized and "2" not in normalized: return "pick-draw" return "pick-mixed" def confidence_theme(percent: int) -> str: if percent >= 85: return "confidence-elite" if percent >= 75: return "confidence-strong" return "confidence-medium" def render_confidence_meter(percent: int) -> str: width = max(10, min(100, percent)) return f"""
""" def fmt_kickoff(kickoff_utc: str) -> str: dt = datetime.fromisoformat(kickoff_utc.replace("Z", "+00:00")) return dt.astimezone().strftime("%d/%m/%Y %H:%M") def parse_kickoff(kickoff_utc: str) -> datetime: return datetime.fromisoformat(kickoff_utc.replace("Z", "+00:00")).astimezone() def build_card(limit: int, min_percent: int) -> tuple[list[InterestingMatch], Path | None]: matches = collect_interesting_matches(limit=limit, min_percent=min_percent) if not matches: return matches, None CARDS_DIR.mkdir(parents=True, exist_ok=True) batch = [to_card_match(match) for match in matches[:6]] generate_card(batch, title=f"Matchs surs {min_percent}%+", out_path=str(CARD_PATH)) return matches, CARD_PATH def render_prediction_table(matches: list[InterestingMatch]) -> str: grouped_rows: dict[str, list[str]] = {} ordered_slots: list[str] = [] for match in sorted(matches, key=lambda item: parse_kickoff(item.kickoff_utc)): kickoff = parse_kickoff(match.kickoff_utc) kickoff_label = kickoff.strftime("%d/%m/%Y %H:%M") slot = kickoff.strftime("%d/%m/%Y • %H:00") why = " • ".join(match.why[:2]) or "Analyse disponible" consensus = " / ".join(match.consensus_notes[:2]) or "Consensus stable" pick_class = pick_theme(match.prediction) confidence_class = confidence_theme(match.sureness_percent) favorite_button = render_favorite_button( match.match_id, f"{match.home_name} vs {match.away_name}", kickoff_label, match.prediction, match.sureness_percent, f"/match/{match.match_id}", ) row = ( f"""
{kickoff.strftime("%H:%M")}
{kickoff.strftime("%d/%m/%Y")}
{html.escape(match.tournament_name)}
{html.escape(match.home_name)} vs {html.escape(match.away_name)}
{html.escape(why)}
Voir l'analyse{favorite_button}
{html.escape(match.prediction)}
{match.sureness_percent}% fiable
{render_confidence_meter(match.sureness_percent)}
{html.escape(match.home_form)} | {html.escape(match.away_form)}
Classement {match.home_rank or '-'} / {match.away_rank or '-'}
Hist. {match.home_history_score:.2f} / {match.away_history_score:.2f}
H2H {match.h2h_edge:+.2f} | Abs. {match.injuries_edge:+.2f}
{html.escape(match.home_key_player)} | {html.escape(match.away_key_player)}
{html.escape(consensus)}
{html.escape(' • '.join(match.why))}
Buts {match.home_goals_per_match:.2f} / {match.away_goals_per_match:.2f}
Def. {match.home_conceded_per_match:.2f} / {match.away_conceded_per_match:.2f}
""" ) if slot not in grouped_rows: grouped_rows[slot] = [] ordered_slots.append(slot) grouped_rows[slot].append(row) if not ordered_slots: return '' bodies = [] for slot in ordered_slots: bodies.append( f""" Heure des matchs : {html.escape(slot)} {''.join(grouped_rows[slot])} """ ) return f"""
{''.join(bodies)}
Heure Match Pick Forme Stats Joueurs / Consensus Details match
""" def render_mobile_pick_cards(matches: list[InterestingMatch]) -> str: if not matches: return '' cards: list[str] = [] for match in matches: cards.append( f"""
{html.escape(match.tournament_name)}
{html.escape(fmt_kickoff(match.kickoff_utc))}
{match.sureness_percent}% {html.escape(match.prediction)}

{html.escape(match.home_name)} vs {html.escape(match.away_name)}

{html.escape(' • '.join(match.why[:2]))}

Voir la fiche match
""" ) return "".join(cards) def render_botola_table(botola: list[dict[str, object]]) -> str: grouped_rows: dict[str, list[str]] = {} ordered_slots: list[str] = [] for match in botola: kickoff_text = str(match["kickoff"]) slot = kickoff_text[:13].replace(" ", " • ") if len(kickoff_text) >= 13 else kickoff_text prediction = str(match["prediction"]) confidence = int(match["confidence"]) pick_class = pick_theme(prediction) confidence_class = confidence_theme(confidence) row = ( f"""
{html.escape(kickoff_text[-5:] if len(kickoff_text) >= 5 else kickoff_text)}
{html.escape(kickoff_text[:-6] if len(kickoff_text) > 6 else kickoff_text)}
Botola Pro
{html.escape(str(match['home']))} vs {html.escape(str(match['away']))}
{html.escape(' • '.join(match['why']))}
{html.escape(prediction)}
{confidence}% confiance
{render_confidence_meter(confidence)}
{html.escape(str(match['homeRecord']))} | {html.escape(str(match['awayRecord']))}
Rang {match['homeRank'] or '-'} / {match['awayRank'] or '-'}
Etat {html.escape(str(match['status'])) or 'A venir'}
""" ) if slot not in grouped_rows: grouped_rows[slot] = [] ordered_slots.append(slot) grouped_rows[slot].append(row) if not ordered_slots: return '' bodies = [] for slot in ordered_slots: bodies.append( f""" Heure des matchs : {html.escape(slot)} {''.join(grouped_rows[slot])} """ ) return f"""
{''.join(bodies)}
Horaire Match Pronostic Lecture rapide
""" def render_tennis_table(tennis: list[dict[str, object]]) -> str: grouped_rows: dict[str, list[str]] = {} ordered_slots: list[str] = [] for item in tennis: status = str(item.get("status", "")).strip() slot = status[:16] if status else str(item.get("tournament", "ATP/WTA")) row = ( f"""
{html.escape(str(item['tour']))}
{html.escape(str(item['group']))}
{html.escape(str(item['tournament']))}
{html.escape(str(item['player1']))} vs {html.escape(str(item['player2']))}
{html.escape(str(item['score'])[:1] if str(item['score']) else '-')}
{html.escape(status or 'En cours')}
{render_confidence_meter(68)}
Score {html.escape(str(item['score']))}
Lieu {html.escape(str(item['venue']))}{' | ' + html.escape(str(item['court'])) if item['court'] else ''}
""" ) if slot not in grouped_rows: grouped_rows[slot] = [] ordered_slots.append(slot) grouped_rows[slot].append(row) if not ordered_slots: return '' bodies = [] for slot in ordered_slots: bodies.append( f""" Heure / statut : {html.escape(slot)} {''.join(grouped_rows[slot])} """ ) return f"""
{''.join(bodies)}
Circuit Match Score / Etat Details
""" def render_articles_grid(articles: list[dict[str, str]]) -> str: cards = [] for item in articles: image = str(item.get("image", "")).strip() visual = ( f'{html.escape(item[' if image else '
GABFOOT
' ) logo = str(item.get("logo", "")).strip() badge = ( f'{html.escape(item[' if logo else '
GF
' ) link = ( f'Lire l'article' if item.get("url") else "" ) cards.append( f"""
{visual}
{badge}
Football News

{html.escape(item['title'])}

{html.escape(item['team'])} • {html.escape(item['source'])}

{html.escape(item['summary'])}

{link}
""" ) return "".join(cards) or '' def render_market_strip(matches: list[InterestingMatch], botola: list[dict[str, object]]) -> str: pills = [] for match in matches[:4]: pills.append( f"""
{html.escape(match.home_name)} - {html.escape(match.away_name)} {html.escape(match.prediction)} • {match.sureness_percent}%
""" ) for match in botola[:3]: prediction = str(match.get("prediction", "")) confidence = int(match.get("confidence", 0)) pills.append( f"""
Botola • {html.escape(str(match.get("home", "")))} - {html.escape(str(match.get("away", "")))} {html.escape(prediction)} • {confidence}%
""" ) return "".join(pills) def render_landing_pick_cards(matches: list[InterestingMatch]) -> str: cards: list[str] = [] for match in matches[:3]: consensus = " / ".join(match.consensus_notes[:2]) if match.consensus_notes else "Lecture premium en cours." why = " • ".join(match.why[:2]) if match.why else "Forme, classement et momentum croises." cards.append( f"""
{html.escape(fmt_kickoff(match.kickoff_utc))}

{html.escape(match.home_name)} vs {html.escape(match.away_name)}

{html.escape(match.tournament_name)}
{render_pick_badge(match.prediction, match.sureness_percent)}

{html.escape(why)}

{html.escape(consensus)} Voir la fiche
""" ) return "".join(cards) or '
Les premiers signaux apparaitront ici des que le prochain scan sera termine.
' def render_landing_article_teasers(articles: list[dict[str, str]]) -> str: cards: list[str] = [] for item in articles[:3]: image = str(item.get("image", "")).strip() visual = ( f'{html.escape(item[' if image else '
NEWS
' ) link = ( f'Lire' if item.get("url") else "" ) cards.append( f"""
{visual}
{html.escape(item.get("source", "Football News"))}

{html.escape(item["title"])}

{html.escape(item["summary"])}

{html.escape(item["team"])} {link}
""" ) return "".join(cards) or '
Les articles clubs et joueurs seront affiches ici.
' def render_landing_update_teasers(updates: list[dict[str, object]]) -> str: cards: list[str] = [] for item in updates[:3]: bullets = item.get("bullets", []) bullet_line = " • ".join(str(bullet) for bullet in bullets[:2]) cards.append( f"""
UPDATE
{html.escape(str(item.get("label", "Produit")))} • {html.escape(str(item.get("date", "")))}

{html.escape(str(item.get("title", "")))}

{html.escape(str(item.get("summary", "")))}

{html.escape(bullet_line)} Voir
""" ) return "".join(cards) or '
Les prochaines mises a jour du produit apparaitront ici.
' def landing_html( matches: list[InterestingMatch], card_path: Path | None, limit: int, min_percent: int, notice: str = "", botola: list[dict[str, object]] | None = None, tennis: list[dict[str, object]] | None = None, articles: list[dict[str, str]] | None = None, site_url: str = "", ) -> str: site_updates = load_site_updates() botola = botola or [] tennis = tennis or [] articles = articles or [] featured_match = matches[0] if matches else None featured_article = articles[0] if articles else None avg_confidence = int(round(sum(match.sureness_percent for match in matches) / len(matches))) if matches else 0 updated_at = datetime.now(timezone.utc).strftime("%d/%m/%Y %H:%M UTC") site_url = site_url.rstrip("/") canonical_url = f"{site_url}/" if site_url else "" icon_url = absolute_url(site_url, "/icon.png") if site_url else "/icon.png" canonical_tag = f'' if canonical_url else "" og_url_tag = f'' if canonical_url else "" notice_html = f'
{html.escape(notice)}
' if notice else "" poster_visual = ( 'Affiche Telegram GABFOOT' if card_path and card_path.exists() else '
Poster Telegram pret a sortir
' ) market_strip = render_market_strip(matches, botola) featured_match_html = "" if featured_match: featured_match_html = f"""
Signal principal

{html.escape(featured_match.home_name)} vs {html.escape(featured_match.away_name)}

{html.escape(featured_match.tournament_name)} • {html.escape(fmt_kickoff(featured_match.kickoff_utc))}
{html.escape(featured_match.prediction)} • {featured_match.sureness_percent}% {html.escape(featured_match.home_form)} | {html.escape(featured_match.away_form)}

{html.escape(' • '.join(featured_match.why[:3]))}

Voir la lecture complete
""" featured_article_html = "" if featured_article: article_image = str(featured_article.get("image", "")).strip() article_visual = ( f'{html.escape(featured_article[' if article_image else '
NEWS
' ) article_link = ( f'Lire l'article' if featured_article.get("url") else "" ) featured_article_html = f"""
{article_visual}
Pulse editorial

{html.escape(featured_article["title"])}

{html.escape(featured_article["summary"])}

{html.escape(featured_article["team"])} • {html.escape(featured_article["source"])}
{article_link}
""" return f""" GABFOOT | Studio Pronostics Foot {og_url_tag} {canonical_tag}
Football signal studio

Des pronostics foot plus propres, plus premium et plus lisibles.

GABFOOT prend l'esprit d'un gros site de pronostics et le rend plus editorial, plus clair et plus credible. Les matchs forts, la Botola, les news clubs et le poster Telegram vivent dans une meme direction visuelle, avec une palette pensee pour inspirer confiance.

Board principal Les picks les plus solides remontent avant le reste.
Radar editorial Le flux news complete le signal au lieu de le parasiter.
Sortie Telegram Le site produit aussi une image prete a publier.
{len(matches)} signals majeurs actifs avec ton filtre a {min_percent}%.
{avg_confidence}% fiabilite moyenne lue en une seconde.
{len(botola) + len(tennis)} boards additionnels entre Maroc et tennis.
{len(articles)} angles editoriaux pour habiller le produit.
{len(site_updates)} mises a jour produit deja publiees.
{market_strip}
{notice_html}
{featured_match_html}
{poster_visual}
Telegram studio

Une affiche prete a diffuser sans sortir de l'univers GABFOOT.

Le site ne se limite pas a l'inspiration visuelle. Il pousse aussi une image exploitable pour les canaux Telegram, avec la meme logique de selection que le dashboard.

{featured_article_html}
Direction du produit

Une signature plus forte que le simple tableau de pronostics.

Le projet garde la richesse d'un site de pronostics populaire, mais remonte en gamme avec une meilleure hierarchie, une couleur plus maitrisee et une lecture plus rapide des signaux utiles.

01
Un ton plus credible

Fond sable chaud, vert profond et accent or. Le rendu evoque l'analyse et la confiance, pas le casino agressif ni la page surchargee.

02
Une lecture plus rapide

Les picks importants remontent tout de suite. En quelques secondes, tu vois les matchs forts, le niveau de fiabilite et les boards annexes qui comptent.

03
Un produit plus complet

Dashboard, fiches match, favoris personnels, flux editorial et poster Telegram travaillent ensemble au lieu de donner l'impression de blocs isoles.

Lecture instantanee

Le niveau du flux actuel, sans ouvrir dix pages.

La home montre deja le ton du produit. Les meilleures cartes doivent suffire a convaincre que GABFOOT sait trier, cadrer et raconter les matchs qui meritent l'attention.

{render_landing_pick_cards(matches)}
Editorial Clubs & joueurs
Voir tout
{render_landing_article_teasers(articles)}
Produit Nouveautes
Voir tout
{render_landing_update_teasers(site_updates)}
Architecture du site

Une colonne centrale claire, des branches utiles, aucun bloc perdu.

La home doit expliquer tout le produit. Le dashboard porte l'execution, les boards annexes elargissent la couverture, l'editorial habille le site et le journal produit montre que la plateforme avance.

01
Accueil

La page d'entree pose le ton, presente le signal fort et oriente immediatement vers les axes qui comptent.

Rester sur la vitrine
02
Dashboard

Le coeur operationnel ou tu filtres les matchs, pilotes le seuil de confiance et pousses le contenu exploitable.

Ouvrir le board principal
03
Boards

Botola et Tennis etendent la lecture sans casser la structure. Chaque univers garde sa place au lieu d'etre ajoute au hasard.

Voir les boards secondaires
04
Editorial

Articles et nouveautes donnent du contexte, de la credibilite et une preuve visible que le site est vivant.

Lire le flux editorial
Parcours rapides

Des parcours alignes avec la logique du produit.

Chaque bloc a maintenant une fonction nette dans l'architecture globale. Les liens ne se battent plus entre eux et gardent la meme hierarchie visuelle.

{interaction_script()} """ def favorites_script() -> str: return """ """ def find_match_for_detail(match_id: int, limit: int = 12, min_percent: int = 55) -> InterestingMatch | None: with _CACHE_LOCK: cached_entries = list(_DASHBOARD_CACHE.values()) for entry in cached_entries: for item in entry.get("matches", []): if int(item.get("match_id", 0)) == match_id: return deserialize_match(item) try: matches = collect_interesting_matches(limit=limit, min_percent=min_percent) except Exception: return None for match in matches: if match.match_id == match_id: return match return None def render_match_detail_page(match: InterestingMatch, articles: list[dict[str, str]]) -> str: kickoff = fmt_kickoff(match.kickoff_utc) pick_class = pick_theme(match.prediction) confidence_class = confidence_theme(match.sureness_percent) reasons = "".join(f"
  • {html.escape(item)}
  • " for item in match.why) consensus = "".join(f"
  • {html.escape(item)}
  • " for item in match.consensus_notes) article_cards = render_articles_grid(articles) favorite_button = render_favorite_button( match.match_id, f"{match.home_name} vs {match.away_name}", kickoff, match.prediction, match.sureness_percent, f"/match/{match.match_id}", ) external_link = ( f'Voir sur FotMob' if match.page_url else "" ) return f""" {html.escape(match.home_name)} vs {html.escape(match.away_name)} | GABFOOT
    {html.escape(match.tournament_name)} • {html.escape(kickoff)}

    {html.escape(match.home_name)} vs {html.escape(match.away_name)}

    {html.escape(match.prediction)}
    Confiance GABFOOT : {match.sureness_percent}%
    Forme recente
    {html.escape(match.home_form)} | {html.escape(match.away_form)}
    Joueurs cles
    {html.escape(match.home_key_player)} | {html.escape(match.away_key_player)}
    Consensus
    {' / '.join(html.escape(item) for item in match.consensus_notes) or 'Aucun signal fort'}
    Classement
    {match.home_rank or '-'} / {match.away_rank or '-'}
    Historique 3 ans
    {match.home_history_score:.2f} / {match.away_history_score:.2f}
    Buts par match
    {match.home_goals_per_match:.2f} / {match.away_goals_per_match:.2f}
    Buts encaisses
    {match.home_conceded_per_match:.2f} / {match.away_conceded_per_match:.2f}
    H2H
    {match.h2h_edge:+.2f}
    Absences
    {match.injuries_edge:+.2f}

    Pourquoi ce pick

      {reasons}

    Lecture GABFOOT

      {consensus}

    Articles lies

    {article_cards}
    {interaction_script()} {favorites_script()} """ def render_team_detail_page(team_id: int) -> str: payload = get_team_payload(team_id) details = payload.get("details", {}) or {} overview = payload.get("overview", {}) or {} top_players = overview.get("topPlayers") or {} next_match = overview.get("nextMatch") or {} def first_player(bucket: str) -> str: bucket_payload = top_players.get(bucket) or {} players = bucket_payload.get("players") or [] if not players: return "N/A" player = players[0] return f"{player.get('name', 'Joueur')} ({player.get('value', '-')})" logo = ( payload.get("sportsTeamJSONLD", {}).get("logo") or details.get("logo") or "" ) visual = f'{html.escape(details.get(' if logo else "" form_record = parse_form(payload).get("record", "N/A") venue = (overview.get("venue") or {}).get("name") or "Stade indisponible" next_match_name = "" if next_match: home = (next_match.get("home") or {}).get("name", "") away = (next_match.get("away") or {}).get("name", "") if home or away: next_match_name = f"{home} vs {away}".strip() related_articles = [] for item in ((overview.get("newsSummary") or {}).get("items") or [])[:6]: source = item.get("source") or {} related_articles.append( { "team": str(details.get("name", "Equipe")), "title": str(source.get("title", "Article club")), "summary": str(item.get("summary", "Resume indisponible.")), "url": str(source.get("uri", "")), "source": str(source.get("sourceName", "Source")), "image": str(logo), "logo": str(logo), } ) article_cards = render_articles_grid(related_articles) return f""" {html.escape(details.get("name", "Equipe"))} | GABFOOT
    {visual}

    {html.escape(details.get("name", "Equipe"))}

    {html.escape(details.get("country", {}).get("name", "") if isinstance(details.get("country"), dict) else str(details.get("country", "")))} • {html.escape(str(details.get("primaryLeagueName", "Ligue principale")))} • {html.escape(venue)}

    Vue rapide

    Forme
    {html.escape(form_record)}
    Buteur
    {html.escape(first_player('byGoals'))}
    Meilleure note
    {html.escape(first_player('byRating'))}
    Passe decisive
    {html.escape(first_player('byAssists'))}

    Prochain match

    {html.escape(next_match_name or 'Prochain match indisponible')}

    Articles lies

    {article_cards}
    {interaction_script()} """ def render_league_detail_page(league_id: int) -> str: payload = get_json(f"https://www.fotmob.com/api/leagues?id={league_id}", timeout=40) details = payload.get("details", {}) or {} rows = top_teams_for_league(league_id, limit=10) fixtures = (payload.get("fixtures") or {}).get("allMatches") or [] upcoming = [item for item in fixtures if not item.get("status", {}).get("finished")] upcoming.sort(key=lambda item: item.get("status", {}).get("utcTime", "")) table_rows = [] for row in rows: team_id = int(row.get("id", 0)) link = f"/team/{team_id}" if team_id else "#" table_rows.append( f""" {row.get('idx', '-')} {html.escape(str(row.get('name', 'Equipe')))} {row.get('played', '-')} {row.get('wins', '-')} {row.get('draws', '-')} {row.get('losses', '-')} {html.escape(str(row.get('scoresStr', '-')))} {row.get('pts', '-')} """ ) fixture_cards = [] for item in upcoming[:8]: fixture_cards.append( f"""
    {html.escape(fmt_kickoff(item.get('status', {}).get('utcTime', '')))}
    {html.escape((item.get('home') or {}).get('name', ''))} vs {html.escape((item.get('away') or {}).get('name', ''))}
    """ ) return f""" {html.escape(str(details.get('name', 'Ligue')))} | GABFOOT

    {html.escape(str(details.get('name', 'Ligue')))}

    Classement, equipes leaders et prochains matchs sur la meme page.

    Classement

    {''.join(table_rows)}
    #EquipeJGNPButsPts

    Prochains matchs

    {''.join(fixture_cards) or '
    Aucun match a venir.
    '}
    {interaction_script()} """ def page_html( matches: list[InterestingMatch], card_path: Path | None, limit: int, min_percent: int, notice: str = "", botola: list[dict[str, object]] | None = None, tennis: list[dict[str, object]] | None = None, articles: list[dict[str, str]] | None = None, site_url: str = "", ) -> str: now = datetime.now(timezone.utc).strftime("%d/%m/%Y %H:%M UTC") botola = botola or [] tennis = tennis or [] articles = articles or [] site_url = site_url.rstrip("/") canonical_url = f"{site_url}/dashboard" if site_url else "" icon_url = absolute_url(site_url, "/icon.png") if site_url else "/icon.png" canonical_tag = f'' if canonical_url else "" og_url_tag = f'' if canonical_url else "" featured_match = matches[0] if matches else None featured_article = articles[0] if articles else None avg_confidence = int(round(sum(match.sureness_percent for match in matches) / len(matches))) if matches else 0 prediction_table = render_prediction_table(matches) mobile_pick_cards = render_mobile_pick_cards(matches) botola_table = render_botola_table(botola) tennis_table = render_tennis_table(tennis) article_cards = render_articles_grid(articles) market_strip = render_market_strip(matches, botola) if DASHBOARD_HERO_IMAGE_PATH.exists(): dashboard_hero_visual = f"""
    Visuel premium GABFOOT pour le dashboard
    Visual studio
    {avg_confidence}% Fiabilite moyenne du board actif avec un filtre fixe a {min_percent}% minimum.
    """ else: dashboard_hero_visual = f"""
    {avg_confidence}% Fiabilite moyenne du board actif avec un filtre fixe a {min_percent}% minimum.
    """ image_block = "" if card_path and card_path.exists(): image_block = """
    Poster

    Affiche Telegram

    Ouvrir l'image

    Une sortie visuelle prete a diffuser, construite avec le meme filtre que le board principal.

    Affiche matchs surs
    """ notice_html = f'
    {html.escape(notice)}
    ' if notice else "" lead_panel = "" if featured_match: featured_favorite = render_favorite_button( featured_match.match_id, f"{featured_match.home_name} vs {featured_match.away_name}", fmt_kickoff(featured_match.kickoff_utc), featured_match.prediction, featured_match.sureness_percent, f"/match/{featured_match.match_id}", ) lead_panel = f"""
    Match signature

    {html.escape(featured_match.home_name)} vs {html.escape(featured_match.away_name)}

    {html.escape(featured_match.tournament_name)} • {html.escape(fmt_kickoff(featured_match.kickoff_utc))}
    {html.escape(featured_match.prediction)} • {featured_match.sureness_percent}% {html.escape(featured_match.home_form)} | {html.escape(featured_match.away_form)} H2H {html.escape(str(featured_match.h2h_edge))}

    {html.escape(' • '.join(featured_match.why))}

    Voir la fiche match{featured_favorite}
    """ editorial_panel = "" if featured_article: image = str(featured_article.get("image", "")).strip() visual = f'{html.escape(featured_article[' if image else '
    NEWS
    ' article_link = f'Lire l'analyse' if featured_article.get("url") else "" editorial_panel = f"""
    {visual}
    Radar editorial

    {html.escape(featured_article["title"])}

    {html.escape(featured_article["team"])} • {html.escape(featured_article["source"])}

    {html.escape(featured_article["summary"])}

    {article_link}
    """ favorites_panel = """
    Mon board

    Mes favoris

    Stockes localement sur cet appareil

    Les matchs enregistres ici servent de shortlist personnelle. Tu peux construire ton propre board sans casser le flux principal.

    Ajoute des matchs depuis les tableaux ou les fiches pour garder tes meilleurs spots dans un espace a part.
    """ return f""" GABFOOT | Control Room Pronostics Foot {og_url_tag} {canonical_tag}
    Control room GABFOOT

    Des picks mieux cadres, plus credibles et plus lisibles qu'un portail surcharge.

    Le dashboard GABFOOT rassemble les matchs les plus solides, la Botola, le tennis, les news et le poster Telegram dans une seule salle de controle. Mise a jour: {now}
    Board live Botola + Tennis Poster Telegram
    {dashboard_hero_visual}
    Top picks
    {len(matches)}
    Matchs gardes dans le tri principal.
    Botola
    {len(botola)}
    Signaux marocains actifs aujourd'hui.
    Tennis
    {len(tennis)}
    Rencontres ATP et WTA surveillees.
    Articles
    {len(articles)}
    Angles editoriaux pour donner du relief.
    {market_strip}
    {notice_html}
    {lead_panel} {editorial_panel}
    Premium board

    Matchs les plus solides

    {len(matches)} match(s) retenu(s) dans ce run

    La lecture reste immediate: horaire, contexte, recommandation, taux de confiance et lien direct vers la fiche match.

    {mobile_pick_cards}
    {prediction_table}
    {image_block}
    Maroc

    Signal Botola Pro

    Premiere ligue marocaine

    Une entree locale plus forte pour donner au produit une personnalite claire et un axe marocain visible.

    {botola_table}
    Multi-board

    Tennis world

    ATP / WTA

    Le board secondaire montre que GABFOOT peut ouvrir d'autres flux sans perdre sa direction visuelle.

    {tennis_table}
    {favorites_panel}
    Editorial

    Radar clubs & joueurs

    Actualites football

    Le produit ressemble moins a une simple grille de cotes quand l'editorial est traite avec la meme exigence visuelle que les picks.

    {article_cards}
    {interaction_script()} {favorites_script()} """ def match_to_dict(match: InterestingMatch) -> dict[str, object]: return { "tournament": match.tournament_name, "kickoff": fmt_kickoff(match.kickoff_utc), "homeName": match.home_name, "awayName": match.away_name, "prediction": match.prediction, "surenessPercent": match.sureness_percent, "homeForm": match.home_form, "awayForm": match.away_form, "homeRank": match.home_rank, "awayRank": match.away_rank, "homeHistoryScore": match.home_history_score, "awayHistoryScore": match.away_history_score, "h2hEdge": match.h2h_edge, "injuriesEdge": match.injuries_edge, "homeKeyPlayer": match.home_key_player, "awayKeyPlayer": match.away_key_player, "why": match.why, "consensusNotes": match.consensus_notes, } def render_collection(title: str, subtitle: str, content: str) -> str: return f""" {html.escape(title)} - GABFOOT
    Section GABFOOT

    {html.escape(title)}

    {html.escape(subtitle)}
    {content}
    {interaction_script()} """ def render_botola_cards(botola: list[dict[str, object]]) -> str: return render_botola_table(botola) def render_tennis_cards(tennis: list[dict[str, object]]) -> str: return render_tennis_table(tennis) def render_article_cards(articles: list[dict[str, str]]) -> str: cards = [] for item in articles: link = "" if item["url"]: link = f'Lire l'article' image = str(item.get("image", "")).strip() visual = ( f'{html.escape(item[' if image else '
    GABFOOT
    ' ) cards.append( f"""
    {visual}
    Football News
    {html.escape(item['team'])} • {html.escape(item['source'])}
    {html.escape(item['title'])}
    {html.escape(item['summary'])}
    {link}
    """ ) return "".join(cards) or '
    Aucun article remonte pour le moment.
    ' def render_update_cards(updates: list[dict[str, object]]) -> str: cards = [] for item in updates: bullets = item.get("bullets", []) bullet_html = "".join(f"
  • {html.escape(str(bullet))}
  • " for bullet in bullets[:4]) cards.append( f"""
    {html.escape(str(item.get("label", "Produit")))}
    {html.escape(str(item.get("date", "")))}
    NEW update
    {html.escape(str(item.get("title", "")))}
    {html.escape(str(item.get("summary", "")))}
      {bullet_html}
    """ ) return "".join(cards) or '
    Aucune mise a jour publiee pour le moment.
    ' class AppHandler(BaseHTTPRequestHandler): def do_GET(self) -> None: parsed = urlparse(self.path) params = parse_qs(parsed.query) limit = max(1, min(12, int(params.get("limit", ["6"])[0]))) min_percent = max(55, min(90, int(params.get("min_percent", ["78"])[0]))) site_url = request_base_url(self) if parsed.path == "/healthz": with _CACHE_LOCK: cache_entries = len(_DASHBOARD_CACHE) return self.render_json({"ok": True, "cacheEntries": cache_entries, "siteUrl": site_url}) if parsed.path == "/robots.txt": return self.render_robots(site_url) if parsed.path == "/sitemap.xml": return self.render_sitemap(site_url) if parsed.path == "/image": return self.serve_image() if parsed.path == "/dashboard-hero.jpg": return self.serve_file(DASHBOARD_HERO_IMAGE_PATH, "image/jpeg", cache_control="public, max-age=86400") if parsed.path == "/icon.png": return self.serve_file(ICON_PATH, "image/png", cache_control="public, max-age=86400") if parsed.path == "/manifest.webmanifest": return self.render_manifest() if parsed.path == "/sw.js": return self.render_sw() if parsed.path == "/api/send": matches, card_path = build_card(limit=limit, min_percent=min_percent) if not card_path: return self.render_json({"ok": False, "message": "Aucun match disponible"}, status=HTTPStatus.OK) send_photo(card_path, f"Top du top | Matchs surs {min_percent}%+") return self.render_json({"ok": True, "message": "Affiche envoyee sur Telegram"}) if parsed.path == "/send": matches, card_path = build_card(limit=limit, min_percent=min_percent) botola = safe_botola_predictions() tennis = safe_tennis_world_matches() articles = safe_football_articles(matches, botola) notice = "Aucun match disponible a envoyer." if card_path: send_photo(card_path, f"Top du top | Matchs surs {min_percent}%+") notice = "Affiche envoyee sur Telegram." return self.render_dashboard(matches, card_path, limit, min_percent, notice, botola, tennis, articles, site_url=site_url) if parsed.path == "/api/dashboard": force_refresh = "_refresh" in params or params.get("force", ["0"])[0] == "1" if force_refresh: cached_payload = get_fresh_dashboard_payload(limit=limit, min_percent=min_percent) stale = False else: cached_payload, stale = get_cached_dashboard_payload(limit=limit, min_percent=min_percent) if cached_payload is None: return self.render_json( { "updatedAt": "", "minPercent": min_percent, "imagePath": "/image" if CARD_PATH.exists() else "", "matches": [], "botolaPredictions": [], "tennisWorld": [], "footballArticles": [], "notice": "Chargement initial en cours. Recharge dans quelques secondes.", } ) matches = [deserialize_match(item) for item in cached_payload.get("matches", [])] return self.render_json( { "updatedAt": datetime.fromtimestamp(float(cached_payload.get("updated_at", time.time())), timezone.utc).isoformat(), "minPercent": min_percent, "imagePath": "/image" if cached_payload.get("has_card") else "", "matches": [match_to_dict(match) for match in matches], "botolaPredictions": cached_payload.get("botola", []), "tennisWorld": cached_payload.get("tennis", []), "footballArticles": cached_payload.get("articles", []), "notice": "Donnees en cache, actualisation en cours." if stale else "", } ) if parsed.path.startswith("/match/"): raw_match_id = parsed.path.removeprefix("/match/").strip("/") if not raw_match_id.isdigit(): self.send_error(HTTPStatus.NOT_FOUND, "Match introuvable") return match = find_match_for_detail(int(raw_match_id)) if not match: self.send_error(HTTPStatus.NOT_FOUND, "Match introuvable") return articles = safe_football_articles([match], [], limit=6) return self.render_html(render_match_detail_page(match, articles)) if parsed.path.startswith("/team/"): raw_team_id = parsed.path.removeprefix("/team/").strip("/") if not raw_team_id.isdigit(): self.send_error(HTTPStatus.NOT_FOUND, "Equipe introuvable") return return self.render_html(render_team_detail_page(int(raw_team_id))) if parsed.path.startswith("/league/"): raw_league_id = parsed.path.removeprefix("/league/").strip("/") if not raw_league_id.isdigit(): self.send_error(HTTPStatus.NOT_FOUND, "Ligue introuvable") return return self.render_html(render_league_detail_page(int(raw_league_id))) if parsed.path == "/botola": botola = safe_botola_predictions(limit=12) return self.render_html(render_collection("Pronostic Botola Pro", "Premiere ligue marocaine", render_botola_cards(botola))) if parsed.path == "/tennis": tennis = safe_tennis_world_matches(limit=16) return self.render_html(render_collection("Tennis World", "Circuit ATP / WTA", render_tennis_cards(tennis))) if parsed.path == "/articles": cached_payload, stale = get_cached_dashboard_payload(limit=6, min_percent=min_percent) articles = list((cached_payload or {}).get("articles", [])) subtitle = "Actualites football, clubs et joueurs" if stale: subtitle += " - donnees en cache" return self.render_html(render_collection("Articles clubs & joueurs", subtitle, render_article_cards(articles))) if parsed.path == "/updates": subtitle = "Journal produit GABFOOT, nouveautes visibles et mises a jour de la plateforme" return self.render_html(render_collection("Nouveautes & mises a jour", subtitle, render_update_cards(load_site_updates()))) force_refresh = "_refresh" in params or params.get("force", ["0"])[0] == "1" if force_refresh: cached_payload = get_fresh_dashboard_payload(limit=limit, min_percent=min_percent) stale = False else: cached_payload, stale = get_cached_dashboard_payload(limit=limit, min_percent=min_percent) if cached_payload is None: matches = [] card_path = CARD_PATH if CARD_PATH.exists() else None notice = "Chargement initial en cours. Recharge la page dans quelques secondes." botola = [] tennis = [] articles = [] else: matches = [deserialize_match(item) for item in cached_payload.get("matches", [])] card_path = CARD_PATH if cached_payload.get("has_card") and CARD_PATH.exists() else None notice = "Donnees en cache, actualisation en cours." if stale else "" botola = list(cached_payload.get("botola", [])) tennis = list(cached_payload.get("tennis", [])) articles = list(cached_payload.get("articles", [])) if parsed.path == "/": return self.render_html(landing_html(matches, card_path, limit, min_percent, notice, botola, tennis, articles, site_url=site_url)) if parsed.path in {"/dashboard", "/app"}: return self.render_dashboard(matches, card_path, limit, min_percent, notice, botola, tennis, articles, site_url=site_url) self.send_error(HTTPStatus.NOT_FOUND, "Page introuvable") return def serve_image(self) -> None: return self.serve_file(CARD_PATH, "image/png") def render_bytes( self, payload: bytes, content_type: str, status: HTTPStatus = HTTPStatus.OK, cache_control: str = "no-store, max-age=0", ) -> None: self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(payload))) self.send_header("Cache-Control", cache_control) self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "strict-origin-when-cross-origin") self.send_header("X-Frame-Options", "SAMEORIGIN") self.end_headers() self.wfile.write(payload) def serve_file(self, path: Path, content_type: str, cache_control: str = "no-store, max-age=0") -> None: if not path.exists(): self.send_error(HTTPStatus.NOT_FOUND, "Fichier indisponible") return payload = path.read_bytes() self.render_bytes(payload, content_type, cache_control=cache_control) def render_dashboard( self, matches: list[InterestingMatch], card_path: Path | None, limit: int, min_percent: int, notice: str = "", botola: list[dict[str, object]] | None = None, tennis: list[dict[str, object]] | None = None, articles: list[dict[str, str]] | None = None, site_url: str = "", ) -> None: payload = page_html(matches, card_path, limit, min_percent, notice, botola, tennis, articles, site_url=site_url).encode("utf-8") self.render_bytes(payload, "text/html; charset=utf-8") def render_html(self, html_text: str) -> None: payload = html_text.encode("utf-8") self.render_bytes(payload, "text/html; charset=utf-8") def render_json(self, data: dict[str, object], status: HTTPStatus = HTTPStatus.OK) -> None: payload = json.dumps(data, ensure_ascii=True).encode("utf-8") self.render_bytes(payload, "application/json; charset=utf-8", status=status) def render_robots(self, site_url: str) -> None: payload = f"User-agent: *\nAllow: /\nSitemap: {absolute_url(site_url, '/sitemap.xml')}\n".encode("utf-8") self.render_bytes(payload, "text/plain; charset=utf-8", cache_control="public, max-age=3600") def render_sitemap(self, site_url: str) -> None: static_entries = [ ("/", "daily", "1.0"), ("/dashboard", "hourly", "0.9"), ("/botola", "daily", "0.8"), ("/tennis", "hourly", "0.7"), ("/articles", "daily", "0.8"), ] dynamic_entries: list[tuple[str, str, str]] = [] seen_paths: set[str] = set() with _CACHE_LOCK: cached_entries = list(_DASHBOARD_CACHE.values()) for entry in cached_entries: for item in entry.get("matches", []): match_id = int(item.get("match_id", 0)) league_id = int(item.get("league_id", 0)) home_id = int(item.get("home_id", 0)) away_id = int(item.get("away_id", 0)) for path in ( f"/match/{match_id}" if match_id else "", f"/league/{league_id}" if league_id else "", f"/team/{home_id}" if home_id else "", f"/team/{away_id}" if away_id else "", ): if path and path not in seen_paths: seen_paths.add(path) dynamic_entries.append((path, "daily", "0.6")) if len(dynamic_entries) >= 24: break if len(dynamic_entries) >= 24: break lastmod = datetime.now(timezone.utc).date().isoformat() urls = [] for path, changefreq, priority in [*static_entries, *dynamic_entries]: urls.append( f"{html.escape(absolute_url(site_url, path))}{lastmod}{changefreq}{priority}" ) payload = ( '' '' + "".join(urls) + "" ).encode("utf-8") self.render_bytes(payload, "application/xml; charset=utf-8", cache_control="public, max-age=3600") def render_manifest(self) -> None: public_url = configured_public_url() payload = json.dumps( { "name": "GABFOOT Dashboard", "short_name": "GABFOOT", "id": absolute_url(public_url, "/dashboard") if public_url else "/dashboard", "start_url": "/dashboard", "scope": "/", "display": "standalone", "background_color": "#08150c", "theme_color": "#08150c", "description": "Dashboard GABFOOT pour les matchs surs, l'affiche Telegram et le controle des boards.", "icons": [ { "src": "/icon.png", "sizes": "512x512", "type": "image/png", } ], }, ensure_ascii=True, ).encode("utf-8") self.render_bytes(payload, "application/manifest+json; charset=utf-8", cache_control="public, max-age=3600") def render_sw(self) -> None: payload = b"""self.addEventListener('install', () => self.skipWaiting()); self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); self.addEventListener('fetch', () => {}); """ self.render_bytes(payload, "application/javascript; charset=utf-8", cache_control="public, max-age=3600") def log_message(self, format: str, *args) -> None: return def main() -> int: load_dotenv(ENV_FILE) load_dashboard_cache() ensure_dashboard_refresh(limit=6, min_percent=78) port = int(os.getenv("PORT") or os.getenv("GABFOOT_WEB_PORT", str(PORT))) default_host = "0.0.0.0" if os.getenv("PORT") else HOST host = os.getenv("GABFOOT_WEB_HOST", default_host) server = ThreadingHTTPServer((host, port), AppHandler) print(f"GABFOOT web app sur http://{host}:{port}", flush=True) try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() return 0 if __name__ == "__main__": raise SystemExit(main())