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
 
 
 
 
 
 
 
 
 
4f5b15c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75f3c4a
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <title>Timestral 后台</title>
  <style>
    :root {
      --bg: #f6f4f1;
      --card: #fff;
      --border: #e8ddd2;
      --text: #1f1520;
      --muted: #6b5a62;
      --accent: #4dbbeb;
      --danger: #c62828;
      --ok: #2e7d32;
      --radius: 12px;
      --font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: var(--font);
      background: var(--bg);
      color: var(--text);
      line-height: 1.45;
      font-size: 14px;
      padding: 16px;
      max-width: 960px;
      margin: 0 auto;
      min-height: 100dvh;
    }
    h1 { font-size: 1.35rem; margin-bottom: 4px; }
    .sub { color: var(--muted); font-size: 12px; margin-bottom: 16px; }
    .key-row {
      display: flex; flex-wrap: wrap; gap: 8px; align-items: center;
      margin-bottom: 16px; padding: 12px; background: var(--card);
      border: 1px solid var(--border); border-radius: var(--radius);
    }
    .key-row label { font-size: 12px; color: var(--muted); white-space: nowrap; }
    .key-row input[type="password"],
    .key-row input[type="text"] {
      flex: 1; min-width: 160px; padding: 8px 10px;
      border: 1px solid var(--border); border-radius: 8px;
      font-size: 14px; background: #fffaf6;
    }
    button {
      padding: 8px 14px; border: none; border-radius: 8px;
      background: var(--accent); color: #fff; font-weight: 600;
      cursor: pointer; font-size: 13px;
    }
    button:disabled { opacity: 0.55; cursor: wait; }
    button.secondary { background: #6b5a62; }
    .msg {
      padding: 10px 12px; border-radius: 8px; margin-bottom: 14px;
      font-size: 13px; display: none;
    }
    .msg.err { display: block; background: #fdecea; color: var(--danger); border: 1px solid #f5c6c2; }
    .msg.ok { display: block; background: #e8f5e9; color: var(--ok); border: 1px solid #c8e6c9; }
    .msg.note { display: block; background: #eef7fb; color: #255; border: 1px solid #c5e4f0; }
    .cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
      gap: 10px; margin-bottom: 18px;
    }
    .card {
      background: var(--card); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 12px 14px;
    }
    .card .label { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
    .card .val { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.02em; }
    .card .hint { font-size: 11px; color: var(--muted); margin-top: 2px; }
    section { margin-bottom: 20px; }
    section h2 { font-size: 1rem; margin-bottom: 8px; }
    .table-wrap {
      overflow-x: auto; background: var(--card);
      border: 1px solid var(--border); border-radius: var(--radius);
    }
    table { width: 100%; border-collapse: collapse; font-size: 13px; }
    th, td { padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--border); white-space: nowrap; }
    th { background: #fff8f0; color: var(--muted); font-weight: 600; font-size: 12px; }
    tr:last-child td { border-bottom: none; }
    .empty { color: var(--muted); padding: 14px; font-size: 13px; }
    .toolbar { display: flex; gap: 8px; margin-bottom: 12px; flex-wrap: wrap; }
    a.home { color: var(--accent); font-size: 12px; text-decoration: none; }
    a.home:hover { text-decoration: underline; }
    .auth-note {
      display: none; margin-bottom: 16px; padding: 10px 12px;
      background: var(--card); border: 1px solid var(--border);
      border-radius: var(--radius); font-size: 13px; color: var(--muted);
      align-items: center; gap: 8px; flex-wrap: wrap;
    }
    .auth-note.visible { display: flex; }
    .site-btn.active { border-color: #111; font-weight: 600; background: #eee; }
  </style>
</head>
<body>
  <h1>Timestral 后台</h1>
  <p class="sub">访问与 X 登录统计 · <a class="home" href="/">返回看板</a></p>

  <div id="authNote" class="auth-note"></div>

  <div class="key-row" id="keyRow">
    <label for="adminKey">管理密钥</label>
    <input id="adminKey" type="password" autocomplete="off" placeholder="ADMIN_STATS_KEY" />
    <button type="button" id="btnLoad">查看</button>
    <button type="button" id="btnRefresh" class="secondary" disabled>刷新</button>
  </div>

  <div class="key-row" id="siteSwitch" hidden>
    <span>站点</span>
    <button type="button" class="secondary site-btn active" data-site="crypto-vol-live">气泡图看板</button>
    <button type="button" class="secondary site-btn" data-site="timestral-candle-forecast">K线预测页</button>
  </div>

  <div id="msg" class="msg"></div>

  <div class="cards" id="cards" hidden>
    <div class="card"><div class="label">今日浏览次数</div><div class="val" id="cTodayPv">—</div><div class="hint" id="cToday">—</div></div>
    <div class="card"><div class="label">今日独立浏览器</div><div class="val" id="cTodayUv">—</div><div class="hint" id="cTodayUvHint">匿名编号,不是人数</div></div>
    <div class="card"><div class="label">近 5 分钟活跃浏览器</div><div class="val" id="cLast5mUv">—</div><div class="hint" id="cLast5mHint">仍打开页面的独立浏览器</div></div>
    <div class="card"><div class="label">累计浏览次数</div><div class="val" id="cTotalPv">—</div></div>
    <div class="card"><div class="label">累计独立浏览器</div><div class="val" id="cTotalUv">—</div></div>
    <div class="card"><div class="label">登录用户数</div><div class="val" id="cUsers">—</div></div>
  </div>

  <section id="secDays" hidden>
    <h2>近 7 天访问</h2>
    <div class="table-wrap">
      <table>
        <thead><tr><th>日期</th><th>PV</th><th>UV</th></tr></thead>
        <tbody id="daysBody"></tbody>
      </table>
    </div>
  </section>

  <section id="secRefs" hidden>
    <h2>来源域名</h2>
    <div class="table-wrap">
      <table>
        <thead><tr><th>来源</th><th>次数</th></tr></thead>
        <tbody id="refsBody"></tbody>
      </table>
    </div>
  </section>

  <section id="secUsers" hidden>
    <h2>X 登录用户(气泡看板登录,不是访问计数)</h2>
    <div class="table-wrap">
      <table>
        <thead><tr><th>用户名</th><th>X ID</th><th>首次登录</th><th>最近活跃</th></tr></thead>
        <tbody id="usersBody"></tbody>
      </table>
    </div>
  </section>

  <script>
    (function () {
      var KEY_STORE = "timestral_admin_stats_key";
      var elKey = document.getElementById("adminKey");
      var elMsg = document.getElementById("msg");
      var elKeyRow = document.getElementById("keyRow");
      var elAuthNote = document.getElementById("authNote");
      var btnLoad = document.getElementById("btnLoad");
      var btnRefresh = document.getElementById("btnRefresh");
      var authMode = null; // "x" | "key" | null
      var refreshBtnOnly = null;

      function showMsg(text, kind) {
        elMsg.textContent = text || "";
        elMsg.className = "msg" + (kind ? " " + kind : "");
        if (!text) elMsg.style.display = "none";
      }

      function getKey() {
        return (elKey.value || "").trim();
      }

      function saveKey(k) {
        try { localStorage.setItem(KEY_STORE, k); } catch (e) {}
      }

      function loadStoredKey() {
        try {
          var local = localStorage.getItem(KEY_STORE) || "";
          if (local) return local;
          var sess = sessionStorage.getItem(KEY_STORE) || "";
          if (sess) {
            try { localStorage.setItem(KEY_STORE, sess); } catch (e2) {}
            try { sessionStorage.removeItem(KEY_STORE); } catch (e3) {}
            return sess;
          }
          return "";
        } catch (e) { return ""; }
      }

      function hideKeyRow(noteHtml) {
        elKeyRow.style.display = "none";
        if (noteHtml) {
          elAuthNote.innerHTML = noteHtml;
          elAuthNote.classList.add("visible");
          if (!refreshBtnOnly) {
            refreshBtnOnly = document.createElement("button");
            refreshBtnOnly.type = "button";
            refreshBtnOnly.className = "secondary";
            refreshBtnOnly.textContent = "刷新";
            refreshBtnOnly.addEventListener("click", function () { fetchStats(true); });
            elAuthNote.appendChild(refreshBtnOnly);
          }
        }
      }

      function showKeyRow() {
        elKeyRow.style.display = "";
        elAuthNote.classList.remove("visible");
      }

      function esc(s) {
        return String(s == null ? "" : s)
          .replace(/&/g, "&amp;").replace(/</g, "&lt;")
          .replace(/>/g, "&gt;").replace(/"/g, "&quot;");
      }

      var lastStats = null;
      var currentSite = "crypto-vol-live";

      function render(data) {
        lastStats = data;
        var sites = data.sites || {};
        var v = sites[currentSite] || data.visits || {};
        document.getElementById("siteSwitch").hidden = false;
        document.querySelectorAll(".site-btn").forEach(function (b) {
          if (b.getAttribute("data-site") === currentSite) b.classList.add("active");
          else b.classList.remove("active");
        });
        document.getElementById("cards").hidden = false;
        document.getElementById("cTodayPv").textContent = v.today_pv != null ? v.today_pv : "—";
        document.getElementById("cTodayUv").textContent = v.today_uv != null ? v.today_uv : "—";
        document.getElementById("cLast5mUv").textContent = v.last_5m_uv != null ? v.last_5m_uv : "—";
        document.getElementById("cTotalPv").textContent = v.total_pv != null ? v.total_pv : "—";
        document.getElementById("cTotalUv").textContent = v.total_uv != null ? v.total_uv : "—";
        document.getElementById("cUsers").textContent = data.unique_users != null ? data.unique_users : "—";
        document.getElementById("cToday").textContent = v.today ? ("日期 " + v.today + "(上海时区)") : "";
        var kline = currentSite === "timestral-candle-forecast";
        document.getElementById("cTodayUvHint").textContent = kline
          ? "匿名浏览器编号,不是人数;清缓存或换浏览器会算新的"
          : "按哈希 IP+UA 计(历史定义,未改)";
        document.getElementById("cLast5mHint").textContent = kline
          ? "近5分钟有心跳的独立浏览器,不是实时人数"
          : "近5分钟有记录的独立哈希";

        var days = v.last_7_days || [];
        var daysBody = document.getElementById("daysBody");
        document.getElementById("secDays").hidden = false;
        if (!days.length) {
          daysBody.innerHTML = '<tr><td colspan="3" class="empty">暂无访问记录</td></tr>';
        } else {
          daysBody.innerHTML = days.map(function (r) {
            return "<tr><td>" + esc(r.day) + "</td><td>" + esc(r.pv) + "</td><td>" + esc(r.uv) + "</td></tr>";
          }).join("");
        }

        var users = data.users || [];
        var usersBody = document.getElementById("usersBody");
        document.getElementById("secUsers").hidden = false;
        if (!users.length) {
          usersBody.innerHTML = '<tr><td colspan="4" class="empty">暂无登录用户</td></tr>';
        } else {
          usersBody.innerHTML = users.map(function (u) {
            var name = u.username ? "@" + u.username : "—";
            return "<tr><td>" + esc(name) + "</td><td>" + esc(u.x_id) +
              "</td><td>" + esc(u.created_at) + "</td><td>" + esc(u.updated_at) + "</td></tr>";
          }).join("");
        }

        var refs = v.referrers || [];
        var refsBody = document.getElementById("refsBody");
        document.getElementById("secRefs").hidden = false;
        if (!refs.length) {
          refsBody.innerHTML = '<tr><td colspan="2" class="empty">暂无来源记录</td></tr>';
        } else {
          refsBody.innerHTML = refs.map(function (r) {
            return "<tr><td>" + esc(r.host) + "</td><td>" + esc(r.hits) + "</td></tr>";
          }).join("");
        }

        if (v.note) showMsg(v.note, "note");
        else showMsg("已加载 · 登录用户 " + (data.unique_users || 0) + " · session " + (data.session_rows || 0), "ok");
      }

      document.getElementById("siteSwitch").addEventListener("click", function (ev) {
        var btn = ev.target && ev.target.closest ? ev.target.closest(".site-btn") : null;
        if (!btn) return;
        currentSite = btn.getAttribute("data-site") || "crypto-vol-live";
        if (lastStats) render(lastStats);
      });

      function applyAuthUI(data) {
        authMode = (data && data.auth) || authMode;
        if (authMode === "x") {
          fetch("/api/auth/status", { credentials: "same-origin", cache: "no-store" })
            .then(function (r) { return r.ok ? r.json() : null; })
            .then(function (st) {
              var u = st && st.user && st.user.username ? "@" + st.user.username : "X";
              hideKeyRow('<span>已用 X 登录 · ' + esc(u) + '</span>');
            })
            .catch(function () {
              hideKeyRow("<span>已用 X 登录</span>");
            });
        } else if (authMode === "key") {
          // keep key row; key remembered in localStorage
          showKeyRow();
          btnRefresh.disabled = false;
        }
      }

      function fetchStats(preferCookie) {
        var key = getKey();
        var headers = {};
        var useCookie = preferCookie === true || authMode === "x";
        if (!useCookie) {
          if (!key) {
            showMsg("请先输入管理密钥(Space 密钥 ADMIN_STATS_KEY),或先在看板用 X 登录", "err");
            return;
          }
          headers["X-Admin-Key"] = key;
          saveKey(key);
        }

        btnLoad.disabled = true;
        btnRefresh.disabled = true;
        if (refreshBtnOnly) refreshBtnOnly.disabled = true;
        showMsg("加载中…", "note");
        fetch("/api/auth/admin/stats", {
          method: "GET",
          headers: headers,
          credentials: "same-origin",
          cache: "no-store"
        }).then(function (res) {
          if (res.status === 403) throw new Error("未授权(403):请用看板 X 登录,或输入正确密钥");
          if (!res.ok) throw new Error("请求失败 HTTP " + res.status);
          return res.json();
        }).then(function (data) {
          if (!data || !data.ok) throw new Error((data && data.detail) || "接口返回异常");
          if (data.auth === "key" && key) saveKey(key);
          render(data);
          applyAuthUI(data);
          btnRefresh.disabled = false;
          if (refreshBtnOnly) refreshBtnOnly.disabled = false;
        }).catch(function (err) {
          showMsg(String(err.message || err), "err");
          btnRefresh.disabled = false;
          if (refreshBtnOnly) refreshBtnOnly.disabled = false;
          if (preferCookie) showKeyRow();
        }).finally(function () {
          btnLoad.disabled = false;
        });
      }

      btnLoad.addEventListener("click", function () { fetchStats(false); });
      btnRefresh.addEventListener("click", function () {
        fetchStats(authMode === "x");
      });
      elKey.addEventListener("keydown", function (e) {
        if (e.key === "Enter") fetchStats(false);
      });

      // Prefer header; strip ?key= from URL after capturing once (bookmark convenience)
      var params = new URLSearchParams(location.search);
      var qKey = (params.get("key") || "").trim();
      var stored = loadStoredKey();
      if (qKey) {
        elKey.value = qKey;
        saveKey(qKey);
        if (history.replaceState) {
          params.delete("key");
          var clean = location.pathname + (params.toString() ? "?" + params.toString() : "") + location.hash;
          history.replaceState(null, "", clean);
        }
        fetchStats(false);
      } else {
        // 1) Try cookie / X session first (no key)
        btnLoad.disabled = true;
        showMsg("加载中…", "note");
        fetch("/api/auth/admin/stats", {
          method: "GET",
          credentials: "same-origin",
          cache: "no-store"
        }).then(function (res) {
          if (res.status === 403) return null;
          if (!res.ok) throw new Error("请求失败 HTTP " + res.status);
          return res.json();
        }).then(function (data) {
          if (data && data.ok) {
            render(data);
            applyAuthUI(data);
            btnRefresh.disabled = false;
            return;
          }
          // Fall back to stored localStorage key
          if (stored) {
            elKey.value = stored;
            fetchStats(false);
          } else {
            showKeyRow();
            showMsg("请用看板 X 登录后打开本页,或输入管理密钥", "note");
          }
        }).catch(function (err) {
          if (stored) {
            elKey.value = stored;
            fetchStats(false);
          } else {
            showKeyRow();
            showMsg(String(err.message || err), "err");
          }
        }).finally(function () {
          btnLoad.disabled = false;
        });
      }
    })();
  </script>
</body>
</html>