Aleksmorshen commited on
Commit
0db87d2
·
verified ·
1 Parent(s): b675c79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +495 -589
app.py CHANGED
@@ -2,73 +2,79 @@
2
  # -*- coding: utf-8 -*-
3
 
4
  import os
5
- import json
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, HFValidationError
16
 
17
- # --- Configuration ---
18
- BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Use environment variable or default
19
  HOST = '0.0.0.0'
20
  PORT = 7860
21
- DATA_FILE = 'data.json'
22
- REPO_ID = "flpolprojects/teledata" # Target HF repo
23
- HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", os.getenv("HF_TOKEN")) # Use specific write token or general HF_TOKEN
24
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", os.getenv("HF_TOKEN")) # Use specific read token or general HF_TOKEN
25
- BACKUP_INTERVAL = 900 # seconds (15 minutes)
 
 
 
 
 
 
 
 
26
 
27
  app = Flask(__name__)
28
 
29
- # --- Logging Setup ---
30
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
31
 
32
- # --- Hugging Face & Data Handling ---
33
 
34
- def load_user_data():
35
- try:
36
- with open(DATA_FILE, 'r', encoding='utf-8') as f:
37
- data = json.load(f)
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
- with open(DATA_FILE, 'w', encoding='utf-8') as f:
56
- json.dump(data, f, ensure_ascii=False, indent=4)
57
- logging.info(f"Successfully saved user data to local {DATA_FILE}")
 
 
 
 
 
 
 
 
58
  return True
 
 
 
59
  except Exception as e:
60
- logging.error(f"Error saving user data to {DATA_FILE}: {e}")
 
 
 
 
61
  return False
62
 
63
  def upload_db_to_hf():
64
- if not HF_TOKEN_WRITE:
65
- logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.")
66
  return False
67
  if not os.path.exists(DATA_FILE):
68
- logging.warning(f"{DATA_FILE} not found. Skipping Hugging Face upload.")
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"Automated user data backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
80
  )
81
- logging.info(f"Successfully uploaded {DATA_FILE} to Hugging Face repo {REPO_ID}")
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
- def download_db_from_hf():
91
- if not HF_TOKEN_READ:
92
- logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.")
93
- return False
 
94
  try:
95
- hf_hub_download(
96
- repo_id=REPO_ID,
97
- filename=DATA_FILE,
98
- repo_type="dataset",
99
- token=HF_TOKEN_READ,
100
- local_dir=".",
101
- local_dir_use_symlinks=False, # Important for Docker/simple setups
102
- force_download=True # Ensure we get the latest version
103
- )
104
- logging.info(f"Successfully downloaded {DATA_FILE} from Hugging Face repo {REPO_ID}")
105
- return True
106
- except RepositoryNotFoundError:
107
- logging.warning(f"Hugging Face repository {REPO_ID} not found or {DATA_FILE} does not exist there yet.")
108
- return False
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 downloading {DATA_FILE} from Hugging Face: {e}")
114
- return False
115
 
116
- def periodic_backup():
117
- logging.info(f"Starting periodic backup thread. Interval: {BACKUP_INTERVAL} seconds.")
118
- while True:
119
- time.sleep(BACKUP_INTERVAL)
120
- logging.info("Initiating periodic backup to Hugging Face...")
121
- save_user_data(user_data_global) # Save current in-memory data before backup
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: No hash found in initData.")
132
  return None, False
133
 
134
  data_check_list = []
135
  for key, value in sorted(parsed_data.items()):
136
- # Decode URL-encoded values before adding
137
- # Special handling for 'user' which might be double-encoded
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, e.g., 24 hours, adjust as needed for security
154
- if current_time - auth_date > 86400:
155
- logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).")
156
- # logging.info("Telegram data verified successfully.") # Can be noisy
 
157
  return parsed_data, True
158
  else:
159
- logging.warning(f"Data verification failed. Hash mismatch. Calculated: {calculated_hash}, Received: {received_hash}")
160
- logging.debug(f"Data check string used for hash calculation:\n{data_check_string}")
 
161
  return parsed_data, False
162
  except Exception as e:
