Spaces:
Sleeping
Sleeping
Commit ·
69c9e26
1
Parent(s): fcb850d
added good working stuff
Browse filesFiles changed (11)
- app.py+29-32
- pages/dungeon_draft.py → app_pages/dungeon_draft.pyRenamed
- app_pages/game_detail.pyAdded+42
- pages/home.py → app_pages/home.pyRenamed
- pages/points_tracker.py → app_pages/points_tracker.pyRenamed+39-105
- pages/skull_king.py → app_pages/skull_king.pyRenamed
- requirements.txt-1
- src/cookie_token_store.py+53-26
- src/scoreboard.pyAdded+111
- src/sheets_backend.py+183-32
- src/workbook_access.pyAdded+21
40 unmodified lines4142434445464748495051525354555614 unmodified lines717273747576777879808182838485868788891 unmodified line91929394959697985 unmodified lines1041051061071081091101111121131 unmodified line1151161171181191201211221231241251261271281291301311323 unmodified lines13613713813914014114214314414514614740 unmodified lines)def _handle_drive_oauth_callback(cookie_manager) -> None:"""Completes the one-time "Connect Google Drive" exchange, if we're mid-flow."""if not st.user.is_logged_in:returncode = st.query_params.get("code")state = st.query_params.get("state")if not code or not state or state != st.session_state.get("drive_oauth_state"):returnst.session_state.pop("drive_oauth_state", None)try:tokens = google_oauth.exchange_code(st.secrets["auth"]["client_id"],14 unmodified lines"Drive access will work for this session only -- try disconnecting ""the app at myaccount.google.com/permissions and reconnecting.")elif cookie_manager is not None:cookie_token_store.save_refresh_token(cookie_manager, st.user.email, refresh_token)_store_access_token(tokens)st.query_params.clear()# Deliberately no st.rerun() here: it would abandon this script run before# the browser has a chance to mount the cookie-manager's "set" component# and actually execute the JS that writes document.cookie, so the saved# refresh_token would never actually reach the browser. Letting this run# finish naturally still reflects the fresh access token immediately,# since the rest of app.py (sidebar, page) renders right after this call.def _ensure_drive_access(cookie_manager) -> None:"""Populates session_state's Drive access token, silently refreshing from astored refresh_token when possible. Shows a one-time "Connect Google Drive"link only when neither a live token nor a stored refresh_token exists.1 unmodified lineif not st.user.is_logged_in or _access_token_valid():returnif cookie_manager is not None:refresh_token = cookie_token_store.get_refresh_token(cookie_manager, st.user.email)if refresh_token:try:tokens = google_oauth.refresh_access_token(5 unmodified linesreturnexcept Exception as e:st.warning(f"Stored Drive access expired or was revoked ({e}); reconnecting.")cookie_token_store.delete_refresh_token(cookie_manager, st.user.email)state = uuid.uuid4().hexst.session_state["drive_oauth_state"] = stateauthorize_url = google_oauth.build_authorize_url(st.secrets["auth"]["client_id"], _drive_redirect_uri(), state)1 unmodified linewith st.expander("Drive connection diagnostics"):st.write("Logged in as:", st.user.email)st.write("Cookie storage configured:", cookie_manager is not None)if cookie_manager is not None:found = cookie_token_store.get_refresh_token(cookie_manager, st.user.email) is not Nonest.write("Refresh token cookie present:", found)st.write("Raw cookies seen by the app:", list(cookie_manager.cookies.keys()))# Constructed at most once per script run -- see get_cookie_manager's docstring._cookie_manager = cookie_token_store.get_cookie_manager() if "cookies" in st.secrets else Noneif "auth" in st.secrets:_handle_drive_oauth_callback(_cookie_manager)with st.sidebar:if "auth" not in st.secrets:3 unmodified lineselse:st.caption(f"Logged in as {st.user.email}")st.button("Log out", on_click=st.logout)_ensure_drive_access(_cookie_manager)home_page = st.Page("pages/home.py", title="Home", url_path="home", default=True)skull_king_page = st.Page("pages/skull_king.py", title="Skull King", url_path="skull_king")dungeon_draft_page = st.Page("pages/dungeon_draft.py", title="Dungeon Draft", url_path="dungeon_draft")points_tracker_page = st.Page("pages/points_tracker.py", title="Points Tracker", url_path="points_tracker")pg = st.navigation([home_page, skull_king_page, dungeon_draft_page, points_tracker_page])pg.run()40 unmodified lines4142434445464748495051525354555657585960616214 unmodified lines777879808182838485868788891 unmodified line91929394959697985 unmodified lines1041051061071081091101111121131 unmodified line1151161171181191201211221231241251263 unmodified lines13013113213313413513613713813914014114214314440 unmodified lines)def _handle_drive_oauth_callback() -> None:"""Completes the one-time "Connect Google Drive" exchange, if we're mid-flow.st.link_button always opens the authorize URL in a new tab, so this runsin a session that never had st.session_state populated by the tab thatstarted the flow -- the CSRF state has to be compared against a cookie(shared across tabs), not session_state (tab-scoped)."""if not st.user.is_logged_in:returncode = st.query_params.get("code")state = st.query_params.get("state")if not code or not state or state != cookie_token_store.get_oauth_state():returncookie_token_store.clear_oauth_state()try:tokens = google_oauth.exchange_code(st.secrets["auth"]["client_id"],14 unmodified lines"Drive access will work for this session only -- try disconnecting ""the app at myaccount.google.com/permissions and reconnecting.")elif "cookies" in st.secrets:cookie_token_store.save_refresh_token(st.user.email, refresh_token)_store_access_token(tokens)st.query_params.clear()def _ensure_drive_access() -> None:"""Populates session_state's Drive access token, silently refreshing from astored refresh_token when possible. Shows a one-time "Connect Google Drive"link only when neither a live token nor a stored refresh_token exists.1 unmodified lineif not st.user.is_logged_in or _access_token_valid():returnif "cookies" in st.secrets:refresh_token = cookie_token_store.get_refresh_token(st.user.email)if refresh_token:try:tokens = google_oauth.refresh_access_token(5 unmodified linesreturnexcept Exception as e:st.warning(f"Stored Drive access expired or was revoked ({e}); reconnecting.")cookie_token_store.delete_refresh_token(st.user.email)state = uuid.uuid4().hexcookie_token_store.save_oauth_state(state)authorize_url = google_oauth.build_authorize_url(st.secrets["auth"]["client_id"], _drive_redirect_uri(), state)1 unmodified linewith st.expander("Drive connection diagnostics"):st.write("Logged in as:", st.user.email)st.write("Cookie storage configured:", "cookies" in st.secrets)st.write("Raw cookies seen by the app:", list(st.context.cookies.keys()))if "auth" in st.secrets:_handle_drive_oauth_callback()with st.sidebar:if "auth" not in st.secrets:3 unmodified lineselse:st.caption(f"Logged in as {st.user.email}")st.button("Log out", on_click=st.logout)_ensure_drive_access()home_page = st.Page("app_pages/home.py", title="Home", url_path="home", default=True)skull_king_page = st.Page("app_pages/skull_king.py", title="Skull King", url_path="skull_king")dungeon_draft_page = st.Page("app_pages/dungeon_draft.py", title="Dungeon Draft", url_path="dungeon_draft")points_tracker_page = st.Page("app_pages/points_tracker.py", title="Points Tracker", url_path="points_tracker")game_detail_page = st.Page("app_pages/game_detail.py", title="Game Detail", url_path="game_detail")pg = st.navigation([home_page, skull_king_page, dungeon_draft_page, points_tracker_page, game_detail_page])pg.run()
123456789101112131415161718192021222324252627282930313233343536373839404142import streamlit as st
import scoreboardimport sheets_backend as sheetsfrom workbook_access import get_workbook
st.title("Game Detail")
session_id = st.query_params.get("session_id")
if not session_id: st.info("No game selected -- go to Points Tracker's Game History tab and click View on a game.")else: wb = get_workbook() if wb is None: st.info("Log in with Google to view game history.") else: rows = sheets.get_session_rounds(wb, session_id) if not rows: st.warning("No data found for this game session.") else: game_name = rows[0].get("game_name") or "Untitled" timestamp = rows[0].get("timestamp", "") st.subheader(f"{game_name}") st.caption(f"Played {timestamp}")
players, scores = scoreboard.rows_to_players_and_scores(rows) cumsum, _ = scoreboard.compute_cumulative(players, scores) sorted_players = sorted(players, key=lambda p: cumsum[p], reverse=True)
scoreboard.render_leaderboard(sorted_players, cumsum)
with st.expander("Scoreboard", expanded=True): # No stored winning-score threshold for historical games, so # nothing is ever flagged as "reached the target" here. scoreboard.render_scoreboard_transposed(sorted_players, scores, float("inf"))
with st.expander("Points progression chart", expanded=False): scoreboard.render_chart(players, scores)
if st.button("Back to Game History"): st.switch_page("app_pages/points_tracker.py")1 unmodified line234567891011121314154 unmodified lines202122232425262728293031323334353637383942 unmodified lines8283848586878813 unmodified lines10210310410510610710 unmodified lines11811912012112212317 unmodified lines1411421431441451461471481491501511521531541551564 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425513 unmodified lines26927027127227327427527627727822 unmodified lines3013023033043053063073083093103113123133141 unmodified lineimport streamlit as stimport pandas as pdimport altair as altimport sheets_backend as sheetsdef _init_state():if "pt_players" not in st.session_state:st.session_state.pt_players = []if "pt_game_started" not in st.session_state:st.session_state.pt_game_started = Falseif "pt_scores" not in st.session_state:4 unmodified linesst.session_state.pt_game_name = ""if "pt_session_id" not in st.session_state:st.session_state.pt_session_id = Nonedef _get_workbook():"""Returns the logged-in user's Sheets workbook, or None for anonymous sessions."""if "auth" not in st.secrets or not st.user.is_logged_in:return Noneaccess_token = st.session_state.get("google_access_token")if not access_token:return Noneif "pt_workbook" not in st.session_state:st.session_state.pt_workbook = sheets.get_or_create_user_workbook(access_token, st.user.email)return st.session_state.pt_workbook_NEW_GAME_NAME_SENTINEL = "+ New game name"42 unmodified linesif name and name not in st.session_state.pt_players:st.session_state.pt_players.append(name)if wb is not None:sheets.add_player(wb, name)st.session_state.pt_new_player = ""col1, col2 = st.columns([3, 1])13 unmodified linesfor i, name in enumerate(remaining):if qcols[i % len(qcols)].button(name, key=f"pt_quickadd_{name}"):st.session_state.pt_players.append(name)st.rerun()if st.session_state.pt_players:10 unmodified linesst.session_state.pt_game_started = Truest.session_state.pt_scores = []st.session_state.pt_session_id = uuid.uuid4().hexst.rerun()else:st.info("Add at least 2 players to start.")17 unmodified linesif wb is None:st.info("Log in with Google to see your game history.")returnnames = sheets.list_game_names(wb)if not names:st.caption("No games recorded yet.")returnfor name in names:st.write(f"- {name}")def _setup_phase():wb = _get_workbook()tab_new, tab_players, tab_history = st.tabs(["New Game", "Saved Players", "Game History"])with tab_new:4 unmodified lines_render_game_history_tab(wb)def _compute_cumulative(players, scores):cumsum = {p: 0 for p in players}history = []for round_data in scores:for p in players:cumsum[p] += round_data.get(p, 0)history.append(dict(cumsum))return cumsum, historydef _render_scoreboard_transposed(players, scores, winning_score):header_cols = ["Player"] + [f"R{i + 1}" for i in range(len(scores))]md = "| " + " | ".join(header_cols) + " |\n"md += "| " + " | ".join(["---"] * len(header_cols)) + " |\n"for p in players:row = [f"**{p}**"]running = 0for round_data in scores:pts = round_data.get(p, 0)prev = runningrunning += ptschange = running - previf change > 0:indicator = f' <span style="color:green">▲ +{change}</span>'elif change < 0:indicator = f' <span style="color:red">▼ {change}</span>'else:indicator = ""winner_flag = " ★" if running >= winning_score else ""row.append(f"**{running}**{indicator}{winner_flag}")md += "| " + " | ".join(row) + " |\n"st.markdown(md, unsafe_allow_html=True)def _render_leaderboard(players, cumsum):st.subheader("🏆 Leaderboard")if not players:returnmedals = ["🥇", "🥈", "🥉"]cols = st.columns(len(players))for i, p in enumerate(players):label = f"{medals[i]} {p}" if i < len(medals) else f"#{i + 1} {p}"with cols[i]:st.metric(label, cumsum[p])def _render_chart(players, scores):if not scores:returncumsum = {p: 0 for p in players}rows = [{"Round": 0, **{p: 0 for p in players}}]for i, round_data in enumerate(scores):for p in players:cumsum[p] += round_data.get(p, 0)rows.append({"Round": i + 1, **dict(cumsum)})df = pd.DataFrame(rows)df_long = df.melt(id_vars="Round", var_name="Player", value_name="Points")chart = (alt.Chart(df_long).mark_line(point=True).encode(x=alt.X("Round:Q", axis=alt.Axis(tickMinStep=1)),y=alt.Y("Points:Q"),color=alt.Color("Player:N"),tooltip=["Round", "Player", "Points"],).properties(height=300).interactive())st.altair_chart(chart, use_container_width=True)def _game_phase():players = st.session_state.pt_playersscores = st.session_state.pt_scoreswinning_score = st.session_state.pt_winning_scoregame_name = st.session_state.pt_game_namecumsum, _ = _compute_cumulative(players, scores)sorted_players = sorted(players, key=lambda p: cumsum[p], reverse=True)_render_leaderboard(sorted_players, cumsum)if game_name:st.subheader(f"Tracking: {game_name}")13 unmodified linesif scores:with st.expander("Scoreboard", expanded=True):_render_scoreboard_transposed(sorted_players, scores, winning_score)with st.expander("Points progression chart", expanded=False):_render_chart(players, scores)if winners:st.success(f"Game over! Winner{'s' if len(winners) > 1 else ''}: **{', '.join(winners)}** reached {winning_score} points!")22 unmodified linesif st.button("Save Round", type="primary", key=f"pt_save_r{next_round}"):st.session_state.pt_scores.append(round_scores)wb = _get_workbook()if wb is not None:for player, score in round_scores.items():sheets.record_round(wb,game_name=game_name or "Points Tracker",session_id=st.session_state.pt_session_id,round_number=next_round,player_name=player,score=score,)1 unmodified line234567891011121314151617184 unmodified lines232425262728293042 unmodified lines7374757677787913 unmodified lines9394959697989910 unmodified lines11011111211311411511611711811912012112212317 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661674 unmodified lines17217317417517617717817918018118218318418518618713 unmodified lines20120220320420520620720820921022 unmodified lines2332342352362372382392402412422432442452462472481 unmodified lineimport streamlit as stimport pandas as pdimport scoreboardimport sheets_backend as sheetsfrom workbook_access import get_workbookdef _init_state():if "pt_players" not in st.session_state:st.session_state.pt_players = []if "pt_player_ids" not in st.session_state:st.session_state.pt_player_ids = {}if "pt_game_started" not in st.session_state:st.session_state.pt_game_started = Falseif "pt_scores" not in st.session_state:4 unmodified linesst.session_state.pt_game_name = ""if "pt_session_id" not in st.session_state:st.session_state.pt_session_id = Noneif "pt_game_id" not in st.session_state:st.session_state.pt_game_id = None_NEW_GAME_NAME_SENTINEL = "+ New game name"42 unmodified linesif name and name not in st.session_state.pt_players:st.session_state.pt_players.append(name)if wb is not None:st.session_state.pt_player_ids[name] = sheets.add_player(wb, name)st.session_state.pt_new_player = ""col1, col2 = st.columns([3, 1])13 unmodified linesfor i, name in enumerate(remaining):if qcols[i % len(qcols)].button(name, key=f"pt_quickadd_{name}"):st.session_state.pt_players.append(name)st.session_state.pt_player_ids[name] = sheets.add_player(wb, name)st.rerun()if st.session_state.pt_players:10 unmodified linesst.session_state.pt_game_started = Truest.session_state.pt_scores = []st.session_state.pt_session_id = uuid.uuid4().hexif wb is not None:game_name = st.session_state.pt_game_name or "Points Tracker"st.session_state.pt_game_id = sheets.get_or_create_game(wb, game_name)# Covers players already in the list before a workbook was# available (e.g. added while logged out then logged in).for name in st.session_state.pt_players:if name not in st.session_state.pt_player_ids:st.session_state.pt_player_ids[name] = sheets.add_player(wb, name)st.rerun()else:st.info("Add at least 2 players to start.")17 unmodified linesif wb is None:st.info("Log in with Google to see your game history.")returnsessions = sheets.list_game_sessions(wb)if not sessions:st.caption("No games recorded yet.")returnfor session in sessions:col_info, col_link = st.columns([4, 1])with col_info:st.write(f"**{session['game_name']}** -- {session['timestamp']} -- "f"{session['num_players']} players, {session['num_rounds']} rounds")with col_link:if st.button("View", key=f"pt_view_{session['session_id']}"):st.switch_page("app_pages/game_detail.py",query_params={"session_id": session["session_id"]},)def _setup_phase():wb = get_workbook()tab_new, tab_players, tab_history = st.tabs(["New Game", "Saved Players", "Game History"])with tab_new:4 unmodified lines_render_game_history_tab(wb)def _game_phase():players = st.session_state.pt_playersscores = st.session_state.pt_scoreswinning_score = st.session_state.pt_winning_scoregame_name = st.session_state.pt_game_namecumsum, _ = scoreboard.compute_cumulative(players, scores)sorted_players = sorted(players, key=lambda p: cumsum[p], reverse=True)scoreboard.render_leaderboard(sorted_players, cumsum)if game_name:st.subheader(f"Tracking: {game_name}")13 unmodified linesif scores:with st.expander("Scoreboard", expanded=True):scoreboard.render_scoreboard_transposed(sorted_players, scores, winning_score)with st.expander("Points progression chart", expanded=False):scoreboard.render_chart(players, scores)if winners:st.success(f"Game over! Winner{'s' if len(winners) > 1 else ''}: **{', '.join(winners)}** reached {winning_score} points!")22 unmodified linesif st.button("Save Round", type="primary", key=f"pt_save_r{next_round}"):st.session_state.pt_scores.append(round_scores)wb = get_workbook()if wb is not None:for player, score in round_scores.items():sheets.record_round(wb,game_id=st.session_state.pt_game_id or "",game_name=game_name or "Points Tracker",session_id=st.session_state.pt_session_id,round_number=next_round,player_id=st.session_state.pt_player_ids.get(player, ""),player_name=player,score=score,)
7 unmodified lines8910117 unmodified linestomli_wcryptographyrequestsextra-streamlit-components7 unmodified lines89107 unmodified linestomli_wcryptographyrequests
1234567891011121314151617181920212223245 unmodified lines30313233343536373839404142434445466 unmodified lines53545556575859import hashlibfrom datetime import datetime, timedelta, timezoneimport extra_streamlit_components as stximport streamlit as stfrom cryptography.fernet import Fernet_COOKIE_MAX_AGE_DAYS = 400 # ~ the longest lifetime browsers allow anyway (Chrome caps at 400 days)def get_cookie_manager() -> stx.CookieManager:"""Constructs the cookie-sync component.Must be called exactly once per script run (not cached, not called morethan once) -- the underlying component re-renders every rerun to reportthe browser's current cookies back to Python, so caching it (viast.cache_resource or otherwise) freezes it stale, and constructing asecond instance with the same key in the same run raisesDuplicateWidgetID."""return stx.CookieManager(key="bgt_cookie_manager")def _fernet() -> Fernet:5 unmodified linesreturn "bgt_rt_" + hashlib.sha256(email.encode()).hexdigest()[:16]def save_refresh_token(cookie_manager: stx.CookieManager, email: str, refresh_token: str) -> None:encrypted = _fernet().encrypt(refresh_token.encode()).decode()expires_at = datetime.now(timezone.utc) + timedelta(days=_COOKIE_MAX_AGE_DAYS)name = _cookie_name(email)# same_site="lax" (this library defaults to "strict") to match the SameSite# policy Streamlit's own auth cookie uses.cookie_manager.set(name, encrypted, expires_at=expires_at, key=f"set_{name}", same_site="lax")def get_refresh_token(cookie_manager: stx.CookieManager, email: str) -> str | None:encrypted = cookie_manager.get(_cookie_name(email))if not encrypted:return Nonetry:6 unmodified linesreturn Nonedef delete_refresh_token(cookie_manager: stx.CookieManager, email: str) -> None:name = _cookie_name(email)if cookie_manager.get(name) is not None:cookie_manager.delete(name, key=f"delete_{name}")1234567891011125 unmodified lines181920212223242526272829303132333435363738394041424344454647484950516 unmodified lines5859606162636465666768697071727374757677787980818283848586import hashlibfrom datetime import datetime, timedelta, timezoneimport streamlit as stfrom cryptography.fernet import Fernet_COOKIE_MAX_AGE_DAYS = 400 # ~ the longest lifetime browsers allow anyway (Chrome caps at 400 days)_HTTP_DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"_OAUTH_STATE_COOKIE = "bgt_oauth_state"def _fernet() -> Fernet:5 unmodified linesreturn "bgt_rt_" + hashlib.sha256(email.encode()).hexdigest()[:16]def _write_cookie(name: str, value: str, expires: datetime, *, reload: bool = False) -> None:# st.context.cookies is read-only, so writing needs a JS-side assignment --# same technique as analytics.py's Umami injection. Fernet's base64url# alphabet (letters, digits, -, _, =) is all cookie-safe per RFC 6265, so# no extra encoding is needed.## st.context.cookies reflects whatever the browser sent in the HTTP# request that opened the *current* session/WebSocket -- it does not# magically pick up a cookie set via JS partway through that same live# session (nothing forces a fresh HTTP request for that). So after saving# a token we care about reading back later, force a real page reload# (not st.rerun(), which reuses the existing session) so the very next# request actually carries the new cookie.expires_str = expires.strftime(_HTTP_DATE_FORMAT)script = f'document.cookie = "{name}={value}; expires={expires_str}; path=/; SameSite=Lax";'if reload:script += "window.location.replace(window.location.pathname);"st.html(f"<script>{script}</script>", unsafe_allow_javascript=True)def save_refresh_token(email: str, refresh_token: str) -> None:encrypted = _fernet().encrypt(refresh_token.encode()).decode()expires = datetime.now(timezone.utc) + timedelta(days=_COOKIE_MAX_AGE_DAYS)_write_cookie(_cookie_name(email), encrypted, expires, reload=True)def get_refresh_token(email: str) -> str | None:encrypted = st.context.cookies.get(_cookie_name(email))if not encrypted:return Nonetry:6 unmodified linesreturn Nonedef delete_refresh_token(email: str) -> None:# Expiring in the past is the standard way to delete a cookie via JS._write_cookie(_cookie_name(email), "", datetime(1970, 1, 1, tzinfo=timezone.utc))def save_oauth_state(state: str) -> None:"""Stashes the Connect-Drive CSRF state in a cookie rather thanst.session_state. st.link_button always opens the authorize URL in a newtab (Streamlit's own documented behavior), and Google's redirect lands inthat new tab -- a completely separate session with its own emptysession_state. Cookies, unlike session_state, are shared browser-wideacross tabs, so this is the only place both tabs can agree on the value.No reload needed here (unlike save_refresh_token): the *read* of thiscookie happens in the new tab after a genuinely fresh navigation, whichalready carries whatever cookies exist at that point."""expires = datetime.now(timezone.utc) + timedelta(minutes=10)_write_cookie(_OAUTH_STATE_COOKIE, state, expires)def get_oauth_state() -> str | None:return st.context.cookies.get(_OAUTH_STATE_COOKIE)def clear_oauth_state() -> None:_write_cookie(_OAUTH_STATE_COOKIE, "", datetime(1970, 1, 1, tzinfo=timezone.utc))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import altair as altimport pandas as pdimport streamlit as st
def compute_cumulative(players, scores): cumsum = {p: 0 for p in players} history = [] for round_data in scores: for p in players: cumsum[p] += round_data.get(p, 0) history.append(dict(cumsum)) return cumsum, history
def render_scoreboard_transposed(players, scores, winning_score): header_cols = ["Player"] + [f"R{i + 1}" for i in range(len(scores))] md = "| " + " | ".join(header_cols) + " |\n" md += "| " + " | ".join(["---"] * len(header_cols)) + " |\n"
for p in players: row = [f"**{p}**"] running = 0 for round_data in scores: pts = round_data.get(p, 0) prev = running running += pts change = running - prev if change > 0: indicator = f' <span style="color:green">▲ +{change}</span>' elif change < 0: indicator = f' <span style="color:red">▼ {change}</span>' else: indicator = "" winner_flag = " ★" if running >= winning_score else "" row.append(f"**{running}**{indicator}{winner_flag}") md += "| " + " | ".join(row) + " |\n"
st.markdown(md, unsafe_allow_html=True)
def render_leaderboard(players, cumsum): st.subheader("🏆 Leaderboard") if not players: return
medals = ["🥇", "🥈", "🥉"] cols = st.columns(len(players)) for i, p in enumerate(players): label = f"{medals[i]} {p}" if i < len(medals) else f"#{i + 1} {p}" with cols[i]: st.metric(label, cumsum[p])
def render_chart(players, scores): if not scores: return
cumsum = {p: 0 for p in players} rows = [{"Round": 0, **{p: 0 for p in players}}] for i, round_data in enumerate(scores): for p in players: cumsum[p] += round_data.get(p, 0) rows.append({"Round": i + 1, **dict(cumsum)})
df = pd.DataFrame(rows) df_long = df.melt(id_vars="Round", var_name="Player", value_name="Points")
chart = ( alt.Chart(df_long) .mark_line(point=True) .encode( x=alt.X("Round:Q", axis=alt.Axis(tickMinStep=1)), y=alt.Y("Points:Q"), color=alt.Color("Player:N"), tooltip=["Round", "Player", "Points"], ) .properties(height=300) .interactive() )
st.altair_chart(chart, use_container_width=True)
def rows_to_players_and_scores(rows: list[dict]) -> tuple[list[str], list[dict]]: """Converts raw games_played rows (one row per player per round) into the same (players, scores) shape the live game view uses, so historical sessions can reuse the exact same rendering functions.
Uses player_name (not player_id) since that's guaranteed present on both pre- and post-migration rows -- id lookups are for future robustness, not a requirement for basic display. """ players_seen: list[str] = [] by_round: dict[int, dict[str, int]] = {} for row in rows: name = row.get("player_name") or row.get("player_id") or "Unknown" if name not in players_seen: players_seen.append(name) try: rnd = int(row.get("round_number") or 0) except (TypeError, ValueError): rnd = 0 try: score = int(row.get("score") or 0) except (TypeError, ValueError): score = 0 by_round.setdefault(rnd, {})[name] = score
scores = [by_round[r] for r in sorted(by_round)] return players_seen, scores1 unmodified line23456789101112131415161718195 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified linefrom datetime import datetime, timezoneimport gspreadfrom google.oauth2.credentials import Credentials_PLAYERS_HEADER = ["player_id", "name", "created_at"]_GAMES_HEADER = ["timestamp", "game_name", "session_id", "round_number", "player_name", "score"]_WORKBOOK_TITLE_PREFIX = "BoardGameTracker"def _get_user_client(access_token: str) -> gspread.Client:creds = Credentials(token=access_token)return gspread.authorize(creds)def get_or_create_user_workbook(access_token: str, email: str) -> gspread.Spreadsheet:"""Returns the user's own Sheets workbook, creating it in their Drive on first use.5 unmodified linesexisting = client.list_spreadsheet_files(title=title)if existing:return client.open_by_key(existing[0]["id"])sh = client.create(title)players_ws = sh.sheet1players_ws.update_title("players")players_ws.append_row(_PLAYERS_HEADER)games_ws = sh.add_worksheet(title="games_played", rows=1, cols=len(_GAMES_HEADER))games_ws.append_row(_GAMES_HEADER)return shdef list_players(wb: gspread.Spreadsheet) -> list[dict]:ws = wb.worksheet("players")return ws.get_all_records()def list_game_names(wb: gspread.Spreadsheet) -> list[str]:"""Distinct game names played, most-recently-used first."""ws = wb.worksheet("games_played")names = [row["game_name"] for row in ws.get_all_records() if row.get("game_name")]return list(dict.fromkeys(reversed(names)))def add_player(wb: gspread.Spreadsheet, name: str) -> str:ws = wb.worksheet("players")existing = ws.get_all_records()for row in existing:if row.get("name", "").strip().lower() == name.strip().lower():return row["player_id"]player_id = uuid.uuid4().hexws.append_row([player_id, name, datetime.now(timezone.utc).isoformat()])return player_iddef record_round(wb: gspread.Spreadsheet,*,game_name: str,session_id: str,round_number: int,player_name: str,score: int,) -> None:ws = wb.worksheet("games_played")ws.append_row([datetime.now(timezone.utc).isoformat(),game_name,session_id,round_number,player_name,score,])1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495965 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified linefrom datetime import datetime, timezoneimport gspreadimport streamlit as stfrom google.oauth2.credentials import Credentials_PLAYERS_HEADER = ["player_id", "name", "created_at"]_GAMES_HEADER = ["game_id", "name", "created_at"]# game_name/player_name stay alongside the id columns (rather than being# replaced) so rows written before this schema existed keep displaying# correctly, and so display code never strictly depends on an id lookup# succeeding._GAMES_PLAYED_HEADER = ["timestamp","game_id","game_name","session_id","round_number","player_id","player_name","score",]_WORKBOOK_TITLE_PREFIX = "BoardGameTracker"# Sheets API enforces a strict per-minute read quota. Every worksheet lookup# and every full-table read counts against it, and a Streamlit rerun fires on# every widget interaction -- so naive per-call reads blow through the quota# almost immediately during an active game. These two caches are the fix:# worksheet *handles* (including the one-time header-migration check) are# cached for the life of the session, and row *data* is cached briefly with# an explicit invalidation on every write._RECORDS_CACHE_TTL = 20 # secondsdef _get_user_client(access_token: str) -> gspread.Client:creds = Credentials(token=access_token)return gspread.authorize(creds)def _ensure_columns(ws: gspread.Worksheet, required_columns: list[str]) -> list[str]:"""Appends any missing columns to the end of the header row.Existing data is never touched or reordered -- only new columns getadded at the end -- so sheets created before a schema change keepworking unmodified; old rows simply have blank cells for the newcolumns."""header = ws.row_values(1)missing = [c for c in required_columns if c not in header]if missing:header = header + missingws.update([header], "A1")return headerdef _get_or_create_worksheet(wb: gspread.Spreadsheet, title: str, header: list[str]) -> gspread.Worksheet:cache_key = f"_ws_handle_{wb.id}_{title}"if cache_key in st.session_state:return st.session_state[cache_key]try:ws = wb.worksheet(title)_ensure_columns(ws, header)except gspread.exceptions.WorksheetNotFound:ws = wb.add_worksheet(title=title, rows=1, cols=len(header))ws.append_row(header)st.session_state[cache_key] = wsreturn ws@st.cache_data(ttl=_RECORDS_CACHE_TTL, show_spinner=False)def _cached_records(_ws: gspread.Worksheet, cache_key: str) -> list[dict]:return _ws.get_all_records()def _get_records(wb: gspread.Spreadsheet, ws: gspread.Worksheet, title: str) -> list[dict]:return _cached_records(ws, f"{wb.id}:{title}")def _invalidate_records_cache() -> None:_cached_records.clear()def _append_row(ws: gspread.Worksheet, row: dict) -> None:column_order = ws.row_values(1)ws.append_row([row.get(c, "") for c in column_order])_invalidate_records_cache()def get_or_create_user_workbook(access_token: str, email: str) -> gspread.Spreadsheet:"""Returns the user's own Sheets workbook, creating it in their Drive on first use.5 unmodified linesexisting = client.list_spreadsheet_files(title=title)if existing:sh = client.open_by_key(existing[0]["id"])else:sh = client.create(title)players_ws = sh.sheet1players_ws.update_title("players")players_ws.append_row(_PLAYERS_HEADER)# Idempotent: creates "games" and migrates "games_played" to the current# schema for pre-existing workbooks too, not just brand-new ones._get_or_create_worksheet(sh, "players", _PLAYERS_HEADER)_get_or_create_worksheet(sh, "games", _GAMES_HEADER)_get_or_create_worksheet(sh, "games_played", _GAMES_PLAYED_HEADER)return shdef list_players(wb: gspread.Spreadsheet) -> list[dict]:ws = _get_or_create_worksheet(wb, "players", _PLAYERS_HEADER)return _get_records(wb, ws, "players")def add_player(wb: gspread.Spreadsheet, name: str) -> str:ws = _get_or_create_worksheet(wb, "players", _PLAYERS_HEADER)existing = _get_records(wb, ws, "players")for row in existing:if str(row.get("name", "")).strip().lower() == name.strip().lower():return row["player_id"]player_id = uuid.uuid4().hex_append_row(ws, {"player_id": player_id, "name": name, "created_at": datetime.now(timezone.utc).isoformat()})return player_iddef list_games(wb: gspread.Spreadsheet) -> list[dict]:ws = _get_or_create_worksheet(wb, "games", _GAMES_HEADER)return _get_records(wb, ws, "games")def get_or_create_game(wb: gspread.Spreadsheet, name: str) -> str:ws = _get_or_create_worksheet(wb, "games", _GAMES_HEADER)existing = _get_records(wb, ws, "games")for row in existing:if str(row.get("name", "")).strip().lower() == name.strip().lower():return row["game_id"]game_id = uuid.uuid4().hex_append_row(ws, {"game_id": game_id, "name": name, "created_at": datetime.now(timezone.utc).isoformat()})return game_iddef list_game_names(wb: gspread.Spreadsheet) -> list[str]:"""Distinct game names played, most-recently-used first."""ws = _get_or_create_worksheet(wb, "games_played", _GAMES_PLAYED_HEADER)names = [row["game_name"] for row in _get_records(wb, ws, "games_played") if row.get("game_name")]return list(dict.fromkeys(reversed(names)))def record_round(wb: gspread.Spreadsheet,*,game_id: str,game_name: str,session_id: str,round_number: int,player_id: str,player_name: str,score: int,) -> None:ws = _get_or_create_worksheet(wb, "games_played", _GAMES_PLAYED_HEADER)_append_row(ws,{"timestamp": datetime.now(timezone.utc).isoformat(),"game_id": game_id,"game_name": game_name,"session_id": session_id,"round_number": round_number,"player_id": player_id,"player_name": player_name,"score": score,},)def list_game_sessions(wb: gspread.Spreadsheet) -> list[dict]:"""One summary entry per distinct session_id, most recently played first."""ws = _get_or_create_worksheet(wb, "games_played", _GAMES_PLAYED_HEADER)rows = _get_records(wb, ws, "games_played")sessions: dict[str, dict] = {}order: list[str] = []for row in rows:sid = row.get("session_id")if not sid:continueif sid not in sessions:sessions[sid] = {"game_name": row.get("game_name") or "Untitled","timestamp": row.get("timestamp", ""),"players": set(),"rounds": set(),}order.append(sid)if row.get("player_name"):sessions[sid]["players"].add(row["player_name"])sessions[sid]["rounds"].add(row.get("round_number"))return [{"session_id": sid,"game_name": sessions[sid]["game_name"],"timestamp": sessions[sid]["timestamp"],"num_players": len(sessions[sid]["players"]),"num_rounds": len(sessions[sid]["rounds"]),}for sid in reversed(order)]def get_session_rounds(wb: gspread.Spreadsheet, session_id: str) -> list[dict]:"""Raw games_played rows for one session, sorted by round number."""ws = _get_or_create_worksheet(wb, "games_played", _GAMES_PLAYED_HEADER)rows = _get_records(wb, ws, "games_played")matching = [r for r in rows if str(r.get("session_id")) == str(session_id)]matching.sort(key=lambda r: int(r.get("round_number") or 0))return matching
123456789101112131415161718192021import streamlit as st
import sheets_backend as sheets
def get_workbook(): """Returns the logged-in user's Sheets workbook, or None for anonymous sessions.
Shared by every page that needs Sheets data, keyed off the access token app.py's login/Connect-Drive flow populates in session_state. """ if "auth" not in st.secrets or not st.user.is_logged_in: return None access_token = st.session_state.get("google_access_token") if not access_token: return None if "shared_workbook" not in st.session_state: st.session_state.shared_workbook = sheets.get_or_create_user_workbook( access_token, st.user.email ) return st.session_state.shared_workbookapp.py+29-32
pages/dungeon_draft.py → app_pages/dungeon_draft.pyRenamed
app_pages/game_detail.pyAdded+42
pages/home.py → app_pages/home.pyRenamed
pages/points_tracker.py → app_pages/points_tracker.pyRenamed+39-105
pages/skull_king.py → app_pages/skull_king.pyRenamed
requirements.txt-1
src/cookie_token_store.py+53-26
src/scoreboard.pyAdded+111
src/sheets_backend.py+183-32
src/workbook_access.pyAdded+21