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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +535 -590
app.py CHANGED
@@ -2,141 +2,126 @@
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
  import threading
 
14
  from huggingface_hub import HfApi, hf_hub_download
15
- from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
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' # File to store visited user data
22
-
23
- # Hugging Face Hub Configuration
24
- REPO_ID = "flpolprojects/teledata"
25
- HF_TOKEN = os.getenv("HF_TOKEN") # Write token
26
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", HF_TOKEN) # Read token (defaults to write token if not set)
27
- BACKUP_INTERVAL = 900 # Seconds (15 minutes)
28
 
29
  app = Flask(__name__)
30
- app.secret_key = os.urandom(24) # Needed for flash messages or sessions if used later
31
 
32
- # Logging Setup
33
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
34
 
35
- # --- Hugging Face Hub Functions ---
36
 
37
- def download_db_from_hf():
38
- if not HF_TOKEN_READ:
39
- logging.warning("HF_TOKEN_READ not set. Skipping download from Hugging Face Hub.")
40
- return False
41
  try:
42
- logging.info(f"Attempting to download {DATA_FILE} from {REPO_ID}...")
43
- hf_hub_download(
44
- repo_id=REPO_ID,
45
- filename=DATA_FILE,
46
- repo_type="dataset",
47
- token=HF_TOKEN_READ,
48
- local_dir=".",
49
- local_dir_use_symlinks=False,
50
- force_download=True, # Ensure we get the latest version
51
- resume_download=False
52
- )
53
- logging.info(f"{DATA_FILE} successfully downloaded from Hugging Face Hub.")
 
 
 
 
 
 
 
 
 
 
54
  return True
55
- except RepositoryNotFoundError:
56
- logging.warning(f"Repository {REPO_ID} not found on Hugging Face Hub. Will use/create local file.")
57
- return False
58
- except HfHubHTTPError as e:
59
- if e.response.status_code == 404:
60
- logging.warning(f"{DATA_FILE} not found in repository {REPO_ID}. Will use/create local file.")
61
- else:
62
- logging.error(f"HTTP error downloading {DATA_FILE} from Hugging Face Hub: {e}")
63
- return False
64
  except Exception as e:
65
- logging.error(f"Error downloading {DATA_FILE} from Hugging Face Hub: {e}")
66
  return False
67
 
68
  def upload_db_to_hf():
69
- if not HF_TOKEN:
70
- logging.warning("HF_TOKEN not set. Skipping upload to Hugging Face Hub.")
71
  return False
72
  if not os.path.exists(DATA_FILE):
73
- logging.warning(f"{DATA_FILE} not found locally. Skipping upload.")
74
  return False
 
75
  try:
76
  api = HfApi()
77
- logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}...")
78
  api.upload_file(
79
  path_or_fileobj=DATA_FILE,
80
  path_in_repo=DATA_FILE,
81
  repo_id=REPO_ID,
82
  repo_type="dataset",
83
- token=HF_TOKEN,
84
  commit_message=f"Automated user data backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
85
  )
86
- logging.info(f"{DATA_FILE} successfully uploaded to Hugging Face Hub.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  return True
 
 
 
 
 
 
88
  except Exception as e:
89
- logging.error(f"Error uploading {DATA_FILE} to Hugging Face Hub: {e}")
90
  return False
91
 
92
  def periodic_backup():
93
  logging.info(f"Starting periodic backup thread. Interval: {BACKUP_INTERVAL} seconds.")
94
  while True:
95
  time.sleep(BACKUP_INTERVAL)
96
- logging.info("Initiating scheduled backup...")
 
97
  upload_db_to_hf()
98
 
99
- # --- Data Handling ---
100
-
101
- def load_users():
102
- # Attempt download first
103
- download_db_from_hf()
104
-
105
- if not os.path.exists(DATA_FILE):
106
- logging.warning(f"{DATA_FILE} not found. Initializing empty user data.")
107
- return {}
108
- try:
109
- with open(DATA_FILE, 'r', encoding='utf-8') as f:
110
- users_data = json.load(f)
111
- if not isinstance(users_data, dict):
112
- logging.warning(f"{DATA_FILE} does not contain a valid JSON dictionary. Resetting.")
113
- return {}
114
- logging.info(f"Loaded {len(users_data)} user records from {DATA_FILE}.")
115
- return users_data
116
- except json.JSONDecodeError:
117
- logging.error(f"Error decoding JSON from {DATA_FILE}. Returning empty data.")
118
- # Consider backing up the corrupted file here
119
- return {}
120
- except Exception as e:
121
- logging.error(f"Error loading user data from {DATA_FILE}: {e}")
122
- return {}
123
-
124
- def save_users(users_data):
125
- try:
126
- with open(DATA_FILE, 'w', encoding='utf-8') as f:
127
- json.dump(users_data, f, ensure_ascii=False, indent=4)
128
- logging.info(f"Saved {len(users_data)} user records to {DATA_FILE}.")
129
- # Attempt upload after saving locally
130
- upload_db_to_hf()
131
- except Exception as e:
132
- logging.error(f"Error saving user data to {DATA_FILE}: {e}")
133
-
134
-
135
- # Load initial data on startup
136
- visited_users = load_users()
137
-
138
- # --- Telegram Verification ---
139
-
140
  def verify_telegram_data(init_data_str):
141
  try:
142
  parsed_data = parse_qs(init_data_str)
@@ -148,8 +133,15 @@ def verify_telegram_data(init_data_str):
148
 
149
  data_check_list = []
150
  for key, value in sorted(parsed_data.items()):
151
- # Ensure values are strings before appending
152
- data_check_list.append(f"{key}={value[0]}")
 
 
 
 
 
 
 
153
  data_check_string = "\n".join(data_check_list)
154
 
155
  secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
@@ -158,322 +150,204 @@ def verify_telegram_data(init_data_str):
158
  if calculated_hash == received_hash:
159
  auth_date = int(parsed_data.get('auth_date', [0])[0])
160
  current_time = int(time.time())
161
- # Allow slightly older data, adjust timeout as needed (e.g., 3600 for 1 hour)
162
- if current_time - auth_date > 86400: # 24 hours tolerance
163
  logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).")