163
- logging.error(f"Error verifying Telegram data: {e}", exc_info=True)
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-gradient-start: #10141F;
185
- --bg-gradient-end: #1A202C;
186
- --card-bg: rgba(45, 55, 72, 0.7);
187
- --card-border: rgba(74, 85, 104, 0.5);
188
- --text-primary: #E2E8F0;
189
- --text-secondary: #A0AEC0;
190
- --text-accent: #63B3ED; /* Light Blue Accent */
191
- --accent-gradient: linear-gradient(90deg, #4299E1, #3182CE); /* Blue Gradient */
192
- --accent-gradient-green: linear-gradient(90deg, #48BB78, #38A169); /* Green Gradient */
193
- --tag-bg: rgba(74, 85, 104, 0.4);
194
- --tag-text: #CBD5E0;
195
- --stat-bg: rgba(255, 255, 255, 0.05);
196
- --border-radius-sm: 6px;
197
- --border-radius-md: 10px;
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: linear-gradient(180deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%); scroll-behavior: smooth; }
209
  body {
210
  font-family: var(--font-family);
211
- background: linear-gradient(180deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
212
- color: var(--text-primary);
213
- padding: var(--padding-md);
214
- padding-bottom: 120px; /* Space for save button */
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: 700px; margin: 0 auto; display: flex; flex-direction: column; gap: var(--padding-lg); }
222
-
223
- .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--padding-md); }
224
- .logo { display: flex; align-items: center; gap: var(--padding-md); }
225
- .logo img {
226
- width: 50px; height: 50px; border-radius: 50%;
227
- object-fit: cover; border: 2px solid rgba(255, 255, 255, 0.1);
228
- box-shadow: var(--shadow-md);
 
 
229
  }
230
- .logo span { font-size: 1.6em; font-weight: 700; letter-spacing: -0.5px; }
231
-
232
  .btn {
233
  display: inline-flex; align-items: center; justify-content: center;
234
- padding: 12px var(--padding-lg); border-radius: var(--border-radius-md);
235
- background: var(--accent-gradient); color: #ffffff;
236
- text-decoration: none; font-weight: 600; border: none; cursor: pointer;
237
- transition: all 0.3s ease; gap: 8px; font-size: 1em;
238
- box-shadow: var(--shadow-sm);
239
  }
240
- .btn:hover { opacity: 0.9; transform: translateY(-2px); box-shadow: var(--shadow-md); }
241
- .btn-secondary { background: var(--card-bg); color: var(--text-accent); border: 1px solid var(--card-border); }
242
- .btn-secondary:hover { background: rgba(74, 85, 104, 0.6); }
243
-
244
  .tag {
245
- display: inline-block; background: var(--tag-bg); color: var(--tag-text);
246
- padding: 6px 12px; border-radius: var(--border-radius-sm); font-size: 0.85em; font-weight: 500;
247
- margin: 4px 6px 4px 0; white-space: nowrap; border: 1px solid rgba(255, 255, 255, 0.1);
248
  }
249
- .tag i { margin-right: 5px; opacity: 0.8; font-size: 0.9em; }
250
-
251
  .section-card {
252
- background-color: var(--card-bg); border-radius: var(--border-radius-lg);
253
- padding: var(--padding-lg); margin-bottom: var(--padding-lg);
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-card:hover {
260
- transform: translateY(-3px);
261
- box-shadow: 0 15px 25px rgba(0, 0, 0, 0.15);
262
- }
263
-
264
- .section-title { font-size: 2em; font-weight: 700; margin-bottom: var(--padding-sm); line-height: 1.2; letter-spacing: -0.5px; }
265
- .section-subtitle { font-size: 1.2em; font-weight: 500; color: var(--text-secondary); margin-bottom: var(--padding-md); }
266
- .description { font-size: 1.05em; line-height: 1.6; color: var(--text-secondary); margin-bottom: var(--padding-md); }
267
-
268
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: var(--padding-md); margin-top: var(--padding-md); text-align: center; }
269
- .stat-item { background-color: var(--stat-bg); padding: var(--padding-md); border-radius: var(--border-radius-md); border: 1px solid rgba(255,255,255,0.08); }
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: 30px;
283
  left: 50%;
284
  transform: translateX(-50%);
285
- padding: 14px 28px;
286
- border-radius: 30px;
287
  background: var(--accent-gradient-green);
