Update app.py
Browse files
app.py
CHANGED
@@ -2,73 +2,79 @@
|
|
2 |
# -*- coding: utf-8 -*-
|
3 |
|
4 |
import os
|
5 |
-
import
|
6 |
import hmac
|
7 |
import hashlib
|
|
|
8 |
from urllib.parse import unquote, parse_qs, quote
|
9 |
import time
|
10 |
from datetime import datetime
|
11 |
import logging
|
12 |
-
import threading
|
13 |
-
from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for, send_file
|
14 |
from huggingface_hub import HfApi, hf_hub_download
|
15 |
-
from huggingface_hub.utils import RepositoryNotFoundError
|
16 |
|
17 |
-
#
|
18 |
-
BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Use
|
19 |
HOST = '0.0.0.0'
|
20 |
PORT = 7860
|
21 |
-
DATA_FILE = 'data.json'
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
app = Flask(__name__)
|
28 |
|
29 |
-
#
|
30 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
31 |
|
32 |
-
# --- Hugging Face
|
33 |
|
34 |
-
def
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
if not isinstance(data, dict):
|
39 |
-
logging.warning(f"{DATA_FILE} does not contain a valid dictionary. Resetting.")
|
40 |
-
return {}
|
41 |
-
logging.info(f"Successfully loaded user data from local {DATA_FILE}")
|
42 |
-
return data
|
43 |
-
except FileNotFoundError:
|
44 |
-
logging.info(f"{DATA_FILE} not found locally. Initializing empty data.")
|
45 |
-
return {}
|
46 |
-
except json.JSONDecodeError:
|
47 |
-
logging.error(f"Error decoding JSON from {DATA_FILE}. Initializing empty data.")
|
48 |
-
return {}
|
49 |
-
except Exception as e:
|
50 |
-
logging.error(f"Unexpected error loading user data: {e}")
|
51 |
-
return {}
|
52 |
-
|
53 |
-
def save_user_data(data):
|
54 |
try:
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
return True
|
|
|
|
|
|
|
59 |
except Exception as e:
|
60 |
-
|
|
|
|
|
|
|
|
|
61 |
return False
|
62 |
|
63 |
def upload_db_to_hf():
|
64 |
-
if not HF_TOKEN_WRITE:
|
65 |
-
logging.warning("
|
66 |
return False
|
67 |
if not os.path.exists(DATA_FILE):
|
68 |
-
logging.warning(f"
|
69 |
return False
|
70 |
-
|
71 |
try:
|
|
|
72 |
api = HfApi()
|
73 |
api.upload_file(
|
74 |
path_or_fileobj=DATA_FILE,
|
@@ -76,72 +82,63 @@ def upload_db_to_hf():
|
|
76 |
repo_id=REPO_ID,
|
77 |
repo_type="dataset",
|
78 |
token=HF_TOKEN_WRITE,
|
79 |
-
commit_message=f"
|
80 |
)
|
81 |
-
logging.info(f"
|
82 |
return True
|
83 |
-
except HFValidationError:
|
84 |
-
logging.error("Hugging Face validation error. Check repository ID and token permissions.")
|
85 |
-
return False
|
86 |
except Exception as e:
|
87 |
logging.error(f"Error uploading {DATA_FILE} to Hugging Face: {e}")
|
88 |
return False
|
89 |
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
94 |
try:
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
except
|
107 |
-
logging.
|
108 |
-
return
|
109 |
-
except HFValidationError:
|
110 |
-
logging.error("Hugging Face validation error. Check repository ID and token permissions.")
|
111 |
-
return False
|
112 |
except Exception as e:
|
113 |
-
logging.error(f"Error
|
114 |
-
return
|
115 |
|
116 |
-
def
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
logging.info("
|
121 |
-
|
122 |
upload_db_to_hf()
|
|
|
|
|
|
|
|
|
123 |
|
124 |
-
# --- Telegram Data Verification ---
|
125 |
def verify_telegram_data(init_data_str):
|
126 |
try:
|
127 |
parsed_data = parse_qs(init_data_str)
|
128 |
received_hash = parsed_data.pop('hash', [None])[0]
|
129 |
|
130 |
if not received_hash:
|
131 |
-
logging.warning("Verification failed:
|
132 |
return None, False
|
133 |
|
134 |
data_check_list = []
|
135 |
for key, value in sorted(parsed_data.items()):
|
136 |
-
#
|
137 |
-
|
138 |
-
if key == 'user':
|
139 |
-
# It's often already a JSON string, potentially URL-encoded
|
140 |
-
# The spec implies it should be taken as-is from the query string value
|
141 |
-
data_check_list.append(f"{key}={value[0]}")
|
142 |
-
else:
|
143 |
-
data_check_list.append(f"{key}={unquote(value[0])}")
|
144 |
-
|
145 |
data_check_string = "\n".join(data_check_list)
|
146 |
|
147 |
secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
|
@@ -150,24 +147,23 @@ def verify_telegram_data(init_data_str):
|
|
150 |
if calculated_hash == received_hash:
|
151 |
auth_date = int(parsed_data.get('auth_date', [0])[0])
|
152 |
current_time = int(time.time())
|
153 |
-
# Allow slightly older data,
|
154 |
-
if current_time - auth_date >
|
155 |
-
logging.warning(f"Telegram InitData is older than
|
156 |
-
#
|
|
|
157 |
return parsed_data, True
|
158 |
else:
|
159 |
-
logging.warning(f"Data verification failed.
|
160 |
-
logging
|
|
|
161 |
return parsed_data, False
|
162 |
except Exception as e:
|
163 |
-
logging.error(f"Error verifying Telegram data: {e}"
|
164 |
return None, False
|
165 |
|
166 |
-
# --- Load initial data ---
|
167 |
-
download_db_from_hf()
|
168 |
-
user_data_global = load_user_data()
|
169 |
-
|
170 |
# --- Templates ---
|
|
|
171 |
TEMPLATE = """
|
172 |
<!DOCTYPE html>
|
173 |
<html lang="ru">
|
@@ -176,178 +172,174 @@ TEMPLATE = """
|
|
176 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no">
|
177 |
<title>Morshen Group</title>
|
178 |
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
179 |
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
180 |
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
181 |
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
182 |
<style>
|
183 |
:root {
|
184 |
-
--bg-
|
185 |
-
--bg
|
186 |
-
--
|
187 |
-
--
|
188 |
-
--
|
189 |
-
--
|
190 |
-
--
|
191 |
-
--
|
192 |
-
--
|
193 |
-
--
|
194 |
-
--
|
195 |
-
--
|
196 |
-
--
|
197 |
-
--
|
198 |
-
--border-radius-lg: 16px;
|
199 |
-
--padding-sm: 8px;
|
200 |
-
--padding-md: 16px;
|
201 |
-
--padding-lg: 24px;
|
202 |
-
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
203 |
-
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
|
204 |
-
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
205 |
-
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
|
206 |
}
|
207 |
* { box-sizing: border-box; margin: 0; padding: 0; }
|
208 |
-
html { background:
|
209 |
body {
|
210 |
font-family: var(--font-family);
|
211 |
-
background: linear-gradient(180deg,
|
212 |
-
color: var(--text-
|
213 |
-
padding: var(--padding-
|
214 |
-
padding-bottom:
|
215 |
overscroll-behavior-y: none;
|
216 |
-webkit-font-smoothing: antialiased;
|
217 |
-moz-osx-font-smoothing: grayscale;
|
218 |
-
min-height: 100vh;
|
219 |
visibility: hidden; /* Hide until ready */
|
220 |
}
|
221 |
-
.container { max-width:
|
222 |
-
|
223 |
-
.
|
224 |
-
.logo
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
|
|
|
|
229 |
}
|
230 |
-
.logo
|
231 |
-
|
232 |
.btn {
|
233 |
display: inline-flex; align-items: center; justify-content: center;
|
234 |
-
padding:
|
235 |
-
background: var(--accent-gradient); color:
|
236 |
-
text-decoration: none; font-weight:
|
237 |
-
transition:
|
238 |
-
box-shadow: var(--shadow-sm);
|
239 |
}
|
240 |
-
.btn:hover { opacity: 0.9;
|
241 |
-
.btn-secondary { background: var(--card-bg); color: var(--
|
242 |
-
.btn-secondary:hover { background: rgba(
|
243 |
-
|
244 |
.tag {
|
245 |
-
display: inline-block; background: var(--tag-bg); color: var(--
|
246 |
-
padding:
|
247 |
-
margin: 4px
|
248 |
}
|
249 |
-
.tag i { margin-right:
|
250 |
-
|
251 |
.section-card {
|
252 |
-
background-color: var(--card-bg); border-radius: var(--border-radius-
|
253 |
-
padding: var(--padding-
|
254 |
-
border: 1px solid var(--card-border);
|
255 |
-
box-shadow: var(--shadow-lg);
|
256 |
-
backdrop-filter: blur(10px);
|
257 |
-
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
258 |
}
|
259 |
-
.section-
|
260 |
-
|
261 |
-
|
262 |
-
}
|
263 |
-
|
264 |
-
.
|
265 |
-
.
|
266 |
-
.
|
267 |
-
|
268 |
-
.
|
269 |
-
.
|
270 |
-
.stat-value { font-size: 1.8em; font-weight: 700; display: block; color: var(--text-accent); }
|
271 |
-
.stat-value i { font-size: 0.8em; margin-right: 5px; vertical-align: middle; opacity: 0.8;}
|
272 |
-
.stat-label { font-size: 0.9em; color: var(--text-secondary); display: block; margin-top: 4px;}
|
273 |
-
|
274 |
-
.list-item { background-color: var(--card-bg); padding: var(--padding-md); border-radius: var(--border-radius-md); margin-bottom: var(--padding-sm); display: flex; align-items: center; gap: var(--padding-md); font-size: 1.1em; font-weight: 500; border: 1px solid var(--card-border); transition: background-color 0.2s ease; }
|
275 |
-
.list-item:hover { background-color: rgba(74, 85, 104, 0.7); }
|
276 |
-
.list-item i { font-size: 1.3em; color: var(--accent-gradient-start, #34c759); opacity: 0.9; width: 25px; text-align: center; }
|
277 |
-
|
278 |
-
.footer-greeting { text-align: center; color: var(--text-secondary); font-size: 0.95em; margin-top: var(--padding-lg); padding-bottom: 20px; }
|
279 |
-
|
280 |
.save-card-button {
|
281 |
position: fixed;
|
282 |
-
bottom:
|
283 |
left: 50%;
|
284 |
transform: translateX(-50%);
|
285 |
-
padding:
|
286 |
-
border-radius:
|
287 |
background: var(--accent-gradient-green);
|
288 |
-
color:
|
289 |
text-decoration: none;
|
290 |
font-weight: 600;
|
291 |
border: none;
|
292 |
cursor: pointer;
|
293 |
-
transition:
|
294 |
z-index: 1000;
|
295 |
-
box-shadow: 0
|
296 |
-
font-size:
|
297 |
display: flex;
|
298 |
align-items: center;
|
299 |
-
gap:
|
300 |
}
|
301 |
-
.save-card-button:hover { opacity: 0.9; transform: translateX(-50%) scale(1.
|
302 |
|
303 |
.modal {
|
304 |
-
display: none;
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
|
|
|
|
|
|
|
|
|
|
309 |
}
|
310 |
.modal-content {
|
311 |
-
background-color: var(--card-bg
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
border
|
316 |
-
|
317 |
-
|
318 |
-
|
|
|
|
|
|
|
319 |
}
|
320 |
-
@keyframes fadeInScale { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } }
|
321 |
.modal-close {
|
322 |
-
color: var(--text-secondary);
|
323 |
-
|
324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
}
|
326 |
-
.modal-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
.icon-save::before { content: '💾'; margin-right:
|
333 |
-
.icon-web::before { content: '🌐'; margin-right:
|
334 |
-
.icon-mobile::before { content: '📱'; margin-right:
|
335 |
-
.icon-code::before { content: '💻'; margin-right:
|
336 |
-
.icon-ai::before { content: '🧠'; margin-right:
|
337 |
-
.icon-quantum::before { content: '⚛️'; margin-right:
|
338 |
-
.icon-business::before { content: '💼'; margin-right:
|
339 |
-
.icon-speed::before { content: '⚡️'; margin-right:
|
340 |
-
.icon-complexity::before { content: '🧩'; margin-right:
|
341 |
-
.icon-experience::before { content: '⏳'; margin-right:
|
342 |
-
.icon-clients::before { content: '👥'; margin-right:
|
343 |
-
.icon-market::before { content: '📈'; margin-right:
|
344 |
-
.icon-location::before { content: '📍'; margin-right:
|
345 |
-
.icon-global::before { content: '🌍'; margin-right:
|
346 |
-
.icon-innovation::before { content: '💡'; margin-right:
|
347 |
-
.icon-contact::before { content: '💬'; margin-right:
|
348 |
-
.icon-link::before { content: '🔗'; margin-right:
|
349 |
-
.icon-leader::before { content: '🏆'; margin-right:
|
350 |
-
.icon-company::before { content: '🏢'; margin-right:
|
351 |
</style>
|
352 |
</head>
|
353 |
<body>
|
@@ -363,54 +355,53 @@ TEMPLATE = """
|
|
363 |
</div>
|
364 |
<div>
|
365 |
<span class="tag"><i class="icon-leader"></i>Лидер инноваций 2025</span>
|
366 |
-
<span class="tag"><i class="icon-global"></i>Международный Холдинг</span>
|
367 |
</div>
|
368 |
-
<h1 class="section-title"
|
369 |
<p class="description">
|
370 |
-
|
371 |
-
|
372 |
</p>
|
373 |
-
<a href="#" class="btn contact-link" style="background: var(--accent-gradient-green); width: 100%; margin-top: var(--padding-
|
374 |
-
<i class="icon-contact"></i
|
375 |
</a>
|
376 |
</section>
|
377 |
|
378 |
<section class="ecosystem-header">
|
379 |
-
<span class="tag"><i class="icon-company"></i
|
380 |
-
<h2 class="section-title">Экосистема
|
381 |
<p class="description">
|
382 |
-
|
383 |
-
|
384 |
</p>
|
385 |
</section>
|
386 |
|
387 |
<section class="section-card">
|
388 |
<div class="logo">
|
389 |
-
<img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo"
|
390 |
-
<span style="font-size: 1.
|
391 |
</div>
|
392 |
-
<div style="margin: var(--padding-
|
393 |
-
<span class="tag"><i class="icon-ai"></i
|
394 |
-
<span class="tag"><i class="icon-quantum"></i
|
395 |
-
<span class="tag"><i class="icon-business"></i
|
396 |
-
<span class="tag"><i class="icon-innovation"></i>R&D Hub</span>
|
397 |
</div>
|
398 |
-
<p class="description"
|
399 |
-
Флагманская
|
400 |
-
|
|
|
401 |
</p>
|
402 |
<div class="stats-grid">
|
403 |
<div class="stat-item">
|
404 |
-
<span class="stat-value"><i class="icon-global"></i> 3
|
405 |
<span class="stat-label">Страны присутствия</span>
|
406 |
</div>
|
407 |
<div class="stat-item">
|
408 |
-
<span class="stat-value"><i class="icon-clients"></i>
|
409 |
-
<span class="stat-label"
|
410 |
</div>
|
411 |
<div class="stat-item">
|
412 |
-
<span class="stat-value"><i class="icon-market"></i> 5
|
413 |
-
<span class="stat-label">Лет
|
414 |
</div>
|
415 |
</div>
|
416 |
</section>
|
@@ -418,156 +409,133 @@ TEMPLATE = """
|
|
418 |
<section class="section-card">
|
419 |
<div class="logo">
|
420 |
<img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 50px; height: 50px;">
|
421 |
-
<span style="font-size: 1.
|
422 |
</div>
|
423 |
-
<div style="margin: var(--padding-
|
424 |
-
<span class="tag"><i class="icon-web"></i
|
425 |
-
<span class="tag"><i class="icon-mobile"></i
|
426 |
-
<span class="tag"><i class="icon-code"></i
|
427 |
</div>
|
428 |
-
<p class="description"
|
429 |
-
|
430 |
-
|
|
|
|
|
431 |
</p>
|
432 |
<div class="stats-grid">
|
433 |
<div class="stat-item">
|
434 |
<span class="stat-value"><i class="icon-experience"></i> 10+</span>
|
435 |
-
<span class="stat-label">Лет
|
436 |
</div>
|
437 |
<div class="stat-item">
|
438 |
-
<span class="stat-value"><i class="icon-complexity"></i>
|
439 |
-
<span class="stat-label"
|
440 |
</div>
|
441 |
<div class="stat-item">
|
442 |
-
<span class="stat-value"><i class="icon-speed"></i
|
443 |
-
<span class="stat-label"
|
444 |
</div>
|
445 |
</div>
|
446 |
-
<div style="display: flex; gap: var(--padding-
|
447 |
-
<a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon-link"></i
|
448 |
-
<a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon-contact"></i
|
449 |
</div>
|
450 |
</section>
|
451 |
|
452 |
<section>
|
453 |
-
<span class="tag"><i class="icon-global"></i
|
454 |
-
<h2 class="section-title"
|
455 |
-
<p class="description">Наши решения
|
456 |
<div>
|
457 |
-
<div class="list-item"><i class="icon-location"></i
|
458 |
<div class="list-item"><i class="icon-location"></i>Казахстан</div>
|
459 |
<div class="list-item"><i class="icon-location"></i>Кыргызстан</div>
|
460 |
-
<div class="list-item"><i class="icon-global"></i>...и расширяемся дальше!</div>
|
461 |
</div>
|
462 |
</section>
|
463 |
|
464 |
<footer class="footer-greeting">
|
465 |
-
<p id="greeting"
|
466 |
</footer>
|
467 |
|
468 |
</div>
|
469 |
|
470 |
<button class="save-card-button" id="save-card-btn">
|
471 |
-
<i class="icon-save"></i>Сохранить
|
472 |
</button>
|
473 |
|
474 |
-
<!-- The Modal -->
|
475 |
<div id="saveModal" class="modal">
|
476 |
<div class="modal-content">
|
477 |
<span class="modal-close" id="modal-close-btn">×</span>
|
478 |
-
<p class="modal-text"><b>+
|
479 |
-
<p class="modal-text"
|
480 |
<p class="modal-instruction">Сделайте скриншот экрана, чтобы сохранить контакт.</p>
|
481 |
</div>
|
482 |
</div>
|
483 |
|
484 |
-
|
485 |
<script>
|
486 |
const tg = window.Telegram.WebApp;
|
487 |
|
488 |
-
function applyTheme(themeParams) {
|
489 |
-
document.documentElement.style.setProperty('--bg-gradient-start', themeParams.bg_color || '#10141F');
|
490 |
-
// Use secondary_bg_color for the end gradient if available, otherwise fallback
|
491 |
-
let bgEnd = themeParams.secondary_bg_color ? themeParams.secondary_bg_color : '#1A202C';
|
492 |
-
// Adjust if secondary is too light/same as primary
|
493 |
-
if (bgEnd === themeParams.bg_color) bgEnd = '#1A202C';
|
494 |
-
document.documentElement.style.setProperty('--bg-gradient-end', bgEnd);
|
495 |
-
|
496 |
-
document.documentElement.style.setProperty('--text-primary', themeParams.text_color || '#E2E8F0');
|
497 |
-
document.documentElement.style.setProperty('--text-secondary', themeParams.hint_color || '#A0AEC0');
|
498 |
-
document.documentElement.style.setProperty('--text-accent', themeParams.link_color || '#63B3ED');
|
499 |
-
document.documentElement.style.setProperty('--card-bg', themeParams.secondary_bg_color ? themeParams.secondary_bg_color + 'B3' : 'rgba(45, 55, 72, 0.7)'); // Add transparency
|
500 |
-
document.documentElement.style.setProperty('--card-border', themeParams.hint_color ? themeParams.hint_color + '80': 'rgba(74, 85, 104, 0.5)');
|
501 |
-
|
502 |
-
// Button gradient from button_color if available
|
503 |
-
if (themeParams.button_color) {
|
504 |
-
// Attempt to create a slightly darker shade for the gradient end
|
505 |
-
try {
|
506 |
-
let colorStart = themeParams.button_color;
|
507 |
-
// Simple darken logic (may not be perfect for all colors)
|
508 |
-
let r = parseInt(colorStart.slice(1, 3), 16);
|
509 |
-
let g = parseInt(colorStart.slice(3, 5), 16);
|
510 |
-
let b = parseInt(colorStart.slice(5, 7), 16);
|
511 |
-
r = Math.max(0, r - 30);
|
512 |
-
g = Math.max(0, g - 30);
|
513 |
-
b = Math.max(0, b - 30);
|
514 |
-
let colorEnd = `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
|
515 |
-
document.documentElement.style.setProperty('--accent-gradient', `linear-gradient(90deg, ${colorStart}, ${colorEnd})`);
|
516 |
-
} catch (e) {
|
517 |
-
// Fallback if color parsing fails
|
518 |
-
document.documentElement.style.setProperty('--accent-gradient', `linear-gradient(90deg, ${themeParams.button_color}, ${themeParams.button_color})`);
|
519 |
-
}
|
520 |
-
}
|
521 |
-
if (themeParams.button_text_color) {
|
522 |
-
// Adjust button text color if needed, though white usually works
|
523 |
-
// document.querySelector('.btn').style.color = themeParams.button_text_color;
|
524 |
-
}
|
525 |
-
// Apply to Green button too? Maybe keep it distinct.
|
526 |
-
}
|
527 |
-
|
528 |
-
|
529 |
function setupTelegram() {
|
530 |
if (!tg || !tg.initData) {
|
531 |
console.error("Telegram WebApp script not loaded or initData is missing.");
|
532 |
const greetingElement = document.getElementById('greeting');
|
533 |
-
if(greetingElement) greetingElement.textContent = '
|
534 |
document.body.style.visibility = 'visible';
|
535 |
return;
|
536 |
}
|
537 |
|
538 |
tg.ready();
|
539 |
tg.expand();
|
540 |
-
tg.setHeaderColor(document.documentElement.style.getPropertyValue('--bg-gradient-start').trim() || '#10141F');
|
541 |
-
tg.setBackgroundColor(document.documentElement.style.getPropertyValue('--bg-gradient-end').trim() || '#1A202C');
|
542 |
|
543 |
-
|
544 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
545 |
|
546 |
fetch('/verify', {
|
547 |
method: 'POST',
|
548 |
-
headers: {
|
|
|
|
|
549 |
body: JSON.stringify({ initData: tg.initData }),
|
550 |
})
|
551 |
.then(response => response.json())
|
552 |
.then(data => {
|
553 |
if (data.status === 'ok' && data.verified) {
|
554 |
-
console.log('Backend verification successful
|
555 |
} else {
|
556 |
console.warn('Backend verification failed:', data.message);
|
557 |
-
//
|
558 |
-
// tg.showAlert('Не удалось проверить
|
559 |
}
|
560 |
})
|
561 |
.catch(error => {
|
562 |
console.error('Error sending initData for verification:', error);
|
563 |
-
|
564 |
});
|
565 |
|
566 |
const user = tg.initDataUnsafe?.user;
|
567 |
const greetingElement = document.getElementById('greeting');
|
568 |
if (user) {
|
569 |
-
const name = user.first_name || user.username || '
|
570 |
-
greetingElement.textContent =
|
571 |
} else {
|
572 |
greetingElement.textContent = 'Добро пожаловать!';
|
573 |
console.warn('Telegram User data not available (initDataUnsafe.user is empty).');
|
@@ -577,7 +545,6 @@ TEMPLATE = """
|
|
577 |
contactButtons.forEach(button => {
|
578 |
button.addEventListener('click', (e) => {
|
579 |
e.preventDefault();
|
580 |
-
if (tg.HapticFeedback) tg.HapticFeedback.impactOccurred('light');
|
581 |
tg.openTelegramLink('https://t.me/morshenkhan');
|
582 |
});
|
583 |
});
|
@@ -589,8 +556,10 @@ TEMPLATE = """
|
|
589 |
if (saveCardBtn && modal && closeBtn) {
|
590 |
saveCardBtn.addEventListener('click', (e) => {
|
591 |
e.preventDefault();
|
592 |
-
if (tg.HapticFeedback) tg.HapticFeedback.impactOccurred('medium');
|
593 |
modal.style.display = "block";
|
|
|
|
|
|
|
594 |
});
|
595 |
|
596 |
closeBtn.addEventListener('click', () => {
|
@@ -617,10 +586,10 @@ TEMPLATE = """
|
|
617 |
if (document.body.style.visibility !== 'visible') {
|
618 |
console.error("Telegram WebApp script fallback timeout triggered.");
|
619 |
const greetingElement = document.getElementById('greeting');
|
620 |
-
if(greetingElement) greetingElement.textContent = 'Ошибка загрузки
|
621 |
document.body.style.visibility = 'visible';
|
622 |
}
|
623 |
-
},
|
624 |
}
|
625 |
|
626 |
</script>
|
@@ -634,156 +603,126 @@ ADMIN_TEMPLATE = """
|
|
634 |
<head>
|
635 |
<meta charset="UTF-8">
|
636 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
637 |
-
<title>Admin -
|
638 |
-
<link rel="preconnect" href="https://fonts.googleapis.com">
|
639 |
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
640 |
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
641 |
<style>
|
642 |
-
:
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
}
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
}
|
675 |
-
.btn {
|
676 |
-
padding: 10px 20px;
|
677 |
-
border: none;
|
678 |
-
border-radius: var(--border-radius);
|
679 |
-
font-weight: 500;
|
680 |
-
cursor: pointer;
|
681 |
-
transition: all 0.2s ease;
|
682 |
-
font-size: 0.95em;
|
683 |
-
}
|
684 |
-
.btn-primary { background-color: var(--admin-accent); color: var(--admin-bg); }
|
685 |
-
.btn-primary:hover { background-color: #4299E1; }
|
686 |
-
.btn-success { background-color: var(--admin-success); color: var(--admin-bg); }
|
687 |
-
.btn-success:hover { background-color: #48BB78; }
|
688 |
-
.user-grid {
|
689 |
-
display: grid;
|
690 |
-
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
691 |
-
gap: var(--padding);
|
692 |
-
}
|
693 |
-
.user-card {
|
694 |
-
background-color: var(--admin-card-bg);
|
695 |
-
border-radius: var(--border-radius);
|
696 |
-
padding: var(--padding);
|
697 |
-
box-shadow: var(--shadow);
|
698 |
-
display: flex;
|
699 |
-
flex-direction: column;
|
700 |
-
align-items: center;
|
701 |
-
text-align: center;
|
702 |
-
border: 1px solid var(--admin-border);
|
703 |
-
}
|
704 |
-
.user-card img {
|
705 |
-
width: 80px; height: 80px;
|
706 |
-
border-radius: 50%;
|
707 |
-
margin-bottom: 12px;
|
708 |
-
object-fit: cover;
|
709 |
-
border: 2px solid var(--admin-border);
|
710 |
-
background-color: var(--admin-bg); /* Placeholder bg */
|
711 |
-
}
|
712 |
-
.user-card .name { font-weight: 600; font-size: 1.1em; margin-bottom: 4px; }
|
713 |
-
.user-card .username { color: var(--admin-accent); margin-bottom: 8px; font-size: 0.9em; }
|
714 |
-
.user-card .details { font-size: 0.9em; color: var(--admin-text-secondary); word-break: break-all; line-height: 1.5; }
|
715 |
-
.user-card .timestamp { font-size: 0.8em; color: var(--admin-text-secondary); margin-top: 12px; }
|
716 |
-
.no-users, .message {
|
717 |
-
text-align: center; color: var(--admin-text-secondary);
|
718 |
-
margin-top: 30px; font-size: 1.1em;
|
719 |
-
padding: var(--padding); background-color: var(--admin-card-bg);
|
720 |
-
border-radius: var(--border-radius); border: 1px solid var(--admin-border);
|
721 |
-
}
|
722 |
-
.message.success { color: var(--admin-success); border-left: 5px solid var(--admin-success); }
|
723 |
-
.message.error { color: var(--admin-danger); border-left: 5px solid var(--admin-danger); }
|
724 |
-
.alert {
|
725 |
-
background-color: rgba(245, 101, 101, 0.2); /* Light Red BG */
|
726 |
-
border-left: 6px solid var(--admin-danger);
|
727 |
-
margin: 20px auto; padding: 12px 18px;
|
728 |
-
color: #FED7D7; /* Lighter Red Text */
|
729 |
-
border-radius: var(--border-radius);
|
730 |
-
text-align: center; font-weight: 500;
|
731 |
-
max-width: 800px;
|
732 |
}
|
733 |
-
|
734 |
-
|
|
|
735 |
</style>
|
736 |
</head>
|
737 |
<body>
|
738 |
-
<
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
<div class="controls">
|
751 |
-
<form method="POST" action="{{ url_for('backup_users') }}" style="display: inline;">
|
752 |
-
<button type="submit" class="btn btn-primary">Резервное копирование на HF</button>
|
753 |
-
</form>
|
754 |
-
<form method="POST" action="{{ url_for('download_users') }}" style="display: inline;">
|
755 |
-
<button type="submit" class="btn btn-success">Загрузить с HF</button>
|
756 |
-
</form>
|
757 |
-
<form method="GET" action="{{ url_for('download_local_db') }}" style="display: inline;">
|
758 |
-
<button type="submit" class="btn btn-secondary" style="background-color: var(--admin-text-secondary); color: var(--admin-bg);">Скачать локальный JSON</button>
|
759 |
-
</form>
|
760 |
-
</div>
|
761 |
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
<div class="
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
</div>
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
787 |
</body>
|
788 |
</html>
|
789 |
"""
|
@@ -796,141 +735,108 @@ def index():
|
|
796 |
|
797 |
@app.route('/verify', methods=['POST'])
|
798 |
def verify_data():
|
799 |
-
|
800 |
try:
|
801 |
data = request.get_json()
|
802 |
init_data_str = data.get('initData')
|
803 |
if not init_data_str:
|
804 |
-
logging.warning("
|
805 |
return jsonify({"status": "error", "message": "Missing initData"}), 400
|
806 |
|
807 |
-
#
|
808 |
-
user_data_parsed, is_valid = verify_telegram_data(init_data_str)
|
809 |
-
|
810 |
user_info_dict = {}
|
811 |
-
|
|
|
|
|
812 |
try:
|
813 |
-
#
|
814 |
-
user_json_str = unquote(
|
815 |
user_info_dict = json.loads(user_json_str)
|
816 |
except Exception as e:
|
817 |
logging.error(f"Could not parse user JSON from initData: {e}")
|
818 |
-
|
819 |
-
|
|
|
820 |
|
821 |
if is_valid:
|
822 |
-
user_id = user_info_dict.get('id')
|
823 |
if user_id:
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
logging.info(f"New user detected: {user_id_str} ({user_info_dict.get('username', 'N/A')})")
|
831 |
-
user_data_global[user_id_str] = {} # Initialize if new
|
832 |
-
|
833 |
-
# Update user data, preserving existing fields if they are missing in the new data
|
834 |
-
user_data_global[user_id_str].update({
|
835 |
'id': user_id,
|
836 |
-
'first_name': user_info_dict.get('first_name'
|
837 |
-
'last_name': user_info_dict.get('last_name'
|
838 |
-
'username': user_info_dict.get('username'
|
839 |
-
'photo_url': user_info_dict.get('photo_url'
|
840 |
-
'language_code': user_info_dict.get('language_code'
|
841 |
-
'
|
842 |
-
'
|
843 |
-
}
|
844 |
-
#
|
845 |
-
|
846 |
-
save_user_data(user_data_global)
|
847 |
-
|
848 |
else:
|
849 |
-
logging.warning("Verification successful but user ID missing in parsed
|
850 |
-
|
851 |
|
852 |
return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
|
853 |
else:
|
854 |
-
logging.warning(f"Verification failed for
|
855 |
-
return jsonify({"status": "error", "verified": False, "message": "Invalid data
|
856 |
|
857 |
except Exception as e:
|
858 |
-
logging.error(f"
|
859 |
return jsonify({"status": "error", "message": "Internal server error"}), 500
|
860 |
|
861 |
-
|
862 |
@app.route('/admin')
|
863 |
def admin_panel():
|
864 |
-
# WARNING:
|
865 |
-
|
866 |
-
|
867 |
-
|
868 |
-
|
869 |
-
|
870 |
-
|
871 |
-
|
872 |
-
|
873 |
-
if
|
874 |
-
|
875 |
-
flash("Резервное копирование на Hugging Face успешно завершено.", "success")
|
876 |
-
else:
|
877 |
-
flash("Ошибка при резервном копировании на Hugging Face.", "error")
|
878 |
else:
|
879 |
-
|
880 |
-
|
881 |
-
|
882 |
-
|
883 |
-
|
884 |
-
|
885 |
-
|
886 |
-
|
887 |
-
from flask import flash
|
888 |
-
if download_db_from_hf():
|
889 |
-
user_data_global = load_user_data() # Reload global data after download
|
890 |
-
flash(f"Данные успешно загружены с Hugging Face и {DATA_FILE} обновлен.", "success")
|
891 |
else:
|
892 |
-
|
893 |
-
|
894 |
-
|
895 |
-
@app.route('/admin/download_local_db', methods=['GET'])
|
896 |
-
def download_local_db():
|
897 |
-
# WARNING: Unprotected route!
|
898 |
-
if os.path.exists(DATA_FILE):
|
899 |
-
return send_file(DATA_FILE, as_attachment=True, download_name=DATA_FILE)
|
900 |
-
else:
|
901 |
-
from flask import flash
|
902 |
-
flash(f"Локальный файл {DATA_FILE} не найден.", "error")
|
903 |
-
return redirect(url_for('admin_panel'))
|
904 |
|
905 |
|
906 |
# --- Main Execution ---
|
|
|
907 |
if __name__ == '__main__':
|
908 |
-
|
909 |
-
|
910 |
-
|
911 |
-
|
912 |
-
|
913 |
-
|
914 |
-
|
915 |
-
|
916 |
-
|
917 |
-
|
918 |
-
|
919 |
-
|
920 |
-
|
921 |
-
|
922 |
-
|
923 |
-
|
924 |
-
|
925 |
-
|
926 |
-
|
927 |
-
|
928 |
-
#
|
929 |
-
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
930 |
-
backup_thread.start()
|
931 |
-
|
932 |
-
# Use a production server like Waitress or Gunicorn instead of app.run() for deployment
|
933 |
-
# from waitress import serve
|
934 |
-
# serve(app, host=HOST, port=PORT)
|
935 |
-
app.secret_key = os.urandom(24) # Required for flashing messages
|
936 |
-
app.run(host=HOST, port=PORT, debug=False) # debug=False for production
|
|
|
2 |
# -*- coding: utf-8 -*-
|
3 |
|
4 |
import os
|
5 |
+
from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for
|
6 |
import hmac
|
7 |
import hashlib
|
8 |
+
import json
|
9 |
from urllib.parse import unquote, parse_qs, quote
|
10 |
import time
|
11 |
from datetime import datetime
|
12 |
import logging
|
|
|
|
|
13 |
from huggingface_hub import HfApi, hf_hub_download
|
14 |
+
from huggingface_hub.utils import RepositoryNotFoundError
|
15 |
|
16 |
+
# Configuration
|
17 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Use env var or default
|
18 |
HOST = '0.0.0.0'
|
19 |
PORT = 7860
|
20 |
+
DATA_FILE = 'data.json' # File to store visited user data
|
21 |
+
|
22 |
+
# Hugging Face Settings
|
23 |
+
REPO_ID = os.getenv("HF_REPO_ID", "flpolprojects/teledata") # Your HF repo ID (e.g., YourUsername/YourDatasetName)
|
24 |
+
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") # HF Write Token from env
|
25 |
+
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", HF_TOKEN_WRITE) # HF Read Token from env (can be same as write)
|
26 |
+
|
27 |
+
# Check if essential HF config is present
|
28 |
+
if not HF_TOKEN_WRITE:
|
29 |
+
print("WARNING: HF_TOKEN_WRITE environment variable not set. Hugging Face uploads will fail.")
|
30 |
+
if not REPO_ID:
|
31 |
+
print("WARNING: HF_REPO_ID environment variable not set. Using default 'Morshen/TeleUserData'.")
|
32 |
+
|
33 |
|
34 |
app = Flask(__name__)
|
35 |
|
36 |
+
# Setup logging
|
37 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
38 |
|
39 |
+
# --- Hugging Face Sync Functions ---
|
40 |
|
41 |
+
def download_db_from_hf():
|
42 |
+
if not HF_TOKEN_READ or not REPO_ID:
|
43 |
+
logging.warning("Skipping Hugging Face download: Read token or Repo ID missing.")
|
44 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
try:
|
46 |
+
logging.info(f"Attempting to download {DATA_FILE} from Hugging Face repo {REPO_ID}")
|
47 |
+
hf_hub_download(
|
48 |
+
repo_id=REPO_ID,
|
49 |
+
filename=DATA_FILE,
|
50 |
+
repo_type="dataset",
|
51 |
+
token=HF_TOKEN_READ,
|
52 |
+
local_dir=".",
|
53 |
+
local_dir_use_symlinks=False,
|
54 |
+
force_download=True # Ensure latest version
|
55 |
+
)
|
56 |
+
logging.info(f"{DATA_FILE} successfully downloaded from Hugging Face.")
|
57 |
return True
|
58 |
+
except RepositoryNotFoundError:
|
59 |
+
logging.warning(f"Hugging Face repository {REPO_ID} not found. Will create local {DATA_FILE} if needed.")
|
60 |
+
return False
|
61 |
except Exception as e:
|
62 |
+
# Specifically check for 404 which might mean the *file* doesn't exist yet
|
63 |
+
if "404 Client Error" in str(e):
|
64 |
+
logging.warning(f"{DATA_FILE} not found in Hugging Face repository {REPO_ID}. Will create local file if needed.")
|
65 |
+
else:
|
66 |
+
logging.error(f"Error downloading {DATA_FILE} from Hugging Face: {e}")
|
67 |
return False
|
68 |
|
69 |
def upload_db_to_hf():
|
70 |
+
if not HF_TOKEN_WRITE or not REPO_ID:
|
71 |
+
logging.warning("Skipping Hugging Face upload: Write token or Repo ID missing.")
|
72 |
return False
|
73 |
if not os.path.exists(DATA_FILE):
|
74 |
+
logging.warning(f"Skipping Hugging Face upload: Local file {DATA_FILE} does not exist.")
|
75 |
return False
|
|
|
76 |
try:
|
77 |
+
logging.info(f"Attempting to upload {DATA_FILE} to Hugging Face repo {REPO_ID}")
|
78 |
api = HfApi()
|
79 |
api.upload_file(
|
80 |
path_or_fileobj=DATA_FILE,
|
|
|
82 |
repo_id=REPO_ID,
|
83 |
repo_type="dataset",
|
84 |
token=HF_TOKEN_WRITE,
|
85 |
+
commit_message=f"Update user data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
86 |
)
|
87 |
+
logging.info(f"{DATA_FILE} successfully uploaded to Hugging Face.")
|
88 |
return True
|
|
|
|
|
|
|
89 |
except Exception as e:
|
90 |
logging.error(f"Error uploading {DATA_FILE} to Hugging Face: {e}")
|
91 |
return False
|
92 |
|
93 |
+
# --- Data Handling ---
|
94 |
+
|
95 |
+
def load_data():
|
96 |
+
# Try to download the latest version first
|
97 |
+
download_db_from_hf()
|
98 |
try:
|
99 |
+
if os.path.exists(DATA_FILE):
|
100 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
101 |
+
data = json.load(file)
|
102 |
+
if not isinstance(data, dict): # Ensure it's a dictionary
|
103 |
+
logging.warning(f"{DATA_FILE} does not contain a valid dictionary. Initializing empty data.")
|
104 |
+
return {}
|
105 |
+
logging.info(f"Data successfully loaded from local {DATA_FILE}")
|
106 |
+
return data
|
107 |
+
else:
|
108 |
+
logging.info(f"Local file {DATA_FILE} not found. Initializing empty data.")
|
109 |
+
return {} # Return empty dict if file doesn't exist
|
110 |
+
except json.JSONDecodeError:
|
111 |
+
logging.error(f"Error decoding JSON from {DATA_FILE}. Returning empty data.")
|
112 |
+
return {}
|
|
|
|
|
|
|
113 |
except Exception as e:
|
114 |
+
logging.error(f"Error loading data from {DATA_FILE}: {e}")
|
115 |
+
return {}
|
116 |
|
117 |
+
def save_data(data):
|
118 |
+
try:
|
119 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
120 |
+
json.dump(data, file, ensure_ascii=False, indent=4)
|
121 |
+
logging.info(f"Data successfully saved to local {DATA_FILE}")
|
122 |
+
# Attempt to upload after saving locally
|
123 |
upload_db_to_hf()
|
124 |
+
except Exception as e:
|
125 |
+
logging.error(f"Error saving data to {DATA_FILE}: {e}")
|
126 |
+
|
127 |
+
# --- Telegram Verification ---
|
128 |
|
|
|
129 |
def verify_telegram_data(init_data_str):
|
130 |
try:
|
131 |
parsed_data = parse_qs(init_data_str)
|
132 |
received_hash = parsed_data.pop('hash', [None])[0]
|
133 |
|
134 |
if not received_hash:
|
135 |
+
logging.warning("Verification failed: Hash missing in initData.")
|
136 |
return None, False
|
137 |
|
138 |
data_check_list = []
|
139 |
for key, value in sorted(parsed_data.items()):
|
140 |
+
# Values from parse_qs are lists, take the first element
|
141 |
+
data_check_list.append(f"{key}={value[0]}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
data_check_string = "\n".join(data_check_list)
|
143 |
|
144 |
secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
|
|
|
147 |
if calculated_hash == received_hash:
|
148 |
auth_date = int(parsed_data.get('auth_date', [0])[0])
|
149 |
current_time = int(time.time())
|
150 |
+
# Allow slightly older data, maybe network latency. Adjust 3600 (1 hour) as needed.
|
151 |
+
if current_time - auth_date > 3600:
|
152 |
+
logging.warning(f"Telegram InitData is older than 1 hour (Auth Date: {auth_date}, Current: {current_time}).")
|
153 |
+
# Log successful verification without printing sensitive parts
|
154 |
+
logging.info("Telegram data verified successfully.")
|
155 |
return parsed_data, True
|
156 |
else:
|
157 |
+
logging.warning(f"Data verification failed. Calculated hash mismatch.")
|
158 |
+
# Avoid logging hashes directly in production for security
|
159 |
+
# logging.debug(f"Calculated: {calculated_hash}, Received: {received_hash}")
|
160 |
return parsed_data, False
|
161 |
except Exception as e:
|
162 |
+
logging.error(f"Error verifying Telegram data: {e}")
|
163 |
return None, False
|
164 |
|
|
|
|
|
|
|
|
|
165 |
# --- Templates ---
|
166 |
+
|
167 |
TEMPLATE = """
|
168 |
<!DOCTYPE html>
|
169 |
<html lang="ru">
|
|
|
172 |
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no">
|
173 |
<title>Morshen Group</title>
|
174 |
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
|
|
|
|
|
|
175 |
<style>
|
176 |
:root {
|
177 |
+
--bg-color: #1c1c1e;
|
178 |
+
--card-bg: #2c2c2e;
|
179 |
+
--text-color: #ffffff;
|
180 |
+
--text-secondary-color: #a0a0a5;
|
181 |
+
--accent-gradient: linear-gradient(90deg, #007aff, #5856d6);
|
182 |
+
--accent-gradient-green: linear-gradient(90deg, #34c759, #30d158);
|
183 |
+
--tag-bg: rgba(255, 255, 255, 0.1);
|
184 |
+
--border-radius-s: 8px;
|
185 |
+
--border-radius-m: 12px;
|
186 |
+
--border-radius-l: 16px;
|
187 |
+
--padding-s: 8px;
|
188 |
+
--padding-m: 16px;
|
189 |
+
--padding-l: 24px;
|
190 |
+
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
}
|
192 |
* { box-sizing: border-box; margin: 0; padding: 0; }
|
193 |
+
html { background-color: var(--bg-color); }
|
194 |
body {
|
195 |
font-family: var(--font-family);
|
196 |
+
background: linear-gradient(180deg, #1a2a3a 0%, #101820 100%);
|
197 |
+
color: var(--text-color);
|
198 |
+
padding: var(--padding-m);
|
199 |
+
padding-bottom: 100px;
|
200 |
overscroll-behavior-y: none;
|
201 |
-webkit-font-smoothing: antialiased;
|
202 |
-moz-osx-font-smoothing: grayscale;
|
|
|
203 |
visibility: hidden; /* Hide until ready */
|
204 |
}
|
205 |
+
.container { max-width: 600px; margin: 0 auto; display: flex; flex-direction: column; gap: var(--padding-l); }
|
206 |
+
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--padding-m); }
|
207 |
+
.logo { display: flex; align-items: center; gap: var(--padding-s); }
|
208 |
+
.logo img, .logo-icon {
|
209 |
+
width: 40px;
|
210 |
+
height: 40px;
|
211 |
+
border-radius: 50%;
|
212 |
+
background-color: var(--card-bg);
|
213 |
+
object-fit: cover;
|
214 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
215 |
}
|
216 |
+
.logo-icon { display: inline-flex; align-items: center; justify-content: center; font-weight: bold; color: var(--text-secondary-color); }
|
217 |
+
.logo span { font-size: 1.4em; font-weight: 600; }
|
218 |
.btn {
|
219 |
display: inline-flex; align-items: center; justify-content: center;
|
220 |
+
padding: 10px var(--padding-m); border-radius: var(--border-radius-m);
|
221 |
+
background: var(--accent-gradient); color: var(--text-color);
|
222 |
+
text-decoration: none; font-weight: 500; border: none; cursor: pointer;
|
223 |
+
transition: opacity 0.2s ease; gap: 6px; font-size: 0.95em;
|
|
|
224 |
}
|
225 |
+
.btn:hover { opacity: 0.9; }
|
226 |
+
.btn-secondary { background: var(--card-bg); color: var(--accent-gradient-start, #007aff); }
|
227 |
+
.btn-secondary:hover { background: rgba(44, 44, 46, 0.8); }
|
|
|
228 |
.tag {
|
229 |
+
display: inline-block; background: var(--tag-bg); color: var(--text-secondary-color);
|
230 |
+
padding: 4px 10px; border-radius: var(--border-radius-s); font-size: 0.8em;
|
231 |
+
margin: 4px 4px 4px 0; white-space: nowrap;
|
232 |
}
|
233 |
+
.tag i { margin-right: 4px; opacity: 0.7; }
|
|
|
234 |
.section-card {
|
235 |
+
background-color: var(--card-bg); border-radius: var(--border-radius-l);
|
236 |
+
padding: var(--padding-m); margin-bottom: var(--padding-l);
|
|
|
|
|
|
|
|
|
237 |
}
|
238 |
+
.section-title { font-size: 1.8em; font-weight: 700; margin-bottom: var(--padding-s); line-height: 1.2; }
|
239 |
+
.section-subtitle { font-size: 1.1em; font-weight: 500; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }
|
240 |
+
.description { font-size: 1em; line-height: 1.5; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }
|
241 |
+
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: var(--padding-s); margin-top: var(--padding-m); text-align: center; }
|
242 |
+
.stat-item { background-color: rgba(255, 255, 255, 0.05); padding: var(--padding-s); border-radius: var(--border-radius-m); }
|
243 |
+
.stat-value { font-size: 1.5em; font-weight: 600; display: block; }
|
244 |
+
.stat-label { font-size: 0.85em; color: var(--text-secondary-color); display: block; }
|
245 |
+
.list-item { background-color: var(--card-bg); padding: var(--padding-m); border-radius: var(--border-radius-m); margin-bottom: var(--padding-s); display: flex; align-items: center; gap: var(--padding-s); font-size: 1.1em; font-weight: 500; }
|
246 |
+
.list-item i { font-size: 1.2em; color: var(--accent-gradient-start, #34c759); opacity: 0.8; }
|
247 |
+
.centered-cta { text-align: center; margin-top: var(--padding-l); }
|
248 |
+
.footer-greeting { text-align: center; color: var(--text-secondary-color); font-size: 0.9em; margin-top: var(--padding-l); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
.save-card-button {
|
250 |
position: fixed;
|
251 |
+
bottom: 20px;
|
252 |
left: 50%;
|
253 |
transform: translateX(-50%);
|
254 |
+
padding: 12px 24px;
|
255 |
+
border-radius: 25px;
|
256 |
background: var(--accent-gradient-green);
|
257 |
+
color: var(--text-color);
|
258 |
text-decoration: none;
|
259 |
font-weight: 600;
|
260 |
border: none;
|
261 |
cursor: pointer;
|
262 |
+
transition: opacity 0.2s ease, transform 0.2s ease;
|
263 |
z-index: 1000;
|
264 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
|
265 |
+
font-size: 1em;
|
266 |
display: flex;
|
267 |
align-items: center;
|
268 |
+
gap: 8px;
|
269 |
}
|
270 |
+
.save-card-button:hover { opacity: 0.9; transform: translateX(-50%) scale(1.03); }
|
271 |
|
272 |
.modal {
|
273 |
+
display: none; /* Hidden by default */
|
274 |
+
position: fixed; /* Stay in place */
|
275 |
+
z-index: 1001; /* Sit on top */
|
276 |
+
left: 0;
|
277 |
+
top: 0;
|
278 |
+
width: 100%; /* Full width */
|
279 |
+
height: 100%; /* Full height */
|
280 |
+
overflow: auto; /* Enable scroll if needed */
|
281 |
+
background-color: rgba(0,0,0,0.6); /* Black w/ opacity */
|
282 |
+
padding-top: 60px; /* Location of the box */
|
283 |
}
|
284 |
.modal-content {
|
285 |
+
background-color: var(--card-bg, #2c2c2e);
|
286 |
+
color: var(--text-color, #ffffff);
|
287 |
+
margin: 5% auto; /* 5% from the top and centered */
|
288 |
+
padding: var(--padding-l, 24px);
|
289 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
290 |
+
width: 85%; /* Could be more or less, depending on screen size */
|
291 |
+
max-width: 450px;
|
292 |
+
border-radius: var(--border-radius-l, 16px);
|
293 |
+
text-align: center;
|
294 |
+
position: relative;
|
295 |
+
box-shadow: 0 5px 20px rgba(0,0,0,0.3);
|
296 |
}
|
|
|
297 |
.modal-close {
|
298 |
+
color: var(--text-secondary-color, #aaa);
|
299 |
+
position: absolute;
|
300 |
+
top: 10px;
|
301 |
+
right: 15px;
|
302 |
+
font-size: 28px;
|
303 |
+
font-weight: bold;
|
304 |
+
cursor: pointer;
|
305 |
+
line-height: 1;
|
306 |
+
}
|
307 |
+
.modal-close:hover,
|
308 |
+
.modal-close:focus {
|
309 |
+
color: var(--text-color, #fff);
|
310 |
+
text-decoration: none;
|
311 |
+
}
|
312 |
+
.modal-text {
|
313 |
+
font-size: 1.1em;
|
314 |
+
line-height: 1.6;
|
315 |
+
margin-bottom: var(--padding-m, 16px);
|
316 |
+
word-wrap: break-word;
|
317 |
}
|
318 |
+
.modal-instruction {
|
319 |
+
font-size: 0.9em;
|
320 |
+
color: var(--text-secondary-color, #a0a0a5);
|
321 |
+
margin-top: var(--padding-s, 8px);
|
322 |
+
}
|
323 |
+
|
324 |
+
.icon-save::before { content: '💾'; margin-right: 5px; }
|
325 |
+
.icon-web::before { content: '🌐'; margin-right: 5px; }
|
326 |
+
.icon-mobile::before { content: '📱'; margin-right: 5px; }
|
327 |
+
.icon-code::before { content: '💻'; margin-right: 5px; }
|
328 |
+
.icon-ai::before { content: '🧠'; margin-right: 5px; }
|
329 |
+
.icon-quantum::before { content: '⚛️'; margin-right: 5px; }
|
330 |
+
.icon-business::before { content: '💼'; margin-right: 5px; }
|
331 |
+
.icon-speed::before { content: '⚡️'; margin-right: 5px; }
|
332 |
+
.icon-complexity::before { content: '🧩'; margin-right: 5px; }
|
333 |
+
.icon-experience::before { content: '⏳'; margin-right: 5px; }
|
334 |
+
.icon-clients::before { content: '👥'; margin-right: 5px; }
|
335 |
+
.icon-market::before { content: '📈'; margin-right: 5px; }
|
336 |
+
.icon-location::before { content: '📍'; margin-right: 5px; }
|
337 |
+
.icon-global::before { content: '🌍'; margin-right: 5px; }
|
338 |
+
.icon-innovation::before { content: '💡'; margin-right: 5px; }
|
339 |
+
.icon-contact::before { content: '💬'; margin-right: 5px; }
|
340 |
+
.icon-link::before { content: '🔗'; margin-right: 5px; }
|
341 |
+
.icon-leader::before { content: '🏆'; margin-right: 5px; }
|
342 |
+
.icon-company::before { content: '🏢'; margin-right: 5px; }
|
343 |
</style>
|
344 |
</head>
|
345 |
<body>
|
|
|
355 |
</div>
|
356 |
<div>
|
357 |
<span class="tag"><i class="icon-leader"></i>Лидер инноваций 2025</span>
|
|
|
358 |
</div>
|
359 |
+
<h1 class="section-title">Международный IT холдинг</h1>
|
360 |
<p class="description">
|
361 |
+
Объединяем передовые технологические компании для создания инновационных
|
362 |
+
решений мирового уровня.
|
363 |
</p>
|
364 |
+
<a href="#" class="btn contact-link" style="background: var(--accent-gradient-green); width: 100%; margin-top: var(--padding-s);">
|
365 |
+
<i class="icon-contact"></i>Связаться с нами
|
366 |
</a>
|
367 |
</section>
|
368 |
|
369 |
<section class="ecosystem-header">
|
370 |
+
<span class="tag"><i class="icon-company"></i>Наши компании</span>
|
371 |
+
<h2 class="section-title">Экосистема инноваций</h2>
|
372 |
<p class="description">
|
373 |
+
В состав холдинга входят компании, специализирующиеся на различных
|
374 |
+
направлениях передовых технологий.
|
375 |
</p>
|
376 |
</section>
|
377 |
|
378 |
<section class="section-card">
|
379 |
<div class="logo">
|
380 |
+
<img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo">
|
381 |
+
<span style="font-size: 1.3em; font-weight: 600;">Morshen Alpha</span>
|
382 |
</div>
|
383 |
+
<div style="margin: var(--padding-m) 0;">
|
384 |
+
<span class="tag"><i class="icon-ai"></i>Искусственный интеллект</span>
|
385 |
+
<span class="tag"><i class="icon-quantum"></i>Квантовые технологии</span>
|
386 |
+
<span class="tag"><i class="icon-business"></i>Бизнес-решения</span>
|
|
|
387 |
</div>
|
388 |
+
<p class="description">
|
389 |
+
Флагманская компания холдинга, специализирующаяся на разработке передовых
|
390 |
+
бизнес-решений, исследованиях и разработках в сфере искусственного интеллекта
|
391 |
+
и квантовых технологий. Наши инновации формируют будущее технологической индустрии.
|
392 |
</p>
|
393 |
<div class="stats-grid">
|
394 |
<div class="stat-item">
|
395 |
+
<span class="stat-value"><i class="icon-global"></i> 3</span>
|
396 |
<span class="stat-label">Страны присутствия</span>
|
397 |
</div>
|
398 |
<div class="stat-item">
|
399 |
+
<span class="stat-value"><i class="icon-clients"></i> 3000+</span>
|
400 |
+
<span class="stat-label">Готовых клиентов</span>
|
401 |
</div>
|
402 |
<div class="stat-item">
|
403 |
+
<span class="stat-value"><i class="icon-market"></i> 5</span>
|
404 |
+
<span class="stat-label">Лет на рынке</span>
|
405 |
</div>
|
406 |
</div>
|
407 |
</section>
|
|
|
409 |
<section class="section-card">
|
410 |
<div class="logo">
|
411 |
<img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 50px; height: 50px;">
|
412 |
+
<span style="font-size: 1.3em; font-weight: 600;">Holmgard</span>
|
413 |
</div>
|
414 |
+
<div style="margin: var(--padding-m) 0;">
|
415 |
+
<span class="tag"><i class="icon-web"></i>Веб-разработка</span>
|
416 |
+
<span class="tag"><i class="icon-mobile"></i>Мобильные приложения</span>
|
417 |
+
<span class="tag"><i class="icon-code"></i>Программное обеспечение</span>
|
418 |
</div>
|
419 |
+
<p class="description">
|
420 |
+
Инновационная студия разработки, создающая высокотехнологичные решения
|
421 |
+
для бизнеса любого масштаба. Специализируется на разработке сайтов,
|
422 |
+
мобильных приложений и программного обеспечения с использованием
|
423 |
+
передовых технологий и методологий.
|
424 |
</p>
|
425 |
<div class="stats-grid">
|
426 |
<div class="stat-item">
|
427 |
<span class="stat-value"><i class="icon-experience"></i> 10+</span>
|
428 |
+
<span class="stat-label">Лет опыта</span>
|
429 |
</div>
|
430 |
<div class="stat-item">
|
431 |
+
<span class="stat-value"><i class="icon-complexity"></i> ПО</span>
|
432 |
+
<span class="stat-label">Любой сложности</span>
|
433 |
</div>
|
434 |
<div class="stat-item">
|
435 |
+
<span class="stat-value"><i class="icon-speed"></i></span>
|
436 |
+
<span class="stat-label">Высокая скорость</span>
|
437 |
</div>
|
438 |
</div>
|
439 |
+
<div style="display: flex; gap: var(--padding-s); margin-top: var(--padding-m); flex-wrap: wrap;">
|
440 |
+
<a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon-link"></i>Перейти на сайт</a>
|
441 |
+
<a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon-contact"></i>Связаться</a>
|
442 |
</div>
|
443 |
</section>
|
444 |
|
445 |
<section>
|
446 |
+
<span class="tag"><i class="icon-global"></i>Глобальное присутствие</span>
|
447 |
+
<h2 class="section-title">Международное присутствие</h2>
|
448 |
+
<p class="description">Наши инновационные решения используются в странах:</p>
|
449 |
<div>
|
450 |
+
<div class="list-item"><i class="icon-location"></i>Узбекистан</div>
|
451 |
<div class="list-item"><i class="icon-location"></i>Казахстан</div>
|
452 |
<div class="list-item"><i class="icon-location"></i>Кыргызстан</div>
|
|
|
453 |
</div>
|
454 |
</section>
|
455 |
|
456 |
<footer class="footer-greeting">
|
457 |
+
<p id="greeting">Загрузка данных пользователя...</p>
|
458 |
</footer>
|
459 |
|
460 |
</div>
|
461 |
|
462 |
<button class="save-card-button" id="save-card-btn">
|
463 |
+
<i class="icon-save"></i>Сохранить визитку
|
464 |
</button>
|
465 |
|
|
|
466 |
<div id="saveModal" class="modal">
|
467 |
<div class="modal-content">
|
468 |
<span class="modal-close" id="modal-close-btn">×</span>
|
469 |
+
<p class="modal-text"><b>+996500398754</b></p>
|
470 |
+
<p class="modal-text">Morshen Group, IT компания</p>
|
471 |
<p class="modal-instruction">Сделайте скриншот экрана, чтобы сохранить контакт.</p>
|
472 |
</div>
|
473 |
</div>
|
474 |
|
|
|
475 |
<script>
|
476 |
const tg = window.Telegram.WebApp;
|
477 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
478 |
function setupTelegram() {
|
479 |
if (!tg || !tg.initData) {
|
480 |
console.error("Telegram WebApp script not loaded or initData is missing.");
|
481 |
const greetingElement = document.getElementById('greeting');
|
482 |
+
if(greetingElement) greetingElement.textContent = 'Не удалось загрузить данные Telegram.';
|
483 |
document.body.style.visibility = 'visible';
|
484 |
return;
|
485 |
}
|
486 |
|
487 |
tg.ready();
|
488 |
tg.expand();
|
|
|
|
|
489 |
|
490 |
+
const themeParams = tg.themeParams;
|
491 |
+
document.documentElement.style.setProperty('--bg-color', themeParams.bg_color || '#1c1c1e');
|
492 |
+
document.documentElement.style.setProperty('--text-color', themeParams.text_color || '#ffffff');
|
493 |
+
document.documentElement.style.setProperty('--hint-color', themeParams.hint_color || '#a0a0a5');
|
494 |
+
document.documentElement.style.setProperty('--link-color', themeParams.link_color || '#007aff');
|
495 |
+
document.documentElement.style.setProperty('--button-color', themeParams.button_color || '#007aff');
|
496 |
+
document.documentElement.style.setProperty('--button-text-color', themeParams.button_text_color || '#ffffff');
|
497 |
+
document.documentElement.style.setProperty('--card-bg', themeParams.secondary_bg_color || '#2c2c2e');
|
498 |
+
if (themeParams.button_color) {
|
499 |
+
document.documentElement.style.setProperty('--accent-gradient-start', themeParams.button_color);
|
500 |
+
// Adjust button gradients if needed based on theme
|
501 |
+
document.querySelectorAll('.btn').forEach(btn => {
|
502 |
+
if (!btn.classList.contains('btn-secondary') && !btn.style.background.includes('green')) { // Avoid overriding special buttons
|
503 |
+
btn.style.background = themeParams.button_color;
|
504 |
+
}
|
505 |
+
});
|
506 |
+
document.querySelectorAll('.save-card-button').forEach(btn => {
|
507 |
+
// Optional: theme the save button too, or keep it green
|
508 |
+
// btn.style.background = themeParams.button_color;
|
509 |
+
});
|
510 |
+
}
|
511 |
|
512 |
fetch('/verify', {
|
513 |
method: 'POST',
|
514 |
+
headers: {
|
515 |
+
'Content-Type': 'application/json',
|
516 |
+
},
|
517 |
body: JSON.stringify({ initData: tg.initData }),
|
518 |
})
|
519 |
.then(response => response.json())
|
520 |
.then(data => {
|
521 |
if (data.status === 'ok' && data.verified) {
|
522 |
+
console.log('Backend verification successful.');
|
523 |
} else {
|
524 |
console.warn('Backend verification failed:', data.message);
|
525 |
+
// Optionally inform user verification failed if critical
|
526 |
+
// tg.showAlert('Не удалось проверить ваши данные.');
|
527 |
}
|
528 |
})
|
529 |
.catch(error => {
|
530 |
console.error('Error sending initData for verification:', error);
|
531 |
+
// tg.showAlert('Произошла ошибка при связи с сервером.');
|
532 |
});
|
533 |
|
534 |
const user = tg.initDataUnsafe?.user;
|
535 |
const greetingElement = document.getElementById('greeting');
|
536 |
if (user) {
|
537 |
+
const name = user.first_name || user.username || 'User';
|
538 |
+
greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
|
539 |
} else {
|
540 |
greetingElement.textContent = 'Добро пожаловать!';
|
541 |
console.warn('Telegram User data not available (initDataUnsafe.user is empty).');
|
|
|
545 |
contactButtons.forEach(button => {
|
546 |
button.addEventListener('click', (e) => {
|
547 |
e.preventDefault();
|
|
|
548 |
tg.openTelegramLink('https://t.me/morshenkhan');
|
549 |
});
|
550 |
});
|
|
|
556 |
if (saveCardBtn && modal && closeBtn) {
|
557 |
saveCardBtn.addEventListener('click', (e) => {
|
558 |
e.preventDefault();
|
|
|
559 |
modal.style.display = "block";
|
560 |
+
if (tg.HapticFeedback) {
|
561 |
+
tg.HapticFeedback.impactOccurred('light');
|
562 |
+
}
|
563 |
});
|
564 |
|
565 |
closeBtn.addEventListener('click', () => {
|
|
|
586 |
if (document.body.style.visibility !== 'visible') {
|
587 |
console.error("Telegram WebApp script fallback timeout triggered.");
|
588 |
const greetingElement = document.getElementById('greeting');
|
589 |
+
if(greetingElement) greetingElement.textContent = 'Ошибка загрузки Telegram.';
|
590 |
document.body.style.visibility = 'visible';
|
591 |
}
|
592 |
+
}, 3000);
|
593 |
}
|
594 |
|
595 |
</script>
|
|
|
603 |
<head>
|
604 |
<meta charset="UTF-8">
|
605 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
606 |
+
<title>Admin - Visited Users</title>
|
|
|
|
|
|
|
607 |
<style>
|
608 |
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f0f2f5; color: #1c1c1e; margin: 0; padding: 20px; }
|
609 |
+
h1, h2 { text-align: center; color: #333; font-weight: 600; }
|
610 |
+
.container { max-width: 1200px; margin: 20px auto; background-color: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
611 |
+
.user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; margin-top: 20px; }
|
612 |
+
.user-card { background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); display: flex; flex-direction: column; align-items: center; text-align: center; transition: transform 0.2s ease, box-shadow 0.2s ease; }
|
613 |
+
.user-card:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
|
614 |
+
.user-card img { width: 70px; height: 70px; border-radius: 50%; margin-bottom: 12px; object-fit: cover; border: 2px solid #ced4da; background-color: #e9ecef; }
|
615 |
+
.user-card .name { font-weight: 600; font-size: 1.1em; margin-bottom: 4px; color: #212529; }
|
616 |
+
.user-card .username { color: #007bff; margin-bottom: 8px; font-size: 0.95em; word-break: break-all; }
|
617 |
+
.user-card .details { font-size: 0.9em; color: #495057; line-height: 1.4; }
|
618 |
+
.user-card .timestamp { font-size: 0.8em; color: #6c757d; margin-top: 12px; }
|
619 |
+
.no-users { text-align: center; color: #6c757d; margin-top: 30px; font-size: 1.1em; }
|
620 |
+
.alert { background-color: #fff3cd; border-left: 6px solid #ffc107; margin-bottom: 20px; padding: 12px 18px; color: #856404; border-radius: 4px; text-align: center; font-weight: 500;}
|
621 |
+
.action-buttons { margin-top: 30px; text-align: center; padding-bottom: 10px;}
|
622 |
+
.action-buttons button {
|
623 |
+
padding: 10px 18px; border: none; border-radius: 8px;
|
624 |
+
background-color: #007bff; color: white;
|
625 |
+
font-weight: 500; cursor: pointer; margin: 0 10px;
|
626 |
+
transition: background-color 0.2s ease, box-shadow 0.2s ease;
|
627 |
+
font-size: 0.95em;
|
628 |
+
}
|
629 |
+
.action-buttons button:hover { background-color: #0056b3; box-shadow: 0 2px 8px rgba(0, 123, 255, 0.4); }
|
630 |
+
.action-buttons .backup-btn { background-color: #28a745; }
|
631 |
+
.action-buttons .backup-btn:hover { background-color: #218838; box-shadow: 0 2px 8px rgba(40, 167, 69, 0.4); }
|
632 |
+
.action-buttons .download-btn { background-color: #17a2b8; }
|
633 |
+
.action-buttons .download-btn:hover { background-color: #138496; box-shadow: 0 2px 8px rgba(23, 162, 184, 0.4); }
|
634 |
+
|
635 |
+
/* Spinner */
|
636 |
+
.loader {
|
637 |
+
border: 4px solid #f3f3f3; border-radius: 50%; border-top: 4px solid #3498db;
|
638 |
+
width: 20px; height: 20px; animation: spin 1s linear infinite;
|
639 |
+
display: none; /* Hidden by default */ margin: 5px auto 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
640 |
}
|
641 |
+
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
|
642 |
+
.button-loading .loader { display: inline-block; vertical-align: middle; margin-left: 8px; margin-top: -2px; }
|
643 |
+
button:disabled { opacity: 0.7; cursor: not-allowed; }
|
644 |
</style>
|
645 |
</head>
|
646 |
<body>
|
647 |
+
<div class="container">
|
648 |
+
<h1>Admin Panel</h1>
|
649 |
+
<div class="alert">WARNING: This panel is not password protected. Implement authentication for production use.</div>
|
650 |
+
|
651 |
+
<div class="action-buttons">
|
652 |
+
<form id="backup-form" method="POST" action="{{ url_for('backup') }}" style="display: inline;">
|
653 |
+
<button type="submit" class="backup-btn" id="backup-btn">Backup to HF <span class="loader"></span></button>
|
654 |
+
</form>
|
655 |
+
<form id="download-form" method="POST" action="{{ url_for('download') }}" style="display: inline;">
|
656 |
+
<button type="submit" class="download-btn" id="download-btn">Download from HF <span class="loader"></span></button>
|
657 |
+
</form>
|
658 |
+
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
659 |
|
660 |
+
<h2>Visited Users</h2>
|
661 |
+
{% if users %}
|
662 |
+
<div class="user-grid">
|
663 |
+
{% for user in users|sort(attribute='visited_at', reverse=true) %}
|
664 |
+
<div class="user-card">
|
665 |
+
<img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%23e9ecef%27/%3e%3ctext x=%2750%25%27 y=%2755%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%23adb5bd%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar">
|
666 |
+
<div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
|
667 |
+
{% if user.username %}
|
668 |
+
<div class="username"><a href="https://t.me/{{ user.username }}" target="_blank" title="Open profile">@{{ user.username }}</a></div>
|
669 |
+
{% else %}
|
670 |
+
<div class="username">- no username -</div>
|
671 |
+
{% endif %}
|
672 |
+
<div class="details">
|
673 |
+
ID: {{ user.id }} <br>
|
674 |
+
Lang: {{ user.language_code or 'N/A' }} <br>
|
675 |
+
</div>
|
676 |
+
<div class="timestamp">Last Visit: {{ user.visited_at_str }}</div>
|
677 |
</div>
|
678 |
+
{% endfor %}
|
679 |
+
</div>
|
680 |
+
{% else %}
|
681 |
+
<p class="no-users">No user visit data recorded yet.</p>
|
682 |
+
{% endif %}
|
683 |
+
</div>
|
684 |
+
|
685 |
+
<script>
|
686 |
+
function handleFormSubmit(formId, buttonId) {
|
687 |
+
const form = document.getElementById(formId);
|
688 |
+
const button = document.getElementById(buttonId);
|
689 |
+
const loader = button.querySelector('.loader');
|
690 |
+
|
691 |
+
form.addEventListener('submit', function(event) {
|
692 |
+
event.preventDefault(); // Prevent default form submission
|
693 |
+
|
694 |
+
button.disabled = true;
|
695 |
+
loader.style.display = 'inline-block';
|
696 |
+
button.classList.add('button-loading');
|
697 |
+
|
698 |
+
fetch(form.action, {
|
699 |
+
method: form.method,
|
700 |
+
// No body needed for these actions unless sending data
|
701 |
+
})
|
702 |
+
.then(response => response.json()) // Expect JSON response
|
703 |
+
.then(data => {
|
704 |
+
alert(data.message || 'Operation completed.'); // Show feedback
|
705 |
+
if(formId === 'download-form' && data.success) {
|
706 |
+
// Reload page after successful download to show updated data
|
707 |
+
window.location.reload();
|
708 |
+
}
|
709 |
+
})
|
710 |
+
.catch(error => {
|
711 |
+
console.error('Error:', error);
|
712 |
+
alert('An error occurred.');
|
713 |
+
})
|
714 |
+
.finally(() => {
|
715 |
+
// Re-enable button and hide loader regardless of success/failure
|
716 |
+
button.disabled = false;
|
717 |
+
loader.style.display = 'none';
|
718 |
+
button.classList.remove('button-loading');
|
719 |
+
});
|
720 |
+
});
|
721 |
+
}
|
722 |
+
|
723 |
+
handleFormSubmit('backup-form', 'backup-btn');
|
724 |
+
handleFormSubmit('download-form', 'download-btn');
|
725 |
+
</script>
|
726 |
</body>
|
727 |
</html>
|
728 |
"""
|
|
|
735 |
|
736 |
@app.route('/verify', methods=['POST'])
|
737 |
def verify_data():
|
738 |
+
start_time = time.time()
|
739 |
try:
|
740 |
data = request.get_json()
|
741 |
init_data_str = data.get('initData')
|
742 |
if not init_data_str:
|
743 |
+
logging.warning("Received request to /verify with missing initData.")
|
744 |
return jsonify({"status": "error", "message": "Missing initData"}), 400
|
745 |
|
746 |
+
# We parse the data *before* verification to potentially log user ID even on failure
|
|
|
|
|
747 |
user_info_dict = {}
|
748 |
+
parsed_data, is_valid = verify_telegram_data(init_data_str)
|
749 |
+
|
750 |
+
if parsed_data and 'user' in parsed_data:
|
751 |
try:
|
752 |
+
# Make sure to decode the URL-encoded JSON string
|
753 |
+
user_json_str = unquote(parsed_data['user'][0])
|
754 |
user_info_dict = json.loads(user_json_str)
|
755 |
except Exception as e:
|
756 |
logging.error(f"Could not parse user JSON from initData: {e}")
|
757 |
+
user_info_dict = {} # Ensure it's a dict even on error
|
758 |
+
|
759 |
+
user_id = user_info_dict.get('id')
|
760 |
|
761 |
if is_valid:
|
|
|
762 |
if user_id:
|
763 |
+
# Load current data, update, and save
|
764 |
+
all_user_data = load_data()
|
765 |
+
now = time.time()
|
766 |
+
# Ensure ID is stored as string key for JSON compatibility
|
767 |
+
user_id_str = str(user_id)
|
768 |
+
all_user_data[user_id_str] = {
|
|
|
|
|
|
|
|
|
|
|
769 |
'id': user_id,
|
770 |
+
'first_name': user_info_dict.get('first_name'),
|
771 |
+
'last_name': user_info_dict.get('last_name'),
|
772 |
+
'username': user_info_dict.get('username'),
|
773 |
+
'photo_url': user_info_dict.get('photo_url'),
|
774 |
+
'language_code': user_info_dict.get('language_code'),
|
775 |
+
'visited_at': now,
|
776 |
+
'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S UTC') # Use UTC
|
777 |
+
}
|
778 |
+
save_data(all_user_data) # Save triggers HF upload
|
779 |
+
logging.info(f"Verified and recorded visit for user ID: {user_id}. Processing time: {time.time() - start_time:.4f}s")
|
|
|
|
|
780 |
else:
|
781 |
+
logging.warning("Verification successful, but user ID missing in parsed data.")
|
|
|
782 |
|
783 |
return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
|
784 |
else:
|
785 |
+
logging.warning(f"Verification failed for user ID: {user_id if user_id else 'Unknown'}. Processing time: {time.time() - start_time:.4f}s")
|
786 |
+
return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
|
787 |
|
788 |
except Exception as e:
|
789 |
+
logging.error(f"Error in /verify endpoint: {e}", exc_info=True)
|
790 |
return jsonify({"status": "error", "message": "Internal server error"}), 500
|
791 |
|
|
|
792 |
@app.route('/admin')
|
793 |
def admin_panel():
|
794 |
+
# WARNING: This route is unprotected! Add proper authentication/authorization for production.
|
795 |
+
user_data = load_data()
|
796 |
+
users_list = list(user_data.values())
|
797 |
+
return render_template_string(ADMIN_TEMPLATE, users=users_list)
|
798 |
+
|
799 |
+
@app.route('/backup', methods=['POST'])
|
800 |
+
def backup():
|
801 |
+
# WARNING: Protect this route in production
|
802 |
+
success = upload_db_to_hf()
|
803 |
+
if success:
|
804 |
+
return jsonify({"success": True, "message": "Backup to Hugging Face initiated successfully."}), 200
|
|
|
|
|
|
|
805 |
else:
|
806 |
+
return jsonify({"success": False, "message": "Backup to Hugging Face failed. Check logs."}), 500
|
807 |
+
|
808 |
+
@app.route('/download', methods=['POST'])
|
809 |
+
def download():
|
810 |
+
# WARNING: Protect this route in production
|
811 |
+
success = download_db_from_hf()
|
812 |
+
if success:
|
813 |
+
return jsonify({"success": True, "message": f"{DATA_FILE} downloaded successfully from Hugging Face. Refresh page to see changes."}), 200
|
|
|
|
|
|
|
|
|
814 |
else:
|
815 |
+
# It might fail because the repo/file doesn't exist, which isn't necessarily a server error
|
816 |
+
return jsonify({"success": False, "message": f"Failed to download {DATA_FILE} from Hugging Face. It might not exist yet. Check logs."}), 404
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
817 |
|
818 |
|
819 |
# --- Main Execution ---
|
820 |
+
|
821 |
if __name__ == '__main__':
|
822 |
+
# Initial load attempt on startup
|
823 |
+
logging.info("Application starting. Attempting initial data load...")
|
824 |
+
load_data()
|
825 |
+
|
826 |
+
print(f"\n--- SECURITY WARNING ---")
|
827 |
+
print(f"The /admin, /backup, /download routes are NOT password protected.")
|
828 |
+
print(f"Anyone knowing the URL can access visitor data and trigger backups/downloads.")
|
829 |
+
print(f"Implement proper authentication before deploying to production.")
|
830 |
+
print(f"------------------------")
|
831 |
+
print(f"Starting Flask server on http://{HOST}:{PORT}")
|
832 |
+
print(f"User data will be stored in: {DATA_FILE}")
|
833 |
+
if REPO_ID and HF_TOKEN_WRITE and HF_TOKEN_READ:
|
834 |
+
print(f"Hugging Face sync enabled for repo: {REPO_ID}")
|
835 |
+
else:
|
836 |
+
print(f"Hugging Face sync DISABLED (missing REPO_ID, HF_TOKEN_WRITE, or HF_TOKEN_READ)")
|
837 |
+
print(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
|
838 |
+
|
839 |
+
# Use a production server like Gunicorn or Waitress instead of app.run() for deployment
|
840 |
+
# Example using waitress: waitress-serve --host=0.0.0.0 --port=7860 app:app
|
841 |
+
# For development:
|
842 |
+
app.run(host=HOST, port=PORT, debug=False) # Keep debug=False unless troubleshooting
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|