164
- # logging.info("Telegram data verified successfully.")
165
  return parsed_data, True
166
  else:
167
- logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}")
 
168
  return parsed_data, False
169
  except Exception as e:
170
- logging.error(f"Error verifying Telegram data: {e}")
171
  return None, False
172
 
173
- # --- Templates ---
 
 
174
 
 
175
  TEMPLATE = """
176
  <!DOCTYPE html>
177
  <html lang="ru">
178
  <head>
179
  <meta charset="UTF-8">
180
- <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
181
- <title>Morshen Group - IT Holding</title>
182
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
183
  <link rel="preconnect" href="https://fonts.googleapis.com">
184
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
185
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
186
  <style>
187
  :root {
188
- --tg-theme-bg-color: var(--tg-bg-color, #181a1b);
189
- --tg-theme-text-color: var(--tg-text-color, #ffffff);
190
- --tg-theme-hint-color: var(--tg-hint-color, #aaaaaa);
191
- --tg-theme-link-color: var(--tg-link-color, #8774e1);
192
- --tg-theme-button-color: var(--tg-button-color, #8774e1);
193
- --tg-theme-button-text-color: var(--tg-button-text-color, #ffffff);
194
- --tg-theme-secondary-bg-color: var(--tg-secondary-bg-color, #222425);
195
-
196
- --bg-color: var(--tg-theme-bg-color);
197
- --card-bg: var(--tg-theme-secondary-bg-color);
198
- --text-color: var(--tg-theme-text-color);
199
- --text-secondary-color: var(--tg-theme-hint-color);
200
- --accent-color: var(--tg-theme-button-color);
201
- --accent-text-color: var(--tg-theme-button-text-color);
202
- --link-color: var(--tg-theme-link-color);
203
- --green-accent: #34c759;
204
- --red-accent: #ff3b30;
205
-
206
- --border-radius-s: 8px;
207
- --border-radius-m: 12px;
208
- --border-radius-l: 16px;
209
- --padding-s: 10px;
210
- --padding-m: 20px;
211
- --padding-l: 30px;
212
  --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
213
-
214
- --shadow-color: rgba(0, 0, 0, 0.2);
215
- --card-shadow: 0 4px 15px var(--shadow-color);
216
- --button-shadow: 0 3px 8px var(--shadow-color);
217
  }
218
-
219
  * { box-sizing: border-box; margin: 0; padding: 0; }
220
-
221
- html {
222
- background-color: var(--bg-color);
223
- color: var(--text-color);
224
- font-family: var(--font-family);
225
- scroll-behavior: smooth;
226
- }
227
-
228
  body {
229
- background: linear-gradient(180deg, color-mix(in srgb, var(--bg-color) 80%, black) 0%, var(--bg-color) 100%);
230
- color: var(--text-color);
231
- padding: var(--padding-m);
232
- padding-bottom: 120px; /* Space for fixed button */
 
233
  overscroll-behavior-y: none;
234
  -webkit-font-smoothing: antialiased;
235
  -moz-osx-font-smoothing: grayscale;
236
- line-height: 1.6;
237
  visibility: hidden; /* Hide until ready */
238
  }
 
239
 
240
- .container {
241
- max-width: 650px;
242
- margin: 0 auto;
243
- display: flex;
244
- flex-direction: column;
245
- gap: var(--padding-l);
246
  }
 
247
 
248
- /* Header & Logo */
249
- .header {
250
- display: flex;
251
- justify-content: space-between;
252
- align-items: center;
253
- margin-bottom: var(--padding-s);
254
- }
255
- .logo { display: flex; align-items: center; gap: var(--padding-s); }
256
- .logo img, .logo-icon {
257
- width: 48px;
258
- height: 48px;
259
- border-radius: 50%;
260
- background-color: var(--card-bg);
261
- object-fit: cover;
262
- border: 2px solid rgba(255, 255, 255, 0.1);
263
- box-shadow: 0 2px 5px var(--shadow-color);
264
- }
265
- .logo span { font-size: 1.6em; font-weight: 700; }
266
-
267
- /* Buttons */
268
  .btn {
269
  display: inline-flex; align-items: center; justify-content: center;
270
- padding: 12px var(--padding-m); border-radius: var(--border-radius-m);
271
- background: var(--accent-color); color: var(--accent-text-color);
272
  text-decoration: none; font-weight: 600; border: none; cursor: pointer;
273
- transition: all 0.25s ease-out; gap: 8px; font-size: 1em;
274
- box-shadow: var(--button-shadow);
275
- }
276
- .btn:hover {
277
- opacity: 0.9;
278
- transform: translateY(-2px);
279
- box-shadow: 0 5px 12px var(--shadow-color);
280
- }
281
- .btn-secondary {
282
- background: var(--card-bg);
283
- color: var(--accent-color);
284
- border: 1px solid color-mix(in srgb, var(--accent-color) 50%, transparent);
285
- }
286
- .btn-secondary:hover {
287
- background: color-mix(in srgb, var(--card-bg) 90%, white);
288
  }
289
- .btn-green {
290
- background: var(--green-accent); color: white;
291
- }
292
- .btn-green:hover {
293
- background: color-mix(in srgb, var(--green-accent) 90%, black);
294
- }
295
 
296
- /* Tags */
297
- .tag-container { margin: var(--padding-m) 0; display: flex; flex-wrap: wrap; gap: 8px; }
298
  .tag {
299
- display: inline-flex; align-items: center; gap: 5px;
300
- background: color-mix(in srgb, var(--card-bg) 70%, var(--accent-color) 10%);
301
- color: var(--text-secondary-color);
302
- padding: 6px 12px; border-radius: var(--border-radius-s); font-size: 0.85em; font-weight: 500;
303
- border: 1px solid rgba(255, 255, 255, 0.05);
304
  }
305
- .tag i { opacity: 0.8; }
306
 
307
- /* Cards */
308
  .section-card {
309
- background-color: var(--card-bg);
310
- border-radius: var(--border-radius-l);
311
- padding: var(--padding-m);
312
- margin-bottom: 0; /* Removed default bottom margin */
313
- box-shadow: var(--card-shadow);
314
- border: 1px solid rgba(255, 255, 255, 0.05);
315
- transition: transform 0.2s ease, box-shadow 0.2s ease;
316
  }
317
  .section-card:hover {
318
- transform: translateY(-3px);
319
- box-shadow: 0 8px 25px var(--shadow-color);
320
  }
321
 
322
- /* Typography */
323
- .section-title { font-size: 2em; font-weight: 800; margin-bottom: var(--padding-s); line-height: 1.2; }
324
- .section-subtitle { font-size: 1.2em; font-weight: 500; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }
325
- .description { font-size: 1em; line-height: 1.7; color: var(--text-secondary-color); margin-bottom: var(--padding-m); }
326
 
327
- /* Stats Grid */
328
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: var(--padding-s); margin-top: var(--padding-m); text-align: center; }
329
- .stat-item { background-color: rgba(255, 255, 255, 0.05); padding: var(--padding-s) var(--padding-m); border-radius: var(--border-radius-m); }
330
- .stat-value { font-size: 1.7em; font-weight: 700; display: block; }
331
- .stat-label { font-size: 0.8em; color: var(--text-secondary-color); display: block; text-transform: uppercase; letter-spacing: 0.5px; }
332
 
333
- /* List Items */
334
- .list-container { display: flex; flex-direction: column; gap: var(--padding-s); margin-top: var(--padding-s); }
335
- .list-item { background-color: color-mix(in srgb, var(--card-bg) 80%, black); padding: var(--padding-m); border-radius: var(--border-radius-m); display: flex; align-items: center; gap: var(--padding-m); font-size: 1.1em; font-weight: 500; }
336
- .list-item i { font-size: 1.4em; color: var(--accent-color); opacity: 0.9; width: 25px; text-align: center; }
337
 
338
- /* Footer */
339
- .footer-greeting { text-align: center; color: var(--text-secondary-color); font-size: 0.9em; margin-top: var(--padding-l); }
340
 
341
- /* Fixed Button */
342
  .save-card-button {
343
  position: fixed;
344
- bottom: 25px;
345
  left: 50%;
346
  transform: translateX(-50%);
347
  padding: 14px 28px;
348
  border-radius: 30px;
349
- background: var(--green-accent);
350
- color: white;
351
  text-decoration: none;
352
- font-weight: 700;
353
  border: none;
354
  cursor: pointer;
355
  transition: all 0.3s ease;
356
  z-index: 1000;
357
- box-shadow: 0 6px 20px rgba(52, 199, 89, 0.4);
358
  font-size: 1.1em;
359
  display: flex;
360
  align-items: center;
361
  gap: 10px;
362
- white-space: nowrap;
363
- }
364
- .save-card-button:hover {
365
- opacity: 0.9;
366
- transform: translateX(-50%) scale(1.05);
367
- box-shadow: 0 8px 25px rgba(52, 199, 89, 0.5);
368
  }
369
- .save-card-button i { font-size: 1.2em; }
370
 
371
- /* Modal Styles */
372
  .modal {
373
- display: none; /* Hidden by default */
374
- position: fixed; /* Stay in place */
375
- z-index: 1001; /* Sit on top */
376
- left: 0;
377
- top: 0;
378
- width: 100%; /* Full width */
379
- height: 100%; /* Full height */
380
- overflow: auto; /* Enable scroll if needed */
381
- background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
382
- backdrop-filter: blur(5px);
383
- -webkit-backdrop-filter: blur(5px);
384
- padding-top: 10vh; /* Location of the box */
385
- animation: fadeIn 0.3s ease-out;
386
  }
387
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
388
  .modal-content {
389
- background-color: var(--card-bg, #2c2c2e);
390
- color: var(--text-color, #ffffff);
391
- margin: 5% auto; /* 5% from the top and centered */
392
- padding: var(--padding-l, 30px);
393
- border: 1px solid rgba(255, 255, 255, 0.1);
394
- width: 90%; /* Could be more or less, depending on screen size */
395
- max-width: 480px;
396
- border-radius: var(--border-radius-l, 16px);
397
- text-align: center;
398
- position: relative;
399
  box-shadow: 0 10px 30px rgba(0,0,0,0.4);
400
- animation: slideIn 0.4s ease-out;
401
  }
402
- @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
403
  .modal-close {
404
- color: var(--text-secondary-color, #aaa);
405
- position: absolute;
406
- top: 15px;
407
- right: 20px;
408
- font-size: 32px;
409
- font-weight: bold;
410
- cursor: pointer;
411
- line-height: 1;
412
- transition: color 0.2s ease;
413
- }
414
- .modal-close:hover,
415
- .modal-close:focus {
416
- color: var(--text-color, #fff);
417
- text-decoration: none;
418
- }
419
- .modal-title {
420
- font-size: 1.5em;
421
- font-weight: 700;
422
- margin-bottom: var(--padding-s);
423
- }
424
- .modal-text {
425
- font-size: 1.2em;
426
- line-height: 1.6;
427
- margin-bottom: var(--padding-s);
428
- word-wrap: break-word;
429
- font-weight: 500;
430
- }
431
- .modal-text strong {
432
- font-weight: 700;
433
- color: var(--accent-color);
434
- }
435
- .modal-instruction {
436
- font-size: 1em;
437
- color: var(--text-secondary-color, #a0a0a5);
438
- margin-top: var(--padding-m);
439
- font-style: italic;
440
- }
441
-
442
- /* Icons */
443
- .icon { display: inline-block; font-style: normal; margin-right: 8px; }
444
- .icon-save::before { content: '💾'; }
445
- .icon-web::before { content: '🌐'; }
446
- .icon-mobile::before { content: '📱'; }
447
- .icon-code::before { content: '💻'; }
448
- .icon-ai::before { content: '🧠'; }
449
- .icon-quantum::before { content: '⚛️'; }
450
- .icon-business::before { content: '💼'; }
451
- .icon-speed::before { content: '⚡️'; }
452
- .icon-complexity::before { content: '🧩'; }
453
- .icon-experience::before { content: '⏳'; }
454
- .icon-clients::before { content: '👥'; }
455
- .icon-market::before { content: '📈'; }
456
- .icon-location::before { content: '📍'; }
457
- .icon-global::before { content: '🌍'; }
458
- .icon-innovation::before { content: '💡'; }
459
- .icon-contact::before { content: '💬'; }
460
- .icon-link::before { content: '🔗'; }
461
- .icon-leader::before { content: '🏆'; }
462
- .icon-company::before { content: '🏢'; }
463
-
464
- /* Responsive */
465
- @media (max-width: 600px) {
466
- body { padding: var(--padding-s); padding-bottom: 100px; }
467
- .container { gap: var(--padding-m); }
468
- .section-title { font-size: 1.8em; }
469
- .section-subtitle { font-size: 1.1em; }
470
- .btn { padding: 10px var(--padding-m); font-size: 0.95em; }
471
- .save-card-button { padding: 12px 24px; font-size: 1em; bottom: 20px; }
472
- .modal-content { width: 95%; padding: var(--padding-m); }
473
- .modal-title { font-size: 1.3em; }
474
- .modal-text { font-size: 1.1em; }
475
- .modal-instruction { font-size: 0.9em; }
476
- }
477
  </style>
478
  </head>
479
  <body>
@@ -485,53 +359,58 @@ TEMPLATE = """
485
  <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