288
- color: #ffffff;
289
  text-decoration: none;
290
  font-weight: 600;
291
  border: none;
292
  cursor: pointer;
293
- transition: all 0.3s ease;
294
  z-index: 1000;
295
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
296
- font-size: 1.1em;
297
  display: flex;
298
  align-items: center;
299
- gap: 10px;
300
  }
301
- .save-card-button:hover { opacity: 0.9; transform: translateX(-50%) scale(1.05); box-shadow: 0 8px 25px rgba(72, 187, 120, 0.5); }
302
 
303
  .modal {
304
- display: none; position: fixed; z-index: 1001;
305
- left: 0; top: 0; width: 100%; height: 100%;
306
- overflow: auto; background-color: rgba(0,0,0,0.7);
307
- backdrop-filter: blur(8px);
308
- padding-top: 80px;
 
 
 
 
 
309
  }
310
  .modal-content {
311
- background-color: var(--card-bg); color: var(--text-primary);
312
- margin: 5% auto; padding: var(--padding-lg);
313
- border: 1px solid var(--card-border);
314
- width: 90%; max-width: 480px;
315
- border-radius: var(--border-radius-lg);
316
- text-align: center; position: relative;
317
- box-shadow: 0 10px 30px rgba(0,0,0,0.4);
318
- animation: fadeInScale 0.4s ease-out;
 
 
 
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); position: absolute;
323
- top: 15px; right: 20px; font-size: 32px; font-weight: bold;
324
- cursor: pointer; line-height: 1; transition: color 0.2s ease;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  }
326
- .modal-close:hover, .modal-close:focus { color: var(--text-primary); }
327
- .modal-text { font-size: 1.2em; line-height: 1.7; margin-bottom: var(--padding-md); word-wrap: break-word; }
328
- .modal-text b { color: var(--text-accent); font-weight: 700; font-size: 1.3em; display: block; margin-bottom: 10px;}
329
- .modal-instruction { font-size: 1em; color: var(--text-secondary); margin-top: var(--padding-sm); }
330
-
331
- /* Icons - using text for simplicity */
332
- .icon-save::before { content: '💾'; margin-right: 8px; }
333
- .icon-web::before { content: '🌐'; margin-right: 8px; }
334
- .icon-mobile::before { content: '📱'; margin-right: 8px; }
335
- .icon-code::before { content: '💻'; margin-right: 8px; }
336
- .icon-ai::before { content: '🧠'; margin-right: 8px; }
337
- .icon-quantum::before { content: '⚛️'; margin-right: 8px; }
338
- .icon-business::before { content: '💼'; margin-right: 8px; }
339
- .icon-speed::before { content: '⚡️'; margin-right: 8px; }
340
- .icon-complexity::before { content: '🧩'; margin-right: 8px; }
341
- .icon-experience::before { content: '⏳'; margin-right: 8px; }
342
- .icon-clients::before { content: '👥'; margin-right: 8px; }
343
- .icon-market::before { content: '📈'; margin-right: 8px; }
344
- .icon-location::before { content: '📍'; margin-right: 8px; }
345
- .icon-global::before { content: '🌍'; margin-right: 8px; }
346
- .icon-innovation::before { content: '💡'; margin-right: 8px; }
347
- .icon-contact::before { content: '💬'; margin-right: 8px; }
348
- .icon-link::before { content: '🔗'; margin-right: 8px; }
349
- .icon-leader::before { content: '🏆'; margin-right: 8px; }
350
- .icon-company::before { content: '🏢'; margin-right: 8px; }
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" style="margin-top: var(--padding-md);">Цифровая Трансформация Бизнеса</h1>
369
  <p class="description">
370
- Мы международный IT холдинг, объединяющий экспертизу и ресурсы для создания прорывных
371
- технологических решений, которые формируют будущее индустрий по всему миру.
372
  </p>
373
- <a href="#" class="btn contact-link" style="background: var(--accent-gradient-green); width: 100%; margin-top: var(--padding-md);">
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>Структура Холдинга</span>
380
- <h2 class="section-title">Экосистема Инноваций</h2>
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" style="width: 50px; height: 50px;">
390
- <span style="font-size: 1.5em; font-weight: 600;">Morshen Alpha</span>
391
  </div>
