Spaces:
Sleeping
Sleeping
File size: 9,653 Bytes
84c98ae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | # -*- 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("<script>window.parent.location.reload()</script>", 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(
"<div style='max-width:360px;margin:16vh auto 0;text-align:center;background:#fff;"
"border:1px solid rgba(214,128,72,0.18);border-radius:24px;padding:2.2rem 1.7rem;"
"box-shadow:0 24px 60px rgba(214,120,60,0.22)'>"
"<div style='font-size:2.2rem;margin-bottom:0.7rem'>🖥️</div>"
"<div style='color:#3E2A1E;font-weight:800;font-size:1.3rem;margin-bottom:0.5rem'>"
"กรุณาใช้งานบนคอมพิวเตอร์</div>"
"<div style='color:#6E5848;font-weight:600;font-size:1rem;line-height:1.55'>"
"ปัจจุบัน ยังไม่รองรับการใช้งานในมือถือ<br>ขออภัยในความไม่สะดวก</div></div>",
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
|