486
  <span>Morshen Group</span>
487
  </div>
488
- <a href="#" class="btn btn-secondary contact-link"><i class="icon icon-contact"></i>Связаться</a>
489
  </div>
490
- <div class="tag-container">
491
- <span class="tag"><i class="icon icon-leader"></i>Лидер инноваций 2025</span>
492
- <span class="tag"><i class="icon icon-global"></i>Международный Холдинг</span>
493
  </div>
494
- <h1 class="section-title">Создаем будущее IT сегодня</h1>
495
  <p class="description">
496
- Мы — международный IT холдинг, объединяющий передовые технологические компании для создания прорывных решений мирового уровня в сферах AI, квантовых вычислений и разработки ПО.
 
497
  </p>
498
- <a href="#" class="btn btn-green contact-link" style="width: 100%; margin-top: var(--padding-s);">
499
- <i class="icon icon-contact"></i>Обсудить ваш проект
500
  </a>
501
  </section>
502
 
503
  <section class="ecosystem-header">
504
- <h2 class="section-title">Экосистема <span style="color: var(--accent-color);">Инноваций</span></h2>
 
505
  <p class="description">
506
- В состав холдинга входят специализированные компании, каждая из которых является экспертом в своей области передовых технологий.
 
507
  </p>
508
  </section>