392
- <div style="margin: var(--padding-md) 0; display: flex; flex-wrap: wrap; gap: 10px;">
393
- <span class="tag"><i class="icon-ai"></i>AI & ML</span>
394
- <span class="tag"><i class="icon-quantum"></i>Quantum Research</span>
395
- <span class="tag"><i class="icon-business"></i>Enterprise Solutions</span>
396
- <span class="tag"><i class="icon-innovation"></i>R&D Hub</span>
397
  </div>
398
- <p class="description" style="font-size: 1.1em;">
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+</span>
405
  <span class="stat-label">Страны присутствия</span>
406
  </div>
407
  <div class="stat-item">
408
- <span class="stat-value"><i class="icon-clients"></i> 3K+</span>
409
- <span class="stat-label">Корп. клиентов</span>
410
  </div>
411
  <div class="stat-item">
412
- <span class="stat-value"><i class="icon-market"></i> 5+</span>
413
- <span class="stat-label">Лет экспертизы</span>
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.5em; font-weight: 600;">Holmgard</span>
422
  </div>
423
- <div style="margin: var(--padding-md) 0; display: flex; flex-wrap: wrap; gap: 10px;">
424
- <span class="tag"><i class="icon-web"></i>Веб-платформы</span>
425
- <span class="tag"><i class="icon-mobile"></i>Mobile Apps (iOS/Android)</span>
426
- <span class="tag"><i class="icon-code"></i>Custom Software Dev</span>
427
  </div>
428
- <p class="description" style="font-size: 1.1em;">
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">Лет опыта команды</span>
436
  </div>
437
  <div class="stat-item">
438
- <span class="stat-value"><i class="icon-complexity"></i> High</span>
439
- <span class="stat-label">Сложность проектов</span>
440
  </div>
441
  <div class="stat-item">
442
- <span class="stat-value"><i class="icon-speed"></i> Agile</span>
443
- <span class="stat-label">Методология</span>
444
  </div>
445
  </div>
446
- <div style="display: flex; gap: var(--padding-md); margin-top: var(--padding-lg); flex-wrap: wrap;">
447
- <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon-link"></i>Вебсайт Студии</a>
448
- <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon-contact"></i>Запросить консультацию</a>
449
  </div>
450
  </section>
451
 
452
  <section>
453
- <span class="tag"><i class="icon-global"></i>География</span>
454
- <h2 class="section-title">Глобальное Присутствие</h2>
455
- <p class="description">Наши решения успешно внедрены и работают в:</p>
456
  <div>
457
- <div class="list-item"><i class="icon-location"></i>Узбекистан (Региональный Хаб)</div>
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">Инициализация...</p>
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>+996 500 398 754</b></p>
479
- <p class="modal-text" style="font-size: 1.1em;">Morshen Group (IT Holding)</p>
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 = 'Ошибка: Не удалось получить данные Telegram.';
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
- applyTheme(tg.themeParams);
544
- tg.onEvent('themeChanged', () => applyTheme(tg.themeParams));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545
 
546
  fetch('/verify', {
547
  method: 'POST',
548
- headers: { 'Content-Type': 'application/json' },
 
 
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 for user:', data.user?.id);
555
  } else {
556
  console.warn('Backend verification failed:', data.message);
557
- // Consider showing a non-blocking warning
558
- // tg.showAlert('Не удалось проверить данные сессии.');
559
  }
560
  })
