yangtb24 commited on
Commit
ce156e0
·
verified ·
1 Parent(s): c99d284

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +13 -0
  2. app.py +476 -0
  3. requirements.txt +5 -0
  4. templates/dashboard.html +306 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt requirements.txt
6
+
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ COPY . .
10
+
11
+ EXPOSE 7860
12
+
13
+ CMD ["gunicorn", "app:app", "-w", "2", "--threads", "2", "-b", "0.0.0.0:7860"]
app.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import threading
5
+ from datetime import datetime
6
+ from flask import Flask, request, jsonify, render_template_string, redirect, url_for, session
7
+ import requests
8
+ from apscheduler.schedulers.background import BackgroundScheduler
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+ app = Flask(__name__)
14
+ app.secret_key = os.urandom(24)
15
+
16
+ LOGIN_URL = "https://api-card.infini.money/user/login"
17
+ PROFILE_URL = "https://api-card.infini.money/user/profile"
18
+ CARD_INFO_URL = "https://api-card.infini.money/card/info"
19
+ FRONTEND_PASSWORD = os.getenv("PASSWORD")
20
+ ACCOUNTS_JSON = os.getenv("ACCOUNTS")
21
+
22
+ accounts_data = {}
23
+ scheduler = BackgroundScheduler(daemon=True)
24
+ data_lock = threading.Lock()
25
+
26
+ def parse_accounts():
27
+ global accounts_data
28
+ if not ACCOUNTS_JSON:
29
+ print("错误: ACCOUNTS 环境变量未设置。")
30
+ return False
31
+ try:
32
+ accounts_list = json.loads(ACCOUNTS_JSON)
33
+ if not isinstance(accounts_list, list):
34
+ print("错误: ACCOUNTS 环境变量必须是一个 JSON 数组。")
35
+ return False
36
+
37
+ temp_accounts_data = {}
38
+ for acc in accounts_list:
39
+ if isinstance(acc, dict) and "email" in acc and "password" in acc:
40
+ temp_accounts_data[acc["email"]] = {
41
+ "password": acc["password"],
42
+ "token": None,
43
+ "profile": None,
44
+ "last_login_success": None,
45
+ "last_profile_success": None,
46
+ "last_login_attempt": None,
47
+ "last_profile_attempt": None,
48
+ "login_error": None,
49
+ "profile_error": None,
50
+ "cards_info": None,
51
+ "last_card_info_success": None,
52
+ "last_card_info_attempt": None,
53
+ "card_info_error": None,
54
+ }
55
+ else:
56
+ print(f"警告: ACCOUNTS 中的条目格式不正确: {acc}")
57
+
58
+ with data_lock:
59
+ accounts_data = temp_accounts_data
60
+ print(f"成功加载 {len(accounts_data)} 个账户。")
61
+ return True
62
+ except json.JSONDecodeError:
63
+ print("错误: ACCOUNTS 环境变量不是有效的 JSON 格式。")
64
+ return False
65
+
66
+ def api_login(email, password):
67
+ payload = {"email": email, "password": password}
68
+ try:
69
+ response = requests.post(LOGIN_URL, json=payload, timeout=10)
70
+ response.raise_for_status()
71
+ data = response.json()
72
+ cookies = response.cookies
73
+ jwt_token = cookies.get("jwt_token")
74
+
75
+ if data.get("code") == 0 and jwt_token:
76
+ return jwt_token, None
77
+ else:
78
+ error_message = data.get('message', "未知登录错误")
79
+ if data.get("code") == 0 and not jwt_token:
80
+ error_message = "响应成功但未返回 jwt_token。"
81
+ return None, f"{error_message} (Code: {data.get('code')})"
82
+ except requests.exceptions.Timeout:
83
+ return None, "登录请求超时。"
84
+ except requests.exceptions.RequestException as e:
85
+ return None, f"登录请求错误: {str(e)}"
86
+ except json.JSONDecodeError:
87
+ return None, "登录响应不是有效的 JSON。"
88
+
89
+ def get_api_profile(email, token):
90
+ if not token:
91
+ return None, "Token 为空,无法获取 Profile。"
92
+
93
+ cookies = {"jwt_token": token}
94
+ try:
95
+ response = requests.get(PROFILE_URL, cookies=cookies, timeout=10)
96
+ response.raise_for_status()
97
+ profile_data = response.json()
98
+ if profile_data.get("code") == 0 and profile_data.get("data"):
99
+ return profile_data.get("data"), None
100
+ else:
101
+ error_message = profile_data.get('message', "未知 Profile 错误")
102
+ if profile_data.get("code") == 0 and not profile_data.get("data"):
103
+ error_message = "响应成功但未返回 Profile 数据。"
104
+ return None, f"{error_message} (Code: {profile_data.get('code')})"
105
+ except requests.exceptions.Timeout:
106
+ return None, "获取 Profile 请求超时。"
107
+ except requests.exceptions.RequestException as e:
108
+ return None, f"获取 Profile 请求错误: {str(e)}"
109
+ except json.JSONDecodeError:
110
+ return None, "Profile 响应不是有效的 JSON。"
111
+
112
+ def get_api_card_info(email, token):
113
+ if not token:
114
+ return None, "Token 为空,无法获取卡片信息。"
115
+
116
+ cookies = {"jwt_token": token}
117
+ print(f"[{datetime.now()}] 尝试为账户 {email} 获取卡片信息...")
118
+ try:
119
+ response = requests.get(CARD_INFO_URL, cookies=cookies, timeout=10)
120
+ response.raise_for_status()
121
+ card_data = response.json()
122
+ if card_data.get("code") == 0 and "items" in card_data.get("data", {}):
123
+ items = card_data["data"]["items"]
124
+ if items:
125
+ item = items[0]
126
+ provider_bin = None
127
+ if item.get("provider"):
128
+ parts = item["provider"].split('_')
129
+ if len(parts) > 1 and parts[-1].isdigit():
130
+ provider_bin = parts[-1]
131
+
132
+ processed_card_info = {
133
+ "provider_bin": provider_bin,
134
+ "card_last_four_digits": item.get("card_last_four_digits"),
135
+ "consumption_limit": item.get("consumption_limit"),
136
+ "status": item.get("status"),
137
+ "name": item.get("name")
138
+ }
139
+ return processed_card_info, None
140
+ else:
141
+ return None, None
142
+ elif card_data.get("code") == 0 and not card_data.get("data", {}).get("items"):
143
+ return None, None
144
+ else:
145
+ error_message = card_data.get('message', "未知卡片信息错误")
146
+ if card_data.get("code") == 0 and not card_data.get("data"):
147
+ error_message = "响应成功但未返回卡片数据。"
148
+ return None, f"{error_message} (Code: {card_data.get('code')})"
149
+ except requests.exceptions.Timeout:
150
+ return None, "获取卡片信息请求超时。"
151
+ except requests.exceptions.RequestException as e:
152
+ return None, f"获取卡片信息请求错误: {str(e)}"
153
+ except json.JSONDecodeError:
154
+ return None, "卡片信息响应不是有效的 JSON。"
155
+
156
+ def login_and_store_token(email):
157
+ global accounts_data
158
+ with data_lock:
159
+ account_info = accounts_data.get(email)
160
+ if not account_info:
161
+ print(f"错误: 账户 {email} 未找到。")
162
+ return
163
+
164
+ password = account_info["password"]
165
+ print(f"[{datetime.now()}] 尝试为账户 {email} 登录...")
166
+
167
+ token, error = api_login(email, password)
168
+
169
+ with data_lock:
170
+ accounts_data[email]["last_login_attempt"] = datetime.now()
171
+ if token:
172
+ accounts_data[email]["token"] = token
173
+ accounts_data[email]["last_login_success"] = True
174
+ accounts_data[email]["login_error"] = None
175
+ print(f"[{datetime.now()}] 账户 {email} 登录成功。")
176
+ else:
177
+ accounts_data[email]["token"] = None
178
+ accounts_data[email]["last_login_success"] = False
179
+ accounts_data[email]["login_error"] = error
180
+ print(f"[{datetime.now()}] 账户 {email} 登录失败: {error}")
181
+
182
+ def fetch_and_store_profile(email):
183
+ global accounts_data
184
+ with data_lock:
185
+ account_info = accounts_data.get(email)
186
+ if not account_info:
187
+ print(f"错误: 账户 {email} 未找到 (fetch_and_store_profile)。")
188
+ return
189
+ token = account_info.get("token")
190
+
191
+ if not token:
192
+ print(f"[{datetime.now()}] 账户 {email} 没有有效的 token,跳过获取 Profile。")
193
+ with data_lock:
194
+ accounts_data[email]["last_profile_attempt"] = datetime.now()
195
+ accounts_data[email]["last_profile_success"] = False
196
+ accounts_data[email]["profile_error"] = "无有效 Token"
197
+ accounts_data[email]["profile"] = None
198
+ return
199
+
200
+ print(f"[{datetime.now()}] 尝试为账户 {email} 获取 Profile...")
201
+ profile, error = get_api_profile(email, token)
202
+
203
+ with data_lock:
204
+ accounts_data[email]["last_profile_attempt"] = datetime.now()
205
+ if profile:
206
+ accounts_data[email]["profile"] = profile
207
+ accounts_data[email]["last_profile_success"] = True
208
+ accounts_data[email]["profile_error"] = None
209
+ print(f"[{datetime.now()}] 账户 {email} 获取 Profile 成功。")
210
+ else:
211
+ accounts_data[email]["profile"] = None
212
+ accounts_data[email]["last_profile_success"] = False
213
+ accounts_data[email]["profile_error"] = error
214
+ print(f"[{datetime.now()}] 账户 {email} 获取 Profile 失败: {error}")
215
+ if error and ("token" in error.lower() or "auth" in error.lower() or "登录" in error.lower()):
216
+ print(f"[{datetime.now()}] 账户 {email} 获取 Profile 失败,疑似 Token 失效,将尝试重新登录。")
217
+ accounts_data[email]["token"] = None
218
+ return
219
+
220
+ print(f"[{datetime.now()}] Profile 获取成功,继续为账户 {email} 获取卡片信息...")
221
+ cards_info, card_error = get_api_card_info(email, token)
222
+
223
+ with data_lock:
224
+ accounts_data[email]["last_card_info_attempt"] = datetime.now()
225
+ if cards_info:
226
+ accounts_data[email]["cards_info"] = cards_info
227
+ accounts_data[email]["last_card_info_success"] = True
228
+ accounts_data[email]["card_info_error"] = None
229
+ print(f"[{datetime.now()}] 账户 {email} 获取卡片信息成功。")
230
+ elif card_error:
231
+ accounts_data[email]["cards_info"] = None
232
+ accounts_data[email]["last_card_info_success"] = False
233
+ accounts_data[email]["card_info_error"] = card_error
234
+ print(f"[{datetime.now()}] 账户 {email} 获取卡片信息失败: {card_error}")
235
+ else:
236
+ accounts_data[email]["cards_info"] = None
237
+ accounts_data[email]["last_card_info_success"] = True
238
+ accounts_data[email]["card_info_error"] = None
239
+ print(f"[{datetime.now()}] 账户 {email} 获取卡片信息成功,但无卡片数据。")
240
+
241
+ def initial_login_all_accounts():
242
+ print("程序启动,开始为所有账户执行初始登录...")
243
+ threads = []
244
+ with data_lock:
245
+ emails_to_login = list(accounts_data.keys())
246
+
247
+ for email in emails_to_login:
248
+ thread = threading.Thread(target=login_and_store_token, args=(email,))
249
+ threads.append(thread)
250
+ thread.start()
251
+ for thread in threads:
252
+ thread.join()
253
+ print("所有账户初始登录尝试完成。")
254
+
255
+ def scheduled_login_all_accounts():
256
+ print(f"[{datetime.now()}] 定时任务:开始为所有账户重新登录...")
257
+ threads = []
258
+ with data_lock:
259
+ emails_to_login = list(accounts_data.keys())
260
+
261
+ for email in emails_to_login:
262
+ thread = threading.Thread(target=login_and_store_token, args=(email,))
263
+ threads.append(thread)
264
+ thread.start()
265
+ for thread in threads:
266
+ thread.join()
267
+ print(f"[{datetime.now()}] 定时任务:所有账户重新登录尝试完成。")
268
+ scheduled_fetch_all_profiles()
269
+
270
+ def scheduled_fetch_all_profiles():
271
+ print(f"[{datetime.now()}] 定时任务:开始为所有账户获取 Profile...")
272
+ threads = []
273
+ with data_lock:
274
+ emails_to_fetch = list(accounts_data.keys())
275
+
276
+ for email in emails_to_fetch:
277
+ thread = threading.Thread(target=fetch_and_store_profile, args=(email,))
278
+ threads.append(thread)
279
+ thread.start()
280
+ for thread in threads:
281
+ thread.join()
282
+ print(f"[{datetime.now()}] 定时任务:所有账户获取 Profile 尝试完成。")
283
+
284
+ LOGIN_FORM_HTML = """
285
+ <!DOCTYPE html>
286
+ <html lang="zh-CN">
287
+ <head>
288
+ <meta charset="UTF-8">
289
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
290
+ <title>访问授权</title>
291
+ <style>
292
+ body {
293
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
294
+ display: flex;
295
+ justify-content: center;
296
+ align-items: center;
297
+ height: 100vh;
298
+ margin: 0;
299
+ background-color: #fff;
300
+ color: #000;
301
+ }
302
+ .login-container {
303
+ background-color: #fff;
304
+ padding: 40px;
305
+ border-radius: 8px;
306
+ box-shadow: 0 8px 30px rgba(0,0,0,0.1);
307
+ width: 100%;
308
+ max-width: 360px;
309
+ border: 1px solid #eaeaea;
310
+ }
311
+ h2 {
312
+ text-align: center;
313
+ color: #000;
314
+ font-weight: 600;
315
+ margin-bottom: 30px;
316
+ }
317
+ label {
318
+ display: block;
319
+ margin-bottom: 8px;
320
+ color: #444;
321
+ font-size: 14px;
322
+ }
323
+ input[type="password"] {
324
+ width: 100%;
325
+ padding: 12px;
326
+ margin-bottom: 20px;
327
+ border: 1px solid #ccc;
328
+ border-radius: 6px;
329
+ box-sizing: border-box;
330
+ background-color: #fff;
331
+ color: #000;
332
+ font-size: 16px;
333
+ }
334
+ input[type="password"]:focus {
335
+ border-color: #999;
336
+ outline: none;
337
+ box-shadow: 0 0 0 2px rgba(0,0,0,0.05);
338
+ }
339
+ input[type="submit"] {
340
+ width: 100%;
341
+ padding: 12px;
342
+ background-color: #000;
343
+ color: #fff;
344
+ border: none;
345
+ border-radius: 6px;
346
+ cursor: pointer;
347
+ font-size: 16px;
348
+ font-weight: 500;
349
+ transition: background-color 0.2s ease;
350
+ }
351
+ input[type="submit"]:hover {
352
+ background-color: #333;
353
+ }
354
+ .error {
355
+ color: #e53e3e;
356
+ text-align: center;
357
+ margin-bottom: 15px;
358
+ font-size: 14px;
359
+ }
360
+ </style>
361
+ </head>
362
+ <body>
363
+ <div class="login-container">
364
+ <h2>授权访问</h2>
365
+ {% if error %}
366
+ <p class="error">{{ error }}</p>
367
+ {% endif %}
368
+ <form method="post">
369
+ <label for="password">访问密码:</label>
370
+ <input type="password" id="password" name="password" required autofocus>
371
+ <input type="submit" value="继续">
372
+ </form>
373
+ </div>
374
+ </body>
375
+ </html>
376
+ """
377
+
378
+ @app.route('/', methods=['GET', 'POST'])
379
+ def login_frontend():
380
+ if not FRONTEND_PASSWORD:
381
+ return "错误: 前端密码 (PASSWORD 环境变量) 未设置。", 500
382
+
383
+ if 'logged_in' in session and session['logged_in']:
384
+ return redirect(url_for('dashboard'))
385
+
386
+ error = None
387
+ if request.method == 'POST':
388
+ entered_password = request.form.get('password')
389
+ if entered_password == FRONTEND_PASSWORD:
390
+ session['logged_in'] = True
391
+ return redirect(url_for('dashboard'))
392
+ else:
393
+ error = "密码错误!"
394
+ return render_template_string(LOGIN_FORM_HTML, error=error)
395
+
396
+ @app.route('/dashboard')
397
+ def dashboard():
398
+ if not ('logged_in' in session and session['logged_in']):
399
+ return redirect(url_for('login_frontend'))
400
+ return render_template_string(open('templates/dashboard.html', encoding='utf-8').read())
401
+
402
+ @app.route('/logout')
403
+ def logout():
404
+ session.pop('logged_in', None)
405
+ return redirect(url_for('login_frontend'))
406
+
407
+ @app.route('/api/data', methods=['GET'])
408
+ def get_all_data():
409
+ if not ('logged_in' in session and session['logged_in']):
410
+ return jsonify({"error": "未授权访问"}), 401
411
+
412
+ with data_lock:
413
+ display_data = {}
414
+ for email, data in accounts_data.items():
415
+ display_data[email] = {
416
+ "profile": data.get("profile"),
417
+ "last_login_success": data.get("last_login_success"),
418
+ "last_profile_success": data.get("last_profile_success"),
419
+ "last_login_attempt": data.get("last_login_attempt").isoformat() if data.get("last_login_attempt") else None,
420
+ "last_profile_attempt": data.get("last_profile_attempt").isoformat() if data.get("last_profile_attempt") else None,
421
+ "login_error": data.get("login_error"),
422
+ "profile_error": data.get("profile_error"),
423
+ "token_present": bool(data.get("token")),
424
+ "cards_info": data.get("cards_info"),
425
+ "last_card_info_success": data.get("last_card_info_success"),
426
+ "last_card_info_attempt": data.get("last_card_info_attempt").isoformat() if data.get("last_card_info_attempt") else None,
427
+ "card_info_error": data.get("card_info_error")
428
+ }
429
+ return jsonify(display_data)
430
+
431
+ @app.route('/api/refresh', methods=['POST'])
432
+ def manual_refresh_all_data():
433
+ if not ('logged_in' in session and session['logged_in']):
434
+ return jsonify({"error": "未授权访问"}), 401
435
+
436
+ print(f"[{datetime.now()}] 手动触发数据刷新...")
437
+ threading.Thread(target=scheduled_login_all_accounts).start()
438
+ return jsonify({"message": "刷新任务已启动,请稍后查看数据。"}), 202
439
+
440
+ if __name__ == '__main__':
441
+ if not FRONTEND_PASSWORD:
442
+ print("警告: PASSWORD 环境变量未设置,前端将无法登录。")
443
+ if not parse_accounts():
444
+ print("由于账户加载失败,程序将退出。请检查 ACCOUNTS 环境变量。")
445
+ else:
446
+ initial_login_all_accounts()
447
+ scheduled_fetch_all_profiles()
448
+
449
+ scheduler.add_job(scheduled_login_all_accounts, 'interval', days=3, id='job_login_all')
450
+ scheduler.add_job(scheduled_fetch_all_profiles, 'interval', minutes=30, id='job_fetch_profiles')
451
+
452
+ try:
453
+ scheduler.start()
454
+ print("定时任务已启动。")
455
+ print(f"APScheduler jobs: {scheduler.get_jobs()}")
456
+ except Exception as e:
457
+ print(f"启动 APScheduler 失败: {e}")
458
+
459
+ is_hf_space = os.getenv("SPACE_ID") is not None
460
+ if not is_hf_space:
461
+ app.run(host='0.0.0.0', port=7860, debug=True)
462
+
463
+ else:
464
+ if FRONTEND_PASSWORD and parse_accounts():
465
+ initial_login_all_accounts()
466
+ scheduled_fetch_all_profiles()
467
+ if not scheduler.running:
468
+ scheduler.add_job(scheduled_login_all_accounts, 'interval', days=3, id='job_login_all_gunicorn')
469
+ scheduler.add_job(scheduled_fetch_all_profiles, 'interval', minutes=30, id='job_fetch_profiles_gunicorn')
470
+ try:
471
+ scheduler.start()
472
+ print("APScheduler (Gunicorn) jobs started.")
473
+ except Exception as e:
474
+ print(f"Failed to start APScheduler (Gunicorn): {e}")
475
+ else:
476
+ print("Gunicorn: 未能正确初始化账户或密码未设置。")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Flask>=2.0
2
+ requests>=2.20
3
+ APScheduler>=3.0
4
+ python-dotenv>=0.15
5
+ gunicorn>=20.0
templates/dashboard.html ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>账户仪表盘</title>
7
+ <style>
8
+ body {
9
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
10
+ margin: 0;
11
+ background-color: #f7f7f7;
12
+ color: #333;
13
+ line-height: 1.6;
14
+ }
15
+ .container {
16
+ max-width: 1200px;
17
+ margin: 30px auto;
18
+ padding: 25px;
19
+ }
20
+ header {
21
+ display: flex;
22
+ justify-content: space-between;
23
+ align-items: center;
24
+ margin-bottom: 30px;
25
+ padding-bottom: 15px;
26
+ border-bottom: 1px solid #eaeaea;
27
+ }
28
+ header h1 {
29
+ margin: 0;
30
+ font-size: 26px;
31
+ color: #000;
32
+ font-weight: 600;
33
+ }
34
+ .actions button {
35
+ padding: 10px 18px;
36
+ background-color: #000;
37
+ color: #fff;
38
+ border: 1px solid #000;
39
+ border-radius: 6px;
40
+ cursor: pointer;
41
+ font-size: 14px;
42
+ margin-left: 12px;
43
+ transition: background-color 0.2s ease, color 0.2s ease;
44
+ }
45
+ .actions button:hover { background-color: #333; }
46
+ .actions button#logout-btn { background-color: #fff; color: #000; border: 1px solid #ccc;}
47
+ .actions button#logout-btn:hover { background-color: #f0f0f0; border-color: #bbb;}
48
+
49
+ #account-cards-container {
50
+ display: grid;
51
+ grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
52
+ gap: 25px;
53
+ }
54
+
55
+ .account-card {
56
+ padding: 25px;
57
+ background-color: #fff;
58
+ border-radius: 8px;
59
+ border: 1px solid #eaeaea;
60
+ box-shadow: 0 4px 15px rgba(0,0,0,0.05);
61
+ }
62
+
63
+ .account-info h3 {
64
+ margin-top: 0;
65
+ font-size: 18px;
66
+ color: #000;
67
+ border-bottom: 1px solid #eee;
68
+ padding-bottom: 10px;
69
+ margin-bottom: 15px;
70
+ font-weight: 500;
71
+ }
72
+ .account-info p { margin: 8px 0; font-size: 14px; }
73
+ .account-info p strong { color: #555; min-width: 160px; display: inline-block; font-weight: 500;}
74
+ .status-ok { color: #28a745; font-weight: bold; }
75
+ .status-error { color: #dc3545; font-weight: bold; }
76
+ .error-details {
77
+ font-size: 0.85em;
78
+ color: #666;
79
+ margin-left: 15px;
80
+ white-space: pre-wrap;
81
+ background-color:#f9f9f9;
82
+ padding: 6px 8px;
83
+ border-radius:4px;
84
+ margin-top: 3px;
85
+ border: 1px solid #eee;
86
+ }
87
+ .account-info .card-details-integrated p {
88
+ margin: 8px 0;
89
+ font-size: 14px;
90
+ }
91
+ .account-info .card-details-integrated p strong {
92
+ min-width: 160px;
93
+ }
94
+
95
+
96
+ #loading-indicator {
97
+ text-align: center;
98
+ padding: 40px;
99
+ font-size: 16px;
100
+ color: #555;
101
+ display: none;
102
+ width: 100%;
103
+ }
104
+ #loading-indicator::before {
105
+ content: '';
106
+ display: inline-block;
107
+ width: 24px;
108
+ height: 24px;
109
+ border: 3px solid rgba(0,0,0, 0.1);
110
+ border-radius: 50%;
111
+ border-top-color: #333;
112
+ animation: spin 1s linear infinite;
113
+ margin-right: 12px;
114
+ position: relative;
115
+ top: 4px;
116
+ }
117
+ @keyframes spin { to { transform: rotate(360deg); } }
118
+
119
+ #last-updated { text-align: right; font-size: 0.85em; color: #777; margin-bottom: 20px; }
120
+ </style>
121
+ </head>
122
+ <body>
123
+ <div class="container">
124
+ <header>
125
+ <h1>账户仪表盘</h1>
126
+ <div class="actions">
127
+ <button id="refresh-btn">刷新数据</button>
128
+ <button id="logout-btn">登出</button>
129
+ </div>
130
+ </header>
131
+
132
+ <div id="last-updated">最后更新时间: N/A</div>
133
+ <div id="loading-indicator">正在加载数据...</div>
134
+
135
+ <div id="account-cards-container">
136
+ </div>
137
+ </div>
138
+
139
+ <script>
140
+ document.addEventListener('DOMContentLoaded', function() {
141
+ const accountCardsContainer = document.getElementById('account-cards-container');
142
+ const loadingIndicator = document.getElementById('loading-indicator');
143
+ const refreshButton = document.getElementById('refresh-btn');
144
+ const logoutButton = document.getElementById('logout-btn');
145
+ const lastUpdatedElem = document.getElementById('last-updated');
146
+
147
+ let autoRefreshInterval;
148
+
149
+ function formatDateTime(isoString) {
150
+ if (!isoString) return 'N/A';
151
+ try {
152
+ return new Date(isoString).toLocaleString('zh-CN', { hour12: false });
153
+ } catch (e) {
154
+ return 'Invalid Date';
155
+ }
156
+ }
157
+
158
+ function displayData(data) {
159
+ accountCardsContainer.innerHTML = '';
160
+ loadingIndicator.style.display = 'none';
161
+
162
+ if (Object.keys(data).length === 0) {
163
+ accountCardsContainer.innerHTML = '<p style="text-align:center; color: #888; grid-column: 1 / -1;">没有可显示的账户数据。</p>';
164
+ return;
165
+ }
166
+
167
+ for (const email in data) {
168
+ const account = data[email];
169
+
170
+ const accountCard = document.createElement('div');
171
+ accountCard.classList.add('account-card');
172
+
173
+ let contentHTML = `<div class="account-info"><h3>${email}</h3>`;
174
+
175
+ contentHTML += `<p><strong>Token 状态:</strong> ${account.token_present ? '<span class="status-ok">存在</span>' : '<span class="status-error">不存在</span>'}</p>`;
176
+
177
+ contentHTML += `<p><strong>最后登录:</strong> ${formatDateTime(account.last_login_attempt)} - ${account.last_login_success === true ? '<span class="status-ok">成功</span>' : (account.last_login_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
178
+ if (account.login_error) {
179
+ contentHTML += `<p class="error-details">登录错误: ${account.login_error}</p>`;
180
+ }
181
+
182
+ contentHTML += `<p><strong>最后 Profile 获取:</strong> ${formatDateTime(account.last_profile_attempt)} - ${account.last_profile_success === true ? '<span class="status-ok">成功</span>' : (account.last_profile_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
183
+ if (account.profile_error) {
184
+ contentHTML += `<p class="error-details">Profile 错误: ${account.profile_error}</p>`;
185
+ }
186
+
187
+ if (account.profile) {
188
+ contentHTML += `<p><strong>UID:</strong> ${account.profile.uid || 'N/A'}</p>`;
189
+ contentHTML += `<p><strong>可用余额:</strong> $${account.profile.available_balance || '0.00'}</p>`;
190
+ contentHTML += `<p><strong>每日消耗:</strong> $${account.profile.daily_consumption || '0.00'}</p>`;
191
+ contentHTML += `<p><strong>邀请码:</strong> ${account.profile.invitation_code || 'N/A'}</p>`;
192
+ contentHTML += `<p><strong>总收益:</strong> $${account.profile.total_earn_balance || '0.00'}</p>`;
193
+ contentHTML += `<p><strong>账户状态:</strong> ${account.profile.status || 'N/A'}</p>`;
194
+ } else {
195
+ contentHTML += `<p>Profile 数据不可用。</p>`;
196
+ }
197
+
198
+ contentHTML += `<p><strong>卡片信息获取:</strong> ${formatDateTime(account.last_card_info_attempt)} - ${account.last_card_info_success === true ? '<span class="status-ok">成功</span>' : (account.last_card_info_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
199
+ if (account.card_info_error) {
200
+ contentHTML += `<p class="error-details">卡片错误: ${account.card_info_error}</p>`;
201
+ }
202
+
203
+ if (account.cards_info) {
204
+ const card = account.cards_info;
205
+ let cardDisplayName = card.name && card.name.toLowerCase() !== 'n/a' ? card.name : '未命名卡片';
206
+
207
+ let cardNumberDisplay = '-';
208
+ if (card.provider_bin && card.card_last_four_digits) {
209
+ cardNumberDisplay = `${card.provider_bin}xxxxxx${card.card_last_four_digits}`;
210
+ } else if (card.provider_bin) {
211
+ cardNumberDisplay = `${card.provider_bin}xxxxxx`;
212
+ } else if (card.card_last_four_digits) {
213
+ cardNumberDisplay = `xxxxxx${card.card_last_four_digits}`;
214
+ }
215
+
216
+ let dailyLimitDisplay = '-';
217
+ if (card.consumption_limit !== null && card.consumption_limit !== undefined) {
218
+ if (String(card.consumption_limit) === '-1') {
219
+ dailyLimitDisplay = '无限制';
220
+ } else {
221
+ dailyLimitDisplay = `$${card.consumption_limit}`;
222
+ }
223
+ }
224
+ contentHTML += `<div class="card-details-integrated">`;
225
+ contentHTML += `<p><strong>卡号:</strong> ${cardNumberDisplay}</p>`;
226
+ contentHTML += `<p><strong>卡日限额:</strong> ${dailyLimitDisplay}</p>`;
227
+ contentHTML += `</div>`;
228
+ } else if (account.last_card_info_success === true) {
229
+ contentHTML += `<p><strong>卡信息:</strong> 无可用卡片。</p>`;
230
+ }
231
+
232
+ contentHTML += `</div>`;
233
+ accountCard.innerHTML = contentHTML;
234
+ accountCardsContainer.appendChild(accountCard);
235
+ }
236
+ lastUpdatedElem.textContent = `最后更新时间: ${new Date().toLocaleString('zh-CN', { hour12: false })}`;
237
+ }
238
+
239
+
240
+ async function fetchData() {
241
+ loadingIndicator.style.display = 'block';
242
+ try {
243
+ const response = await fetch('/api/data');
244
+ if (response.status === 401) {
245
+ window.location.href = '/';
246
+ return;
247
+ }
248
+ if (!response.ok) {
249
+ throw new Error(`HTTP error! status: ${response.status}`);
250
+ }
251
+ const data = await response.json();
252
+ if (data.error) {
253
+ console.error("Error fetching data:", data.error);
254
+ tabsContainer.innerHTML = `<p>获取数据时出错: ${data.error}</p>`;
255
+ loadingIndicator.style.display = 'none';
256
+ } else {
257
+ displayData(data);
258
+ }
259
+ } catch (error) {
260
+ console.error('Error fetching data:', error);
261
+ tabsContainer.innerHTML = `<p>获取数据时发生网络错误或服务器错误。</p>`;
262
+ loadingIndicator.style.display = 'none';
263
+ }
264
+ }
265
+
266
+ refreshButton.addEventListener('click', async () => {
267
+ const originalButtonText = refreshButton.textContent;
268
+ refreshButton.textContent = '正在刷新...';
269
+ refreshButton.disabled = true;
270
+ loadingIndicator.textContent = '手动刷新中...';
271
+ loadingIndicator.style.display = 'block';
272
+
273
+ try {
274
+ const response = await fetch('/api/refresh', { method: 'POST' });
275
+ if (response.status === 401) {
276
+ window.location.href = '/';
277
+ return;
278
+ }
279
+
280
+ setTimeout(async () => {
281
+ await fetchData();
282
+ refreshButton.textContent = originalButtonText;
283
+ refreshButton.disabled = false;
284
+ }, 3000);
285
+
286
+ } catch (error) {
287
+ console.error('Error triggering refresh:', error);
288
+ lastUpdatedElem.textContent = `手动刷新失败: ${new Date().toLocaleString('zh-CN', { hour12: false })}`;
289
+ refreshButton.textContent = originalButtonText;
290
+ refreshButton.disabled = false;
291
+ loadingIndicator.style.display = 'none';
292
+ }
293
+ });
294
+
295
+ logoutButton.addEventListener('click', () => {
296
+ window.location.href = '/logout';
297
+ });
298
+
299
+ fetchData();
300
+
301
+ if (autoRefreshInterval) clearInterval(autoRefreshInterval);
302
+ autoRefreshInterval = setInterval(fetchData, 60000);
303
+ });
304
+ </script>
305
+ </body>
306
+ </html>