509
 
510
  <section class="section-card">
511
  <div class="logo">
512
- <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo">
513
  <span style="font-size: 1.5em; font-weight: 600;">Morshen Alpha</span>
514
  </div>
515
- <div class="tag-container">
516
- <span class="tag"><i class="icon icon-ai"></i>Искусственный интеллект</span>
517
- <span class="tag"><i class="icon icon-quantum"></i>Квантовые технологии</span>
518
- <span class="tag"><i class="icon icon-business"></i>Стратегические решения</span>
 
519
  </div>
520
- <p class="description">
521
- Флагман холдинга. Занимаемся R&D в области AI и квантовых технологий, разрабатываем передовые бизнес-решения, формирующие будущее индустрии.
 
522
  </p>
523
  <div class="stats-grid">
524
  <div class="stat-item">
525
- <span class="stat-value"><i class="icon icon-global"></i> 3+</span>
526
- <span class="stat-label">Страны</span>
527
  </div>
528
  <div class="stat-item">
529
- <span class="stat-value"><i class="icon icon-clients"></i> 3K+</span>
530
- <span class="stat-label">Клиенты</span>
531
  </div>
532
  <div class="stat-item">
533
- <span class="stat-value"><i class="icon icon-market"></i> 5+</span>
534
- <span class="stat-label">Лет на рынке</span>
535
  </div>