561
  .catch(error => {
562
  console.error('Error sending initData for verification:', error);
563
- // tg.showAlert('Ошибка связи с сервером.');
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 = `👋 Добро пожаловать, ${name}!`;
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
- }, 3500); // Slightly longer timeout
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 - Посетители</title>
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
- :root {
643
- --admin-bg: #1A202C; /* Dark Blue/Gray */
644
- --admin-card-bg: #2D3748; /* Slightly Lighter Dark Blue/Gray */
645
- --admin-text-primary: #E2E8F0; /* Light Gray */
646
- --admin-text-secondary: #A0AEC0; /* Gray */
647
- --admin-accent: #63B3ED; /* Light Blue */
648
- --admin-border: #4A5568; /* Medium Gray */
649
- --admin-danger: #F56565; /* Red */
650
- --admin-success: #68D391; /* Green */
651
- --border-radius: 8px;
652
- --padding: 16px;
653
- --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
654
- }
655
- body {
656
- font-family: 'Inter', sans-serif;
657
- background-color: var(--admin-bg);
658
- color: var(--admin-text-primary);
659
- margin: 0;
660
- padding: var(--padding);
661
- }
662
- h1, h2 {
663
- text-align: center;
664
- color: var(--admin-text-primary);
665
- margin-bottom: 1.5em;
666
- font-weight: 600;
667
- }
668
- .controls {
669
- display: flex;
670
- justify-content: center;
671
- gap: var(--padding);
672
- margin-bottom: calc(var(--padding) * 1.5);
673
- flex-wrap: wrap;
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
- a { color: var(--admin-accent); text-decoration: none; }
734
- a:hover { text-decoration: underline; }
 
735
  </style>
736
  </head>
737
  <body>
738
- <h1>Панель Администратора</h1>
739
- <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div>
740
-
741
- {% with messages = get_flashed_messages(with_categories=true) %}
742
- {% if messages %}
743
- {% for category, message in messages %}
744
- <div class="message {{ category }}">{{ message }}</div>
745
- {% endfor %}
746
- {% endif %}
747
- {% endwith %}
748
-
749
- <h2>Управление Базой Данных Посетителей</h2>
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
- <h2>Список Посетителей (из локального {{ data_file_name }})</h2>
763
- {% if users %}
764
- <div class="user-grid">
765
- {% for user_id, user in users.items()|sort(attribute='1.last_visited_at', reverse=true) %}
766
- <div class="user-card">
767
- <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%234A5568%27/%3e%3ctext x=%2750%25%27 y=%2750%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2740%27 font-family=%27sans-serif%27 fill=%27%23A0AEC0%27%3e?%3c/text%3e%3c/svg%3e' }}"
768
- alt="User Avatar"
769
- onerror="this.onerror=null; this.src='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%234A5568%27/%3e%3ctext x=%2750%25%27 y=%2750%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2740%27 font-family=%27sans-serif%27 fill=%27%23A0AEC0%27%3e?%3c/text%3e%3c/svg%3e';">
770
- <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
771
- {% if user.username %}
772
- <div class="username"><a href="https://t.me/{{ user.username }}" target="_blank">@{{ user.username }}</a></div>
773
- {% else %}
774
- <div class="username" style="opacity: 0.6;">Нет @username</div>
775
- {% endif %}
776
- <div class="details">
777
- ID: {{ user.id }} <br>
778
- Lang: {{ user.language_code or 'N/A' }}
779
  </div>
780
- <div class="timestamp">Последний визит: {{ user.last_visited_at_str or 'N/A' }}</div>
781
- </div>
782
- {% endfor %}
783
- </div>
784
- {% else %}
785
- <p class="no-users">Данные о посетителях отсутствуют в локальном файле {{ data_file_name }}.</p>
786
- {% endif %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
  </body>
788
  </html>
789
  """
@@ -796,141 +735,108 @@ def index():
796
 
797
  @app.route('/verify', methods=['POST'])
798
  def verify_data():
799
- global user_data_global
800
  try:
801
  data = request.get_json()
802
  init_data_str = data.get('initData')
803
  if not init_data_str:
804
- logging.warning("Verify request missing initData.")
805
  return jsonify({"status": "error", "message": "Missing initData"}), 400
806
 
807
- # logging.debug(f"Received initData string: {init_data_str}")
808
- user_data_parsed, is_valid = verify_telegram_data(init_data_str)
809
-
810
  user_info_dict = {}
811
- if user_data_parsed and 'user' in user_data_parsed:
 
 
812
  try:
813
- # The 'user' value is typically a URL-encoded JSON string
814
- user_json_str = unquote(user_data_parsed['user'][0])
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
- # Log the problematic string if needed: logging.debug(f"Problematic user string: {user_data_parsed['user'][0]}")
819
- user_info_dict = {}
 
820
 
821
  if is_valid:
822
- user_id = user_info_dict.get('id')
823
  if user_id:
824
- user_id_str = str(user_id) # Use string keys for JSON consistency
825
- now = datetime.now()
826
- now_iso = now.isoformat()
827
- now_str = now.strftime('%Y-%m-%d %H:%M:%S')
828
-
829
- if user_id_str not in user_data_global:
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', user_data_global[user_id_str].get('first_name')),
837
- 'last_name': user_info_dict.get('last_name', user_data_global[user_id_str].get('last_name')),
838
- 'username': user_info_dict.get('username', user_data_global[user_id_str].get('username')),
839
- 'photo_url': user_info_dict.get('photo_url', user_data_global[user_id_str].get('photo_url')),
840
- 'language_code': user_info_dict.get('language_code', user_data_global[user_id_str].get('language_code')),
841
- 'last_visited_at': now_iso, # Always update last visit
842
- 'last_visited_at_str': now_str # Human-readable version
843
- })
844
- # Periodically save or save on significant changes? Saving every time can be I/O intensive.
845
- # Let's save here for simplicity in this example.
846
- save_user_data(user_data_global)
847
-
848
  else:
849
- logging.warning("Verification successful but user ID missing in parsed user data.")
850
-
851
 
852
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
853
  else:
854
- logging.warning(f"Verification failed for request. User data (if parsed): {user_info_dict.get('id', 'N/A')}")
855
- return jsonify({"status": "error", "verified": False, "message": "Invalid data hash"}), 403
856
 
857
  except Exception as e:
858
- logging.error(f"Critical error in /verify endpoint: {e}", exc_info=True)
859
  return jsonify({"status": "error", "message": "Internal server error"}), 500
860
 
861
-
862
  @app.route('/admin')
863
  def admin_panel():
864
- # WARNING: Unprotected route! Implement authentication for production.
865
- current_user_data = load_user_data() # Load fresh data from local file for display
866
- return render_template_string(ADMIN_TEMPLATE, users=current_user_data, data_file_name=DATA_FILE)
867
-
868
- @app.route('/admin/backup', methods=['POST'])
869
- def backup_users():
870
- # WARNING: Unprotected route!
871
- global user_data_global
872
- from flask import flash
873
- if save_user_data(user_data_global): # Ensure current memory is saved before upload
874
- if upload_db_to_hf():
875
- flash("Резервное копирование на Hugging Face успешно завершено.", "success")
876
- else:
877
- flash("Ошибка при резервном копировании на Hugging Face.", "error")
878
  else:
879
- flash("Ошибка при сохранении локального файла перед резервным копированием.", "error")
880
- return redirect(url_for('admin_panel'))
881
-
882
-
883
- @app.route('/admin/download', methods=['POST'])
884
- def download_users():
885
- # WARNING: Unprotected route!
886
- global user_data_global
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
- flash("Ошибка при загрузке данных с Hugging Face.", "error")
893
- return redirect(url_for('admin_panel'))
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
- if not BOT_TOKEN or len(BOT_TOKEN.split(':')) != 2:
909
- logging.critical("BOT_TOKEN is missing or invalid. Please set the environment variable.")
910
- exit(1)
911
- if not HF_TOKEN_WRITE:
912
- logging.warning("HF_TOKEN_WRITE environment variable is not set. Hugging Face backups will be skipped.")
913
- if not HF_TOKEN_READ:
914
- logging.warning("HF_TOKEN_READ environment variable is not set. Hugging Face downloads might fail.")
915
-
916
-
917
- logging.info("--- SECURITY WARNING ---")
918
- logging.warning("The /admin/* routes are NOT protected by authentication.")
919
- logging.warning("Anyone knowing the URL can access visitor data and trigger DB operations.")
920
- logging.warning("Implement proper security (e.g., password auth, IP restriction) before deploying.")
921
- logging.info("------------------------")
922
- logging.info(f"Starting Flask server on http://{HOST}:{PORT}")
923
- logging.info(f"Telegram Mini App URL should point to: http://<YOUR_SERVER_IP_OR_DOMAIN>:{PORT}")
924
- logging.info(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
925
- logging.info(f"User data file: {DATA_FILE}")
926
- logging.info(f"Hugging Face Repo: {REPO_ID}")
927
-
928
- # Start the backup thread
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