# -*- coding: utf-8 -*- """ gates — browser-bridge glue + the app's hard gates. - require_desktop() : HARD-block phones/tablets (server-side st.stop()). - require_local_network() : HARD gate — the one-time Local Network Access "Allow". - fetch_signers_for_po(po) : signer/TOR fetch that runs in the USER'S browser. - signer_from_lookup(role) : fast path — signer name from the loaded PO row. Everything here shares one property: it needs the user's BROWSER (via streamlit_js_eval), because the HF server cannot reach the PTT-internal gateway — only the user's browser on the PTT network can. """ import os import json import streamlit as st import streamlit.components.v1 as components import signer_lookup # Browser-side JS bridge: runs the signer fetch in the USER'S browser, which — unlike the HF # server — can reach the PTT-internal gateway after the user grants the one-time Local Network # Access "Allow" (Chrome/Edge 142+). Optional import so the app still runs (manual entry) if absent. try: from streamlit_js_eval import streamlit_js_eval except Exception: # noqa: BLE001 streamlit_js_eval = None # ============================================================================= # ผู้ลงนาม: resolve a signer ROLE → the person's name. # ============================================================================= # Two sources, in order: (1) the PO row from DATA_URL if it already carries # approverName/chairmanName (fast, no fetch); else (2) a LIVE fetch in the USER'S browser to # the SMP gateway — the HF server can't reach the private gateway, but the user's browser can # after a one-time Local Network Access "Allow" (Chrome/Edge 142+; verified reachable 2026-06-30). # Manual entry is always the fallback. See signer_lookup.build_signers_js for the browser chain. SIGNER_COLUMN = signer_lookup.SIGNER_COLUMN # no-reply read-only bearer (Space secret) — injected into the browser-side fetch. SMP_TOKEN = os.environ.get("SMP_TOKEN", "").strip() def signer_from_lookup(role): """Fast path: signer name from the loaded PO row (lookup_data), or '' if the column is absent.""" if not role: return "" data = st.session_state.get("lookup_data") or {} col = SIGNER_COLUMN.get(signer_lookup.role_kind(role), "") return str(data.get(col) or "").strip() def fetch_signers_for_po(po): """Resolve {approver, chairman, ...} via a fetch in the user's browser (streamlit_js_eval). Returns a dict on success, {"error": ...} on failure, or None while still resolving (incl. before the user clicks the one-time Local Network Access 'Allow').""" po = (po or "").strip() if not po: return {"error": "no po"} cache = st.session_state.setdefault("_signers_cache", {}) if po in cache: return cache[po] if not streamlit_js_eval: return {"error": "browser bridge unavailable"} if not SMP_TOKEN: return {"error": "no SMP_TOKEN configured"} js = signer_lookup.build_signers_js(po, SMP_TOKEN) res = streamlit_js_eval(js_expressions=js, key=f"sig_{po}", want_output=True) if isinstance(res, dict): cache[po] = res return res if isinstance(res, str) and res.strip().startswith("{"): try: d = json.loads(res) cache[po] = d return d except Exception: # noqa: BLE001 return {"error": "bad response"} return None # still resolving def require_local_network(): """Background reachability check: silently probe the SMP gateway on load — which auto-triggers the one-time Local Network Access 'Allow' prompt. If granted → seamless, no UI. ONLY if the user did NOT allow (blocked / off-network) do we surface a notification with recovery + retry. App stays gated until allowed (no manual bypass, per product decision).""" if st.session_state.get("lna_ok"): return if not streamlit_js_eval or not SMP_TOKEN: st.error(":material/error: ระบบยังไม่พร้อมใช้งาน (ผู้ดูแลระบบยังไม่ได้ตั้งค่า SMP_TOKEN) — โปรดแจ้งผู้ดูแล") st.stop() # auto-fire the probe in the background (fresh key per attempt so 'ลองใหม่' re-fetches) attempt = st.session_state.get("lna_attempt", 0) res = streamlit_js_eval(js_expressions=signer_lookup.build_probe_js(SMP_TOKEN), key=f"lna_probe_{attempt}", want_output=True) ok = None if isinstance(res, str) and res.strip().startswith("{"): try: ok = bool(json.loads(res).get("ok")) except Exception: # noqa: BLE001 ok = False if ok: st.session_state["lna_ok"] = True return # granted → seamless, no UI shown if ok is False: # user did not allow / blocked / off-network _assets = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets") _, mid, _ = st.columns([1, 2, 1]) with mid: st.warning(":material/lan: **ต้อง “อนุญาต” ให้แอปเชื่อมต่อ เพื่อดึงข้อมูลให้อัตโนมัติ**") st.markdown("**วิธีที่ 1 — ถ้ามีกล่องเด้งขึ้น: กดปุ่ม “Allow / อนุญาต”**") st.image(os.path.join(_assets, "lna_allow.png"), width=340) st.markdown("**วิธีที่ 2 — ถ้าไม่เห็นกล่อง หรือเผลอกด “Block”: ทำตาม 3 ขั้นตอนนี้**") st.image(os.path.join(_assets, "lna_unblock.png"), width=430) if st.button(":material/refresh: โหลดหน้าใหม่", type="primary", use_container_width=True): components.html("", height=0) st.caption("ℹ️ ต้องเชื่อมต่อเครือข่าย PTT หรือ VPN ด้วย") st.stop() # pending (the Allow prompt is open) → wait quietly _, mid, _ = st.columns([1, 2, 1]) with mid: st.info(":material/hourglass_top: กำลังเชื่อมต่อระบบ…") st.stop() # ============================================================================= # Desktop-only gate — the wide two-column form is not usable on a phone. # ============================================================================= # Detect a real mobile device in the browser: mobile/tablet user-agent, OR a # touch-only device (coarse pointer + no hover) on a narrow screen. _MOBILE_DETECT_JS = r""" (() => { try { const ua = navigator.userAgent || ""; const uaMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|Tablet|Silk/i.test(ua); const mm = (q) => (window.matchMedia && window.matchMedia(q).matches) || false; const coarse = mm('(pointer: coarse)'), noHover = mm('(hover: none)'); const narrow = Math.min((window.screen && window.screen.width) || 9999, window.innerWidth || 9999) <= 900; return JSON.stringify({mobile: !!(uaMobile || (coarse && noHover && narrow))}); } catch (e) { return JSON.stringify({mobile: false}); } })() """ def _mobile_notice(): """Always-visible fallback notice (the CSS .mobile-block overlay normally covers this).""" st.markdown( "
" "
🖥️
" "
" "กรุณาใช้งานบนคอมพิวเตอร์
" "
" "ปัจจุบัน ยังไม่รองรับการใช้งานในมือถือ
ขออภัยในความไม่สะดวก
", unsafe_allow_html=True, ) def require_desktop(): """HARD-block phones/tablets so a mobile user cannot progress (not even to login). The CSS .mobile-block overlay covers narrow viewports instantly (no flash); this adds a server-side st.stop() once the browser reports a mobile device. Detection runs once.""" if st.session_state.get("is_mobile") is True: _mobile_notice() st.stop() if st.session_state.get("is_mobile") is False or not streamlit_js_eval: return # known-desktop, or can't detect (CSS still covers) res = streamlit_js_eval(js_expressions=_MOBILE_DETECT_JS, key="mobile_detect", want_output=True) if isinstance(res, str) and res.strip().startswith("{"): try: mob = bool(json.loads(res).get("mobile")) except Exception: # noqa: BLE001 mob = False st.session_state["is_mobile"] = mob if mob: _mobile_notice() st.stop() # res is None (detection still resolving) → CSS overlay keeps mobile users covered meanwhile