536
  </div>
537
  </section>
@@ -539,64 +418,66 @@ TEMPLATE = """
539
  <section class="section-card">
540
  <div class="logo">
541
  <img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 50px; height: 50px;">
542
- <span style="font-size: 1.5em; font-weight: 600;">Holmgard Studio</span>
543
  </div>
544
- <div class="tag-container">
545
- <span class="tag"><i class="icon icon-web"></i>Веб-разработка</span>
546
- <span class="tag"><i class="icon icon-mobile"></i>Мобильные приложения</span>
547
- <span class="tag"><i class="icon icon-code"></i>Энтерпрайз ПО</span>
548
  </div>
549
- <p class="description">
550
- Студия разработки полного цикла. Создаем высокотехнологичные веб-сайты, мобильные приложения и кастомное ПО для бизнеса любого масштаба, используя современные стеки и методологии.
 
551
  </p>
552
  <div class="stats-grid">
553
  <div class="stat-item">
554
- <span class="stat-value"><i class="icon icon-experience"></i> 10+</span>
555
- <span class="stat-label">Лет опыта</span>
556
  </div>
557
  <div class="stat-item">
558
- <span class="stat-value"><i class="icon icon-complexity"></i> Highload</span>
559
- <span class="stat-label">Сложные проекты</span>
560
  </div>
561
  <div class="stat-item">
562
- <span class="stat-value"><i class="icon icon-speed"></i> Agile</span>
563
- <span class="stat-label">Быстрый запуск</span>
564
  </div>
565
  </div>
566
- <div style="display: flex; gap: var(--padding-s); margin-top: var(--padding-m); flex-wrap: wrap;">
567
- <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon icon-link"></i>На сайт</a>
568
- <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon icon-contact"></i>Связаться</a>
569
  </div>
570
  </section>
571
 
572
  <section>
573
- <h2 class="section-title"><i class="icon icon-global"></i> Глобальное Присутствие</h2>
574
- <p class="description">Наши решения и команды работают в ключевых регионах Центральной Азии:</p>
575
- <div class="list-container">
576
- <div class="list-item"><i class="icon icon-location"></i>Узбекистан</div>
577
- <div class="list-item"><i class="icon icon-location"></i>Казахстан</div>
578
- <div class="list-item"><i class="icon icon-location"></i>Кыргызстан</div>
 
 
579
  </div>
580
  </section>
581
 
582
  <footer class="footer-greeting">
583
- <p id="greeting">Загрузка данных...</p>
584
  </footer>
585
 
586
  </div>
587
 
588
  <button class="save-card-button" id="save-card-btn">
589
- <i class="icon icon-save"></i>Сохранить визитку
590
  </button>
591
 
592
  <!-- The Modal -->
593
  <div id="saveModal" class="modal">
594
  <div class="modal-content">
595
  <span class="modal-close" id="modal-close-btn">×</span>
596
- <h3 class="modal-title">Контактная информация</h3>
597
- <p class="modal-text"><strong>+996 500 398 754</strong></p>
598
- <p class="modal-text">Morshen Group, IT Holding</p>
599
- <p class="modal-instruction">Сделайте скриншот, чтобы сохранить контакт.</p>
600
  </div>
601
  </div>
602
 
@@ -605,73 +486,102 @@ TEMPLATE = """
605
  const tg = window.Telegram.WebApp;
606
 
607
  function applyTheme(themeParams) {
608
- document.documentElement.style.setProperty('--tg-bg-color', themeParams.bg_color || '#181a1b');
609
- document.documentElement.style.setProperty('--tg-text-color', themeParams.text_color || '#ffffff');
610
- document.documentElement.style.setProperty('--tg-hint-color', themeParams.hint_color || '#aaaaaa');
611
- document.documentElement.style.setProperty('--tg-link-color', themeParams.link_color || '#8774e1');
612
- document.documentElement.style.setProperty('--tg-button-color', themeParams.button_color || '#8774e1');
613
- document.documentElement.style.setProperty('--tg-button-text-color', themeParams.button_text_color || '#ffffff');
614
- document.documentElement.style.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color || '#222425');
615
- console.log("Theme applied:", themeParams);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  }
617
 
 
618
  function setupTelegram() {
619
  if (!tg || !tg.initData) {
620
  console.error("Telegram WebApp script not loaded or initData is missing.");
621
  const greetingElement = document.getElementById('greeting');
622
- if(greetingElement) greetingElement.textContent = 'Ошибка загрузки Telegram.';
623
- document.body.style.visibility = 'visible'; // Show body anyway
624
  return;
625
  }
626
 
627
  tg.ready();
628
  tg.expand();
 
 
 
629
  applyTheme(tg.themeParams);
630
- tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); // Listen for theme changes
631
 
632
- // Send initData for verification and user logging
633
  fetch('/verify', {
634
  method: 'POST',
635
- headers: {
636
- 'Content-Type': 'application/json',
637
- },
638
  body: JSON.stringify({ initData: tg.initData }),
639
  })
640
  .then(response => response.json())
641
  .then(data => {
642
  if (data.status === 'ok' && data.verified) {
643
- console.log('Backend verification successful.');
644
  } else {
645
  console.warn('Backend verification failed:', data.message);
646
- // Optionally show a non-intrusive warning
 
647
  }
648
  })
649
  .catch(error => {
650
  console.error('Error sending initData for verification:', error);
 
651
  });
652
 
653
- // User Greeting (using unsafe data for immediate feedback)
654
  const user = tg.initDataUnsafe?.user;
655
  const greetingElement = document.getElementById('greeting');
656
  if (user) {
657
  const name = user.first_name || user.username || 'Гость';
658
- greetingElement.textContent = `Приветствуем, ${name}! 👋`;
659
  } else {
660
  greetingElement.textContent = 'Добро пожаловать!';
661
- console.warn('Telegram User data (initDataUnsafe.user) not available.');
662
  }
663
 
664
- // Contact Links
665
  const contactButtons = document.querySelectorAll('.contact-link');
666
  contactButtons.forEach(button => {
667
  button.addEventListener('click', (e) => {
668
  e.preventDefault();
669
- tg.openTelegramLink('https://t.me/morshenkhan'); // Replace with actual contact username
670
- if (tg.HapticFeedback) tg.HapticFeedback.impactOccurred('light');
671
  });
672
  });
673
 
674
- // Modal Setup
675
  const modal = document.getElementById("saveModal");
676
  const saveCardBtn = document.getElementById("save-card-btn");
677
  const closeBtn = document.getElementById("modal-close-btn");
@@ -679,17 +589,16 @@ TEMPLATE = """
679
  if (saveCardBtn && modal && closeBtn) {
680
  saveCardBtn.addEventListener('click', (e) => {
681
  e.preventDefault();
 
682
  modal.style.display = "block";
683
- if (tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
684
  });
685
 
686
  closeBtn.addEventListener('click', () => {
687
  modal.style.display = "none";
688
  });
689
 
690
- // Close modal if clicked outside the content
691
- modal.addEventListener('click', (event) => { // Listen on modal overlay itself
692
- if (event.target === modal) {
693
  modal.style.display = "none";
694
  }
695
  });
@@ -697,26 +606,23 @@ TEMPLATE = """
697
  console.error("Modal elements not found!");
698
  }
699
 
700
- document.body.style.visibility = 'visible'; // Make body visible now
701
- console.log("Telegram Mini App setup complete.");
702
  }
703
 
704
- // Initialize Telegram WebApp
705
  if (window.Telegram && window.Telegram.WebApp) {
706
  setupTelegram();
707
  } else {
708
- console.warn("Telegram WebApp script not immediately available. Waiting for load event.");
709
  window.addEventListener('load', setupTelegram);
710
- // Further fallback timeout
711
  setTimeout(() => {
712
  if (document.body.style.visibility !== 'visible') {
713
- console.error("Telegram WebApp script loading fallback timeout triggered.");
714
  const greetingElement = document.getElementById('greeting');
715
  if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса.';
716
- document.body.style.visibility = 'visible'; // Force display anyway
717
  }
718
- }, 4000); // Increased timeout
719
  }
 
720
  </script>
721
  </body>
722
  </html>
@@ -731,138 +637,157 @@ ADMIN_TEMPLATE = """
731
  <title>Admin - Посетители</title>
732
  <link rel="preconnect" href="https://fonts.googleapis.com">
733
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
734
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
735
  <style>
736
  :root {
737
- --admin-bg-color: #1f2937; /* Dark Gray */
738
- --admin-card-bg: #374151; /* Medium Gray */
739
- --admin-text-color: #f3f4f6; /* Light Gray */
740
- --admin-text-secondary-color: #9ca3af; /* Gray */
741
- --admin-accent-color: #60a5fa; /* Blue */
742
- --admin-border-color: #4b5563; /* Darker Gray */
743
- --admin-shadow-color: rgba(0, 0, 0, 0.3);
744
- --border-radius: 12px;
745
- --padding: 20px;
 
 
746
  }
747
  body {
748
  font-family: 'Inter', sans-serif;
749
- background-color: var(--admin-bg-color);
750
- color: var(--admin-text-color);
751
  margin: 0;
752
  padding: var(--padding);
753
- line-height: 1.6;
754
  }
755
- .container { max-width: 1200px; margin: 0 auto; }
756
- h1 { text-align: center; color: var(--admin-accent-color); font-weight: 700; margin-bottom: 30px; }
757
- .controls { display: flex; justify-content: center; gap: 15px; margin-bottom: 30px; flex-wrap: wrap;}
758
- .control-btn {
 
 
 
 
 
 
 
 
 
 
759
  padding: 10px 20px;
760
  border: none;
761
- border-radius: 8px;
762
- background-color: var(--admin-accent-color);
763
- color: #fff;
764
- font-weight: 600;
765
  cursor: pointer;
766
  transition: all 0.2s ease;
767
- box-shadow: 0 2px 5px var(--admin-shadow-color);
768
  }
769
- .control-btn:hover {
770
- background-color: #3b82f6; /* Darker Blue */
771
- transform: translateY(-1px);
772
- box-shadow: 0 4px 10px var(--admin-shadow-color);
 
 
 
 
773
  }
774
- .control-btn.download { background-color: #34d399; } /* Green */
775
- .control-btn.download:hover { background-color: #059669; }
776
- .user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: var(--padding); }
777
  .user-card {
778
  background-color: var(--admin-card-bg);
779
  border-radius: var(--border-radius);
780
  padding: var(--padding);
781
- box-shadow: 0 4px 15px var(--admin-shadow-color);
782
  display: flex;
783
  flex-direction: column;
784
  align-items: center;
785
  text-align: center;
786
- border: 1px solid var(--admin-border-color);
787
- transition: transform 0.2s ease, box-shadow 0.2s ease;
788
- }
789
- .user-card:hover {
790
- transform: translateY(-4px);
791
- box-shadow: 0 8px 25px var(--admin-shadow-color);
792
  }
793
  .user-card img {
794
- width: 90px;
795
- height: 90px;
796
  border-radius: 50%;
797
- margin-bottom: 15px;
798
  object-fit: cover;
799
- border: 3px solid var(--admin-border-color);
800
- background-color: var(--admin-bg-color); /* Placeholder bg */
801
- }
802
- .user-card .name { font-weight: 700; font-size: 1.2em; margin-bottom: 5px; color: var(--admin-text-color); }
803
- .user-card .username { color: var(--admin-accent-color); margin-bottom: 10px; font-size: 0.95em; font-weight: 500; }
804
- .user-card .details { font-size: 0.9em; color: var(--admin-text-secondary-color); word-break: break-all; line-height: 1.5; }
805
- .user-card .timestamp { font-size: 0.8em; color: var(--admin-text-secondary-color); margin-top: 15px; font-style: italic; }
806
- .no-users { text-align: center; color: var(--admin-text-secondary-color); margin-top: 40px; font-size: 1.1em; }
 
 
 
 
 
 
 
807
  .alert {
808
- background-color: #f87171; /* Red */
809
- color: #fff;
810
- border-left: 6px solid #dc2626; /* Darker Red */
811
- margin-bottom: 25px;
812
- padding: 15px 20px;
813
- border-radius: 8px;
814
- text-align: center;
815
- font-weight: 600;
816
- box-shadow: 0 2px 5px var(--admin-shadow-color);
817
  }
818
- a { color: var(--admin-accent-color); text-decoration: none; }
819
- a:hover { text-decoration: underline; }
820
  </style>
821
  </head>
822
  <body>
823
- <div class="container">
824
- <h1>Панель Администратора - Посетители</h1>
825
- <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div>
826
-
827
- <div class="controls">
828
- <form method="POST" action="{{ url_for('backup_route') }}" style="display: inline;">
829
- <button type="submit" class="control-btn">Создать Резервную Копию</button>
830
- </form>
831
- <form method="GET" action="{{ url_for('download_route') }}" style="display: inline;">
832
- <button type="submit" class="control-btn download">Скачать Базу Данных</button>
833
- </form>
834
- <button class="control-btn" onclick="window.location.reload();">Обновить Список</button>
835
- </div>
 
 
 
 
 
 
 
 
 
 
836
 
837
- {% if users %}
838
- <div class="user-grid">
839
- {% for user in users|sort(attribute='visited_at', reverse=true) %}
840
- <div class="user-card">
841
- <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%234b5563%27/%3e%3ctext x=%2750%25%27 y=%2750%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%239ca3af%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar" loading="lazy">
842
- <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
843
- {% if user.username %}
844
- <div class="username"><a href="https://t.me/{{ user.username }}" target="_blank">@{{ user.username }}</a></div>
845
- {% else %}
846
- <div class="username">Нет username</div>
847
- {% endif %}
848
- <div class="details">
849
- ID: {{ user.id }} <br>
850
- Язык: {{ user.language_code or 'N/A' }} <br>
851
- Телефон: <span style="color: var(--admin-text-secondary-color); font-style: italic;">Недоступен</span>
852
- </div>
853
- <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
854
  </div>
855
- {% endfor %}
856
- </div>
857
- {% else %}
858
- <p class="no-users">Пока нет данных о посетителях.</p>
859
- {% endif %}
860
- </div>
 
861
  </body>
862
  </html>
863
  """
864
 
865
-
866
  # --- Flask Routes ---
867
 
868
  @app.route('/')
@@ -871,121 +796,141 @@ def index():
871
 
872
  @app.route('/verify', methods=['POST'])
873
  def verify_data():
874
- global visited_users
875
  try:
876
  data = request.get_json()
877
  init_data_str = data.get('initData')
878
  if not init_data_str:
879
- logging.warning("Verification request missing initData.")
880
  return jsonify({"status": "error", "message": "Missing initData"}), 400
881
 
 
882
  user_data_parsed, is_valid = verify_telegram_data(init_data_str)
883
 
884
  user_info_dict = {}
885
  if user_data_parsed and 'user' in user_data_parsed:
886
  try:
887
- # Decode JSON string within the 'user' field
888
  user_json_str = unquote(user_data_parsed['user'][0])
889
  user_info_dict = json.loads(user_json_str)
890
- except (KeyError, IndexError, json.JSONDecodeError, TypeError) as e:
891
- logging.error(f"Could not parse user JSON from initData: {e} - Data: {user_data_parsed.get('user')}")
892
- user_info_dict = {} # Ensure it's a dict even on error
 
893
 
894
  if is_valid:
895
  user_id = user_info_dict.get('id')
896
  if user_id:
897
  user_id_str = str(user_id) # Use string keys for JSON consistency
898
- now = time.time()
899
- update_data = {
 
 
 
 
 
 
 
 
900
  'id': user_id,
901
- 'first_name': user_info_dict.get('first_name'),
902
- 'last_name': user_info_dict.get('last_name'),
903
- 'username': user_info_dict.get('username'),
904
- 'photo_url': user_info_dict.get('photo_url'),
905
- 'language_code': user_info_dict.get('language_code'),
906
- 'visited_at': now,
907
- 'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S UTC') # Explicit UTC
908
- }
909
- # Update the global dictionary and save
910
- visited_users[user_id_str] = update_data
911
- save_users(visited_users) # Save after modification
912
- logging.info(f"User visit recorded/updated for ID: {user_id_str}")
 
 
 
913
 
914
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
915
  else:
916
- logging.warning(f"Verification failed for user ID: {user_info_dict.get('id', 'Unknown')}")
917
- return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
918
 
919
  except Exception as e:
920
- logging.exception("Critical error in /verify endpoint") # Log full traceback
921
  return jsonify({"status": "error", "message": "Internal server error"}), 500
922
 
 
923
  @app.route('/admin')
924
  def admin_panel():
925
- # WARNING: This route is unprotected! Add proper authentication/authorization for production.
926
- # Load fresh data for admin view, though 'visited_users' global should be up-to-date
927
- current_users = load_users()
928
- users_list = list(current_users.values())
929
- logging.info(f"Admin panel accessed. Displaying {len(users_list)} users.")
930
- return render_template_string(ADMIN_TEMPLATE, users=users_list)
931
-
932
- @app.route('/backup', methods=['POST'])
933
- def backup_route():
934
- # Manual backup trigger
935
- # WARNING: Unprotected route
936
- logging.info("Manual backup requested via /backup route.")
937
- if upload_db_to_hf():
938
- # Optionally add a success message (e.g., using flash)
939
- pass
940
  else:
941
- # Optionally add an error message
942
- pass
943
- return redirect(url_for('admin_panel')) # Redirect back to admin
944
-
945
- @app.route('/download', methods=['GET'])
946
- def download_route():
947
- # Manual download trigger
948
- # WARNING: Unprotected route
949
- global visited_users
950
- logging.info("Manual download requested via /download route.")
951
  if download_db_from_hf():
952
- visited_users = load_users() # Reload data after download
953
- # Optionally add a success message
954
  else:
955
- # Optionally add an error message
956
- pass
957
- return redirect(url_for('admin_panel')) # Redirect back to admin
958
 
 
 
 
 
 
 
 
 
 
959
 
960
- # --- Main Execution ---
961
 
 
962
  if __name__ == '__main__':
963
- # Initial check for HF tokens
964
- if not HF_TOKEN:
965
- logging.warning("!!! HF_TOKEN environment variable is not set. Uploads to Hugging Face Hub will be disabled.")
 
 
966
  if not HF_TOKEN_READ:
967
- logging.warning("!!! HF_TOKEN_READ environment variable is not set. Downloads from Hugging Face Hub will be disabled (falling back to local file).")
968
-
969
- # Start the periodic backup thread
970
- if HF_TOKEN: # Only start if upload is possible
971
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
972
- backup_thread.start()
973
- else:
974
- logging.warning("Periodic backup thread not started because HF_TOKEN is not set.")
975
 
976
 
977
- logging.warning("--- SECURITY WARNING ---")
978
- logging.warning("The /admin, /backup, /download routes are NOT protected by authentication.")
979
- logging.warning("Anyone knowing the URL can access visitor data and trigger actions.")
980
- logging.warning("Implement proper security (e.g., password protection, IP restriction) before deploying.")
981
- logging.warning("------------------------")
982
  logging.info(f"Starting Flask server on http://{HOST}:{PORT}")
983
- logging.info(f"Ensure this address is accessible and configured in BotFather for your Mini App.")
984
  logging.info(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
985
  logging.info(f"User data file: {DATA_FILE}")
986
  logging.info(f"Hugging Face Repo: {REPO_ID}")
987
 
988
- # Use Waitress or Gunicorn for production instead of app.run()
 
 
 
 
989
  # from waitress import serve
990
  # serve(app, host=HOST, port=PORT)
 
991
  app.run(host=HOST, port=PORT, debug=False) # debug=False for production
 
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,
75
  path_in_repo=DATA_FILE,
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)
 
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
  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">
174
  <head>
175
  <meta charset="UTF-8">
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>
 
359
  <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
360
  <span>Morshen Group</span>
361
  </div>
362
+ <a href="#" class="btn contact-link"><i class="icon-contact"></i>Связаться</a>
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
  <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
 
 
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).');
574
  }
575
 
 
576
  const contactButtons = document.querySelectorAll('.contact-link');
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
  });
584
 
 
585
  const modal = document.getElementById("saveModal");
586
  const saveCardBtn = document.getElementById("save-card-btn");
587
  const closeBtn = document.getElementById("modal-close-btn");
 
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', () => {
597
  modal.style.display = "none";
598
  });
599
 
600
+ window.addEventListener('click', (event) => {
601
+ if (event.target == modal) {
 
602
  modal.style.display = "none";
603
  }
604
  });
 
606
  console.error("Modal elements not found!");
607
  }
608
 
609
+ document.body.style.visibility = 'visible';
 
610
  }
611
 
 
612
  if (window.Telegram && window.Telegram.WebApp) {
613
  setupTelegram();
614
  } else {
 
615
  window.addEventListener('load', setupTelegram);
 
616
  setTimeout(() => {
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>
627
  </body>
628
  </html>
 
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
  """
790
 
 
791
  # --- Flask Routes ---
792
 
793
  @app.route('/')
 
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