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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +633 -473
app.py CHANGED
@@ -10,134 +10,130 @@ 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,
81
- path_in_repo=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
 
@@ -147,23 +143,19 @@ def verify_telegram_data(init_data_str):
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,180 +164,247 @@ TEMPLATE = """
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>
346
  <div class="container">
347
 
348
- <section class="morshen-group-intro">
349
  <div class="header">
350
  <div class="logo">
351
  <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
@@ -353,51 +412,53 @@ TEMPLATE = """
353
  </div>
354
  <a href="#" class="btn contact-link"><i class="icon-contact"></i>Связаться</a>
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>
@@ -408,19 +469,18 @@ TEMPLATE = """
408
 
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">
@@ -428,25 +488,27 @@ TEMPLATE = """
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>
@@ -463,6 +525,7 @@ TEMPLATE = """
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>
@@ -472,9 +535,36 @@ TEMPLATE = """
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.");
@@ -487,68 +577,62 @@ TEMPLATE = """
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).');
542
  }
543
 
 
544
  const contactButtons = document.querySelectorAll('.contact-link');
545
  contactButtons.forEach(button => {
546
  button.addEventListener('click', (e) => {
547
  e.preventDefault();
548
- tg.openTelegramLink('https://t.me/morshenkhan');
 
 
 
 
 
549
  });
550
  });
551
 
 
552
  const modal = document.getElementById("saveModal");
553
  const saveCardBtn = document.getElementById("save-card-btn");
554
  const closeBtn = document.getElementById("modal-close-btn");
@@ -556,9 +640,9 @@ TEMPLATE = """
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
 
@@ -566,8 +650,9 @@ TEMPLATE = """
566
  modal.style.display = "none";
567
  });
568
 
569
- window.addEventListener('click', (event) => {
570
- if (event.target == modal) {
 
571
  modal.style.display = "none";
572
  }
573
  });
@@ -575,197 +660,261 @@ TEMPLATE = """
575
  console.error("Modal elements not found!");
576
  }
577
 
578
- document.body.style.visibility = 'visible';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579
  }
580
 
581
- if (window.Telegram && window.Telegram.WebApp) {
582
- setupTelegram();
583
- } else {
584
- window.addEventListener('load', setupTelegram);
585
- setTimeout(() => {
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>
596
  </body>
597
  </html>
598
  """
599
 
 
600
  ADMIN_TEMPLATE = """
601
  <!DOCTYPE html>
602
  <html lang="ru">
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
  """
729
 
730
  # --- Flask Routes ---
731
-
732
  @app.route('/')
733
  def index():
734
  return render_template_string(TEMPLATE)
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'),
@@ -773,70 +922,81 @@ def verify_data():
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
 
 
 
 
 
 
 
 
 
 
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, HFValidationError
16
 
17
+ # --- Configuration ---
18
+ BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Replace with your actual bot token or set env var
19
  HOST = '0.0.0.0'
20
  PORT = 7860
21
+ USER_DATA_FILE = 'data.json'
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Hugging Face Settings for User Data
24
+ HF_USER_DATA_REPO_ID = "flpolprojects/teledata"
25
+ HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") # Needs write access to the repo
26
+ HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", HF_TOKEN_WRITE) # Can use write token if read token not set
27
 
28
+ # --- Flask App Initialization ---
29
  app = Flask(__name__)
30
 
31
+ # --- Logging Setup ---
32
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
33
 
34
+ # --- Hugging Face Interaction ---
35
+ def download_user_data_from_hf():
36
+ if not HF_TOKEN_READ or not HF_USER_DATA_REPO_ID:
37
+ logging.warning("Hugging Face read token or repo ID not configured. Skipping download.")
38
+ return
 
39
  try:
40
+ logging.info(f"Attempting to download {USER_DATA_FILE} from {HF_USER_DATA_REPO_ID}")
41
  hf_hub_download(
42
+ repo_id=HF_USER_DATA_REPO_ID,
43
+ filename=USER_DATA_FILE,
44
  repo_type="dataset",
45
  token=HF_TOKEN_READ,
46
  local_dir=".",
47
  local_dir_use_symlinks=False,
48
+ force_download=True, # Ensure we get the latest version
49
+ etag_timeout=60 # Extend timeout for potentially larger files
50
  )
51
+ logging.info(f"{USER_DATA_FILE} successfully downloaded from Hugging Face.")
 
52
  except RepositoryNotFoundError:
53
+ logging.warning(f"Repository {HF_USER_DATA_REPO_ID} not found on Hugging Face. Will create local file if needed.")
54
+ except HFValidationError as e:
55
+ logging.error(f"Hugging Face Validation Error during download (Check Token Permissions?): {e}")
56
  except Exception as e:
57
+ # Catch specific exceptions like hf_hub.utils._errors.HfHubHTTPError if possible
58
+ if "404" in str(e):
59
+ logging.warning(f"{USER_DATA_FILE} not found in repository {HF_USER_DATA_REPO_ID}. Will create local file if needed.")
60
  else:
61
+ logging.error(f"Error downloading {USER_DATA_FILE} from Hugging Face: {e}")
 
62
 
63
+ def upload_user_data_to_hf():
64
+ if not HF_TOKEN_WRITE or not HF_USER_DATA_REPO_ID:
65
+ logging.warning("Hugging Face write token or repo ID not configured. Skipping upload.")
66
  return False
67
+ if not os.path.exists(USER_DATA_FILE):
68
+ logging.warning(f"{USER_DATA_FILE} does not exist locally. Skipping upload.")
69
  return False
70
  try:
 
71
  api = HfApi()
72
  api.upload_file(
73
+ path_or_fileobj=USER_DATA_FILE,
74
+ path_in_repo=USER_DATA_FILE,
75
+ repo_id=HF_USER_DATA_REPO_ID,
76
  repo_type="dataset",
77
  token=HF_TOKEN_WRITE,
78
  commit_message=f"Update user data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
79
  )
80
+ logging.info(f"{USER_DATA_FILE} successfully uploaded to Hugging Face.")
81
  return True
82
+ except HFValidationError as e:
83
+ logging.error(f"Hugging Face Validation Error during upload (Check Token Permissions?): {e}")
84
+ return False
85
  except Exception as e:
86
+ logging.error(f"Error uploading {USER_DATA_FILE} to Hugging Face: {e}")
87
  return False
88
 
89
+ def periodic_user_data_backup():
90
+ while True:
91
+ time.sleep(3600) # Backup every hour
92
+ logging.info("Performing periodic backup of user data...")
93
+ upload_user_data_to_hf()
94
 
95
+ # --- User Data Handling ---
96
+ def load_user_data():
97
+ # Try to get the latest from HF first
98
+ # download_user_data_from_hf() # Removed to prevent download on every load, rely on initial download + uploads
99
  try:
100
+ with open(USER_DATA_FILE, 'r', encoding='utf-8') as f:
101
+ data = json.load(f)
102
+ if not isinstance(data, dict):
103
+ logging.warning(f"{USER_DATA_FILE} does not contain a dictionary. Resetting.")
104
+ return {}
105
+ return data
106
+ except FileNotFoundError:
107
+ logging.info(f"{USER_DATA_FILE} not found locally. Initializing empty data.")
108
+ return {}
 
 
109
  except json.JSONDecodeError:
110
+ logging.error(f"Error decoding JSON from {USER_DATA_FILE}. Returning empty data.")
111
  return {}
112
  except Exception as e:
113
+ logging.error(f"Error loading user data from {USER_DATA_FILE}: {e}")
114
  return {}
115
 
116
+ def save_user_data(data):
117
  try:
118
+ with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
119
+ json.dump(data, f, ensure_ascii=False, indent=4)
120
+ logging.info(f"User data saved locally to {USER_DATA_FILE}.")
121
+ # Attempt to upload immediately after saving locally
122
+ upload_user_data_to_hf()
123
  except Exception as e:
124
+ logging.error(f"Error saving user data to {USER_DATA_FILE}: {e}")
 
 
125
 
126
+ # --- Telegram Data Verification ---
127
  def verify_telegram_data(init_data_str):
128
  try:
129
  parsed_data = parse_qs(init_data_str)
130
  received_hash = parsed_data.pop('hash', [None])[0]
131
 
132
  if not received_hash:
 
133
  return None, False
134
 
135
  data_check_list = []
136
  for key, value in sorted(parsed_data.items()):
 
137
  data_check_list.append(f"{key}={value[0]}")
138
  data_check_string = "\n".join(data_check_list)
139
 
 
143
  if calculated_hash == received_hash:
144
  auth_date = int(parsed_data.get('auth_date', [0])[0])
145
  current_time = int(time.time())
146
+ if current_time - auth_date > 3600: # 1 hour validity
 
147
  logging.warning(f"Telegram InitData is older than 1 hour (Auth Date: {auth_date}, Current: {current_time}).")
 
 
148
  return parsed_data, True
149
  else:
150
+ logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}")
 
 
151
  return parsed_data, False
152
  except Exception as e:
153
  logging.error(f"Error verifying Telegram data: {e}")
154
  return None, False
155
 
156
+ # --- HTML Templates ---
157
 
158
+ # Main Application Template
159
  TEMPLATE = """
160
  <!DOCTYPE html>
161
  <html lang="ru">
 
164
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no">
165
  <title>Morshen Group</title>
166
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
167
+ <link rel="preconnect" href="https://fonts.googleapis.com">
168
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
169
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
170
  <style>
171
  :root {
172
+ --bg-gradient-start: #0f172a; /* Slate 900 */
173
+ --bg-gradient-end: #1e293b; /* Slate 800 */
174
+ --card-bg: #334155; /* Slate 700 */
175
+ --card-bg-hover: #475569; /* Slate 600 */
176
+ --text-primary: #f1f5f9; /* Slate 100 */
177
+ --text-secondary: #cbd5e1; /* Slate 300 */
178
+ --text-muted: #94a3b8; /* Slate 400 */
179
+ --accent-primary-start: #3b82f6; /* Blue 500 */
180
+ --accent-primary-end: #6366f1; /* Indigo 500 */
181
+ --accent-secondary-start: #10b981; /* Emerald 500 */
182
+ --accent-secondary-end: #22c55e; /* Green 500 */
183
  --tag-bg: rgba(255, 255, 255, 0.1);
184
+ --tag-text: #e2e8f0; /* Slate 200 */
185
+ --border-color: #475569; /* Slate 600 */
186
+ --shadow-color: rgba(0, 0, 0, 0.3);
187
+ --border-radius-sm: 6px;
188
+ --border-radius-md: 12px;
189
+ --border-radius-lg: 18px;
190
+ --padding-xs: 4px;
191
+ --padding-sm: 8px;
192
+ --padding-md: 16px;
193
+ --padding-lg: 24px;
194
+ --padding-xl: 32px;
195
+ --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
196
  }
197
  * { box-sizing: border-box; margin: 0; padding: 0; }
198
+ html {
199
+ background: linear-gradient(160deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
200
+ min-height: 100vh;
201
+ }
202
  body {
203
  font-family: var(--font-family);
204
+ background: linear-gradient(160deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
205
+ color: var(--text-primary);
206
+ padding: var(--padding-md);
207
+ padding-bottom: 120px; /* Space for fixed button */
208
  overscroll-behavior-y: none;
209
  -webkit-font-smoothing: antialiased;
210
  -moz-osx-font-smoothing: grayscale;
211
  visibility: hidden; /* Hide until ready */
212
+ line-height: 1.6;
213
+ }
214
+ .container {
215
+ max-width: 700px;
216
+ margin: 0 auto;
217
+ display: flex;
218
+ flex-direction: column;
219
+ gap: var(--padding-xl);
220
+ }
221
+ .header {
222
+ display: flex;
223
+ justify-content: space-between;
224
+ align-items: center;
225
+ margin-bottom: var(--padding-md);
226
+ padding: var(--padding-sm) 0;
227
  }
228
+ .logo { display: flex; align-items: center; gap: var(--padding-md); }
229
+ .logo img {
230
+ width: 50px;
231
+ height: 50px;
 
 
232
  border-radius: 50%;
 
233
  object-fit: cover;
234
+ border: 2px solid rgba(255, 255, 255, 0.1);
235
+ box-shadow: 0 4px 15px var(--shadow-color);
236
+ transition: transform 0.3s ease;
237
  }
238
+ .logo img:hover { transform: scale(1.1); }
239
+ .logo span { font-size: 1.6em; font-weight: 700; letter-spacing: -0.5px; }
240
  .btn {
241
  display: inline-flex; align-items: center; justify-content: center;
242
+ padding: 12px var(--padding-lg);
243
+ border-radius: var(--border-radius-md);
244
+ background: linear-gradient(90deg, var(--accent-primary-start), var(--accent-primary-end));
245
+ color: var(--text-primary);
246
+ text-decoration: none;
247
+ font-weight: 600;
248
+ border: none;
249
+ cursor: pointer;
250
+ transition: all 0.3s ease;
251
+ gap: var(--padding-sm);
252
+ font-size: 1em;
253
+ box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
254
+ }
255
+ .btn:hover { opacity: 0.9; box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4); transform: translateY(-2px); }
256
+ .btn-secondary {
257
+ background: var(--card-bg);
258
+ color: var(--accent-primary-start);
259
+ box-shadow: 0 2px 8px rgba(0,0,0, 0.2);
260
+ }
261
+ .btn-secondary:hover { background: var(--card-bg-hover); box-shadow: 0 4px 12px rgba(0,0,0, 0.3); }
262
+ .btn-cta {
263
+ background: linear-gradient(90deg, var(--accent-secondary-start), var(--accent-secondary-end));
264
+ box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
265
+ }
266
+ .btn-cta:hover {
267
+ box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
268
+ }
269
  .tag {
270
+ display: inline-block;
271
+ background: var(--tag-bg);
272
+ color: var(--tag-text);
273
+ padding: var(--padding-xs) var(--padding-sm);
274
+ border-radius: var(--border-radius-sm);
275
+ font-size: 0.8em;
276
+ font-weight: 500;
277
+ margin: var(--padding-xs) var(--padding-xs) var(--padding-xs) 0;
278
+ white-space: nowrap;
279
+ border: 1px solid rgba(255, 255, 255, 0.1);
280
  }
281
+ .tag i { margin-right: 4px; opacity: 0.8; color: var(--accent-secondary-start); }
282
  .section-card {
283
+ background-color: var(--card-bg);
284
+ border-radius: var(--border-radius-lg);
285
+ padding: var(--padding-lg);
286
+ border: 1px solid var(--border-color);
287
+ box-shadow: 0 8px 25px var(--shadow-color);
288
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
289
+ overflow: hidden; /* Ensure children don't overflow rounded corners */
290
+ }
291
+ .section-card:hover {
292
+ transform: translateY(-3px);
293
+ box-shadow: 0 12px 30px var(--shadow-color);
294
+ }
295
+ .section-title {
296
+ font-size: 2em;
297
+ font-weight: 800;
298
+ margin-bottom: var(--padding-sm);
299
+ line-height: 1.2;
300
+ letter-spacing: -0.8px;
301
+ background: linear-gradient(90deg, var(--text-primary), var(--text-secondary));
302
+ -webkit-background-clip: text;
303
+ -webkit-text-fill-color: transparent;
304
+ }
305
+ .section-subtitle { font-size: 1.1em; font-weight: 500; color: var(--text-secondary); margin-bottom: var(--padding-md); }
306
+ .description { font-size: 1em; line-height: 1.7; color: var(--text-secondary); margin-bottom: var(--padding-lg); }
307
+ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: var(--padding-md); margin-top: var(--padding-lg); }
308
+ .stat-item { background-color: rgba(255, 255, 255, 0.05); padding: var(--padding-md); border-radius: var(--border-radius-md); text-align: center; border: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.3s ease;}
309
+ .stat-item:hover { background-color: rgba(255, 255, 255, 0.1); }
310
+ .stat-value { font-size: 1.8em; font-weight: 700; display: block; color: var(--text-primary); }
311
+ .stat-value i { font-size: 0.8em; margin-right: 4px; opacity: 0.7; }
312
+ .stat-label { font-size: 0.85em; color: var(--text-muted); display: block; margin-top: var(--padding-xs); text-transform: uppercase; letter-spacing: 0.5px; }
313
+ .list-item { background-color: rgba(255, 255, 255, 0.05); 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 rgba(255, 255, 255, 0.08); transition: background-color 0.3s ease; }
314
+ .list-item:hover { background-color: rgba(255, 255, 255, 0.1); }
315
+ .list-item i { font-size: 1.3em; color: var(--accent-primary-start); opacity: 0.9; }
316
+ .footer-greeting { text-align: center; color: var(--text-muted); font-size: 0.9em; margin-top: var(--padding-xl); }
317
  .save-card-button {
318
  position: fixed;
319
  bottom: 20px;
320
  left: 50%;
321
  transform: translateX(-50%);
322
+ padding: 14px 28px;
323
+ border-radius: 30px;
324
+ background: linear-gradient(90deg, var(--accent-secondary-start), var(--accent-secondary-end));
325
+ color: var(--text-primary);
326
  text-decoration: none;
327
+ font-weight: 700;
328
  border: none;
329
  cursor: pointer;
330
+ transition: all 0.3s ease;
331
  z-index: 1000;
332
+ box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
333
+ font-size: 1.05em;
334
  display: flex;
335
  align-items: center;
336
+ gap: 10px;
337
  }
338
+ .save-card-button:hover { opacity: 0.9; transform: translateX(-50%) scale(1.05); box-shadow: 0 8px 25px rgba(16, 185, 129, 0.5); }
339
 
340
+ /* Modal Styles (Enhanced) */
341
  .modal {
342
+ display: none; position: fixed; z-index: 1001;
343
+ left: 0; top: 0; width: 100%; height: 100%;
344
+ overflow: auto; background-color: rgba(15, 23, 42, 0.8); /* Slate 900 with opacity */
345
+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
346
+ display: flex; align-items: center; justify-content: center;
347
+ animation: fadeIn 0.3s ease-out;
 
 
 
 
348
  }
349
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
350
  .modal-content {
351
+ background-color: var(--card-bg); color: var(--text-primary);
352
+ margin: auto; padding: var(--padding-xl);
353
+ border: 1px solid var(--border-color);
354
+ width: 85%; max-width: 450px;
355
+ border-radius: var(--border-radius-lg);
356
+ text-align: center; position: relative;
357
+ box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5);
358
+ animation: scaleUp 0.3s ease-out;
 
 
 
359
  }
360
+ @keyframes scaleUp { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
361
  .modal-close {
362
+ color: var(--text-muted); position: absolute;
363
+ top: 15px; right: 20px; font-size: 28px;
364
+ font-weight: bold; cursor: pointer; line-height: 1;
365
+ transition: color 0.3s ease, transform 0.3s ease;
 
 
 
 
366
  }
367
+ .modal-close:hover { color: var(--text-primary); transform: rotate(90deg); }
368
+ .modal-text { font-size: 1.15em; line-height: 1.6; margin-bottom: var(--padding-md); word-wrap: break-word; }
369
+ .modal-text b { color: var(--accent-secondary-start); font-weight: 700; }
370
+ .modal-instruction { font-size: 0.95em; color: var(--text-muted); margin-top: var(--padding-sm); }
371
+
372
+ /* Icons */
373
+ [class^="icon-"]::before {
374
+ display: inline-block;
375
+ font-style: normal;
376
+ font-variant: normal;
377
+ text-rendering: auto;
378
+ -webkit-font-smoothing: antialiased;
379
+ margin-right: 8px;
380
+ opacity: 0.9;
381
+ font-size: 1.1em; /* Slightly larger icons */
382
  }
383
+ .icon-save::before { content: '💾'; color: #a7f3d0; } /* Emerald 200 */
384
+ .icon-web::before { content: '🌐'; color: #93c5fd; } /* Blue 300 */
385
+ .icon-mobile::before { content: '📱'; color: #a5b4fc; } /* Indigo 300 */
386
+ .icon-code::before { content: '💻'; color: #fde047; } /* Yellow 400 */
387
+ .icon-ai::before { content: '🧠'; color: #f9a8d4; } /* Pink 300 */
388
+ .icon-quantum::before { content: '⚛️'; color: #d8b4fe; } /* Purple 300 */
389
+ .icon-business::before { content: '💼'; color: #fdba74; } /* Orange 300 */
390
+ .icon-speed::before { content: '⚡️'; color: #facc15; } /* Amber 400 */
391
+ .icon-complexity::before { content: '🧩'; color: #a7f3d0; } /* Emerald 200 */
392
+ .icon-experience::before { content: '⏳'; color: #fca5a5; } /* Red 300 */
393
+ .icon-clients::before { content: '👥'; color: #67e8f9; } /* Cyan 300 */
394
+ .icon-market::before { content: '📈'; color: #86efac; } /* Green 300 */
395
+ .icon-location::before { content: '📍'; color: #f87171; } /* Red 400 */
396
+ .icon-global::before { content: '🌍'; color: #60a5fa; } /* Blue 400 */
397
+ .icon-innovation::before { content: '💡'; color: #fcd34d; } /* Amber 300 */
398
+ .icon-contact::before { content: '💬'; color: #5eead4; } /* Teal 300 */
399
+ .icon-link::before { content: '🔗'; color: #9ca3af; } /* Gray 400 */
400
+ .icon-leader::before { content: '🏆'; color: #fde047; } /* Yellow 400 */
401
+ .icon-company::before { content: '🏢'; color: #a5b4fc; } /* Indigo 300 */
 
 
 
 
 
 
 
 
 
 
 
 
402
  </style>
403
  </head>
404
  <body>
405
  <div class="container">
406
 
407
+ <section class="morshen-group-intro section-card" style="border-top: 4px solid var(--accent-primary-start);">
408
  <div class="header">
409
  <div class="logo">
410
  <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo">
 
412
  </div>
413
  <a href="#" class="btn contact-link"><i class="icon-contact"></i>Связаться</a>
414
  </div>
415
+ <div style="margin: var(--padding-sm) 0 var(--padding-md) 0;">
416
  <span class="tag"><i class="icon-leader"></i>Лидер инноваций 2025</span>
417
+ <span class="tag"><i class="icon-global"></i>Международный</span>
418
  </div>
419
+ <h1 class="section-title" style="font-size: 2.4em;">Международный IT холдинг</h1>
420
  <p class="description">
421
  Объединяем передовые технологические компании для создания инновационных
422
+ решений мирового уровня, формируя цифровое будущее.
423
  </p>
424
+ <a href="#" class="btn btn-cta contact-link" style="width: 100%; margin-top: var(--padding-md); padding: 14px 0;">
425
  <i class="icon-contact"></i>Связаться с нами
426
  </a>
427
  </section>
428
 
429
  <section class="ecosystem-header">
430
+ <div style="text-align: center; margin-bottom: var(--padding-md);">
431
+ <span class="tag"><i class="icon-company"></i>Наши компании</span>
432
+ </div>
433
+ <h2 class="section-title" style="text-align: center;">Экосистема Инноваций</h2>
434
+ <p class="description" style="text-align: center; max-width: 550px; margin-left: auto; margin-right: auto;">
435
  В состав холдинга входят компании, специализирующиеся на различных
436
+ направлениях передовых технологий, от ИИ до веб-разработки.
437
  </p>
438
  </section>
439
 
440
  <section class="section-card">
441
  <div class="logo">
442
+ <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo" style="width: 45px; height: 45px;">
443
+ <span style="font-size: 1.5em; font-weight: 700;">Morshen Alpha</span>
444
  </div>
445
+ <div style="margin: var(--padding-md) 0;">
446
  <span class="tag"><i class="icon-ai"></i>Искусственный интеллект</span>
447
  <span class="tag"><i class="icon-quantum"></i>Квантовые технологии</span>
448
  <span class="tag"><i class="icon-business"></i>Бизнес-решения</span>
449
  </div>
450
  <p class="description">
451
+ Флагманская R&D компания холдинга. Специализируемся на разработке прорывных
452
+ бизнес-решений, исследованиях в сфере ИИ и квантовых технологий. Наши инновации формируют будущее индустрии.
 
453
  </p>
454
  <div class="stats-grid">
455
  <div class="stat-item">
456
  <span class="stat-value"><i class="icon-global"></i> 3</span>
457
+ <span class="stat-label">Страны</span>
458
  </div>
459
  <div class="stat-item">
460
+ <span class="stat-value"><i class="icon-clients"></i> 3K+</span>
461
+ <span class="stat-label">Клиенты</span>
462
  </div>
463
  <div class="stat-item">
464
  <span class="stat-value"><i class="icon-market"></i> 5</span>
 
469
 
470
  <section class="section-card">
471
  <div class="logo">
472
+ <img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 45px; height: 45px;">
473
+ <span style="font-size: 1.5em; font-weight: 700;">Holmgard</span>
474
  </div>
475
+ <div style="margin: var(--padding-md) 0;">
476
  <span class="tag"><i class="icon-web"></i>Веб-разработка</span>
477
  <span class="tag"><i class="icon-mobile"></i>Мобильные приложения</span>
478
+ <span class="tag"><i class="icon-code"></i>ПО на заказ</span>
479
  </div>
480
  <p class="description">
481
+ Инновационная студия разработки, создающая высокотехнологичные цифровые продукты
482
+ для бизнеса любого масштаба. Сайты, мобильные приложения и ПО с использованием
483
+ передовых технологий и гибких методологий.
 
484
  </p>
485
  <div class="stats-grid">
486
  <div class="stat-item">
 
488
  <span class="stat-label">Лет опыта</span>
489
  </div>
490
  <div class="stat-item">
491
+ <span class="stat-value"><i class="icon-complexity"></i> ∞</span>
492
+ <span class="stat-label">Сложность</span>
493
  </div>
494
  <div class="stat-item">
495
  <span class="stat-value"><i class="icon-speed"></i></span>
496
+ <span class="stat-label">Скорость</span>
497
  </div>
498
  </div>
499
+ <div style="display: flex; gap: var(--padding-md); margin-top: var(--padding-lg); flex-wrap: wrap;">
500
+ <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon-link"></i>Веб-сайт</a>
501
  <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon-contact"></i>Связаться</a>
502
  </div>
503
  </section>
504
 
505
  <section>
506
+ <div style="text-align: center; margin-bottom: var(--padding-md);">
507
+ <span class="tag"><i class="icon-global"></i>Глобальное Присутствие</span>
508
+ </div>
509
+ <h2 class="section-title" style="text-align: center;">География Присутствия</h2>
510
+ <p class="description" style="text-align: center;">Наши инновационные решения активно используются в странах:</p>
511
+ <div style="display: flex; flex-direction: column; gap: var(--padding-sm);">
512
  <div class="list-item"><i class="icon-location"></i>Узбекистан</div>
513
  <div class="list-item"><i class="icon-location"></i>Казахстан</div>
514
  <div class="list-item"><i class="icon-location"></i>Кыргызстан</div>
 
525
  <i class="icon-save"></i>Сохранить визитку
526
  </button>
527
 
528
+ <!-- The Modal -->
529
  <div id="saveModal" class="modal">
530
  <div class="modal-content">
531
  <span class="modal-close" id="modal-close-btn">×</span>
 
535
  </div>
536
  </div>
537
 
538
+
539
  <script>
540
  const tg = window.Telegram.WebApp;
541
 
542
+ function applyTheme(themeParams) {
543
+ // Example of adapting to TG theme (can be more complex)
544
+ const isDark = themeParams.bg_color && themeParams.bg_color.startsWith('#') && parseInt(themeParams.bg_color.substring(1), 16) < parseInt('888888', 16);
545
+
546
+ if (isDark) {
547
+ // Use default dark theme or potentially adjust CSS vars based on themeParams
548
+ document.body.classList.add('tg-dark'); // Add a class to target specific styles
549
+ } else {
550
+ // Use default light theme or adjust
551
+ document.body.classList.remove('tg-dark');
552
+ }
553
+
554
+ // Apply specific colors if available (more granular control)
555
+ if (themeParams.bg_color) document.documentElement.style.setProperty('--tg-bg-color', themeParams.bg_color);
556
+ if (themeParams.text_color) document.documentElement.style.setProperty('--tg-text-color', themeParams.text_color);
557
+ if (themeParams.button_color) {
558
+ document.documentElement.style.setProperty('--tg-button-color', themeParams.button_color);
559
+ // Example: Update accent gradient if needed based on button color
560
+ // document.documentElement.style.setProperty('--accent-primary-start', themeParams.button_color);
561
+ }
562
+ if (themeParams.button_text_color) document.documentElement.style.setProperty('--tg-button-text-color', themeParams.button_text_color);
563
+ if (themeParams.secondary_bg_color) document.documentElement.style.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color);
564
+
565
+ console.log("Applied Telegram Theme:", themeParams);
566
+ }
567
+
568
  function setupTelegram() {
569
  if (!tg || !tg.initData) {
570
  console.error("Telegram WebApp script not loaded or initData is missing.");
 
577
  tg.ready();
578
  tg.expand();
579
 
580
+ // Apply Theme
581
+ applyTheme(tg.themeParams || {});
582
+ tg.onEvent('themeChanged', () => applyTheme(tg.themeParams));
583
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
584
 
585
+ // Send initData for verification and user logging
586
  fetch('/verify', {
587
  method: 'POST',
588
+ headers: { 'Content-Type': 'application/json', },
 
 
589
  body: JSON.stringify({ initData: tg.initData }),
590
  })
591
  .then(response => response.json())
592
  .then(data => {
593
  if (data.status === 'ok' && data.verified) {
594
+ console.log('Backend verification successful.', data.user);
595
  } else {
596
  console.warn('Backend verification failed:', data.message);
597
+ // Optional: Show visual warning in the UI
598
+ // const greetingElement = document.getElementById('greeting');
599
+ // if(greetingElement) greetingElement.innerHTML += ' <span style="color: yellow;">(верификация не пройдена)</span>';
600
  }
601
  })
602
  .catch(error => {
603
  console.error('Error sending initData for verification:', error);
 
604
  });
605
 
606
+
607
+ // User Greeting (using unsafe data for speed)
608
  const user = tg.initDataUnsafe?.user;
609
  const greetingElement = document.getElementById('greeting');
610
  if (user) {
611
+ const firstName = user.first_name || '';
612
+ const lastName = user.last_name || '';
613
+ const username = user.username ? `@${user.username}` : '';
614
+ const name = `${firstName} ${lastName}`.trim() || username || 'Гость';
615
  greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
616
  } else {
617
  greetingElement.textContent = 'Добро пожаловать!';
618
  console.warn('Telegram User data not available (initDataUnsafe.user is empty).');
619
  }
620
 
621
+ // Contact Links
622
  const contactButtons = document.querySelectorAll('.contact-link');
623
  contactButtons.forEach(button => {
624
  button.addEventListener('click', (e) => {
625
  e.preventDefault();
626
+ try {
627
+ tg.openTelegramLink('https://t.me/morshenkhan'); // Replace with actual contact username
628
+ } catch (err) {
629
+ console.error("Failed to open TG link:", err);
630
+ window.open('https://t.me/morshenkhan', '_blank'); // Fallback
631
+ }
632
  });
633
  });
634
 
635
+ // Modal Setup
636
  const modal = document.getElementById("saveModal");
637
  const saveCardBtn = document.getElementById("save-card-btn");
638
  const closeBtn = document.getElementById("modal-close-btn");
 
640
  if (saveCardBtn && modal && closeBtn) {
641
  saveCardBtn.addEventListener('click', (e) => {
642
  e.preventDefault();
643
+ modal.style.display = "flex"; // Use flex for centering
644
  if (tg.HapticFeedback) {
645
+ tg.HapticFeedback.impactOccurred('light');
646
  }
647
  });
648
 
 
650
  modal.style.display = "none";
651
  });
652
 
653
+ // Close modal if clicked outside the content (on the backdrop)
654
+ modal.addEventListener('click', (event) => {
655
+ if (event.target === modal) { // Check if the click is directly on the modal backdrop
656
  modal.style.display = "none";
657
  }
658
  });
 
660
  console.error("Modal elements not found!");
661
  }
662
 
663
+ document.body.style.visibility = 'visible'; // Make body visible now
664
+ }
665
+
666
+ // Initialize Telegram WebApp robustly
667
+ try {
668
+ if (tg && tg.initData) {
669
+ setupTelegram();
670
+ } else {
671
+ console.log("Telegram WebApp object not immediately available, waiting for window.load");
672
+ window.addEventListener('load', setupTelegram);
673
+ }
674
+ } catch (e) {
675
+ console.error("Error during initial Telegram WebApp setup:", e);
676
+ const greetingElement = document.getElementById('greeting');
677
+ if(greetingElement) greetingElement.textContent = 'Ошибка инициализации Telegram.';
678
+ document.body.style.visibility = 'visible'; // Show body anyway on error
679
  }
680
 
681
+
682
+ // Fallback timeout in case 'load' doesn't fire or TG script fails silently
683
+ setTimeout(() => {
684
+ if (document.body.style.visibility !== 'visible') {
685
+ console.error("Telegram WebApp script fallback timeout triggered. Forcing visibility.");
686
+ const greetingElement = document.getElementById('greeting');
687
+ if(greetingElement && greetingElement.textContent.includes('Загрузка')) {
688
+ greetingElement.textContent = 'Ошибка загрузки Telegram.';
 
 
689
  }
690
+ document.body.style.visibility = 'visible';
691
+ // Attempt setup one last time if it failed
692
+ if (typeof window.Telegram !== 'undefined' && typeof window.Telegram.WebApp !== 'undefined') {
693
+ setupTelegram();
694
+ }
695
+ }
696
+ }, 4000); // Increased timeout
697
 
698
  </script>
699
  </body>
700
  </html>
701
  """
702
 
703
+ # Admin Panel Template
704
  ADMIN_TEMPLATE = """
705
  <!DOCTYPE html>
706
  <html lang="ru">
707
  <head>
708
  <meta charset="UTF-8">
709
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
710
+ <title>Admin - Посетители</title>
711
+ <link rel="preconnect" href="https://fonts.googleapis.com">
712
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
713
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
714
  <style>
715
+ :root {
716
+ --admin-bg: #f8fafc; /* Slate 50 */
717
+ --admin-text: #1e293b; /* Slate 800 */
718
+ --admin-card-bg: #ffffff;
719
+ --admin-border: #e2e8f0; /* Slate 200 */
720
+ --admin-shadow: rgba(0, 0, 0, 0.05);
721
+ --admin-accent: #3b82f6; /* Blue 500 */
722
+ --admin-text-muted: #64748b; /* Slate 500 */
723
+ --admin-danger-bg: #fee2e2; /* Red 100 */
724
+ --admin-danger-text: #b91c1c; /* Red 700 */
725
+ --admin-danger-border: #ef4444; /* Red 500 */
726
+ --border-radius-md: 8px;
727
+ --padding-md: 16px;
728
+ --padding-lg: 24px;
729
+ --font-family: 'Inter', sans-serif;
730
+ }
731
+ body {
732
+ font-family: var(--font-family);
733
+ background-color: var(--admin-bg);
734
+ color: var(--admin-text);
735
+ margin: 0;
736
+ padding: var(--padding-lg);
737
+ line-height: 1.6;
738
+ }
739
+ h1 {
740
+ text-align: center;
741
+ color: var(--admin-text);
742
+ font-weight: 700;
743
+ margin-bottom: var(--padding-lg);
744
+ }
745
+ .user-grid {
746
+ display: grid;
747
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
748
+ gap: var(--padding-lg);
749
+ margin-top: var(--padding-lg);
750
+ }
751
+ .user-card {
752
+ background-color: var(--admin-card-bg);
753
+ border-radius: var(--border-radius-md);
754
+ padding: var(--padding-lg);
755
+ box-shadow: 0 4px 10px var(--admin-shadow);
756
+ border: 1px solid var(--admin-border);
757
+ display: flex;
758
+ flex-direction: column;
759
+ align-items: center;
760
+ text-align: center;
761
+ transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
762
+ }
763
+ .user-card:hover {
764
+ transform: translateY(-3px);
765
+ box-shadow: 0 6px 15px rgba(0,0,0,0.08);
766
+ }
767
+ .user-card img {
768
+ width: 80px;
769
+ height: 80px;
770
+ border-radius: 50%;
771
+ margin-bottom: var(--padding-md);
772
+ object-fit: cover;
773
+ border: 3px solid var(--admin-border);
774
+ background-color: #f1f5f9; /* Placeholder bg */
775
+ }
776
+ .user-card .name {
777
+ font-weight: 600;
778
+ font-size: 1.15em;
779
+ margin-bottom: 4px;
780
+ color: var(--admin-text);
781
+ }
782
+ .user-card .username {
783
+ color: var(--admin-accent);
784
+ margin-bottom: var(--padding-md);
785
+ font-size: 0.95em;
786
+ font-weight: 500;
787
+ }
788
+ .user-card .details {
789
+ font-size: 0.9em;
790
+ color: var(--admin-text-muted);
791
+ word-break: break-word; /* Ensure long IDs don't overflow */
792
+ width: 100%;
793
+ line-height: 1.5;
794
+ }
795
+ .user-card .details span { display: block; margin-bottom: 4px; }
796
+ .user-card .details strong { color: #475569; } /* Slate 600 */
797
+ .user-card .timestamp {
798
+ font-size: 0.8em;
799
+ color: #94a3b8; /* Slate 400 */
800
+ margin-top: var(--padding-md);
801
+ }
802
+ .no-users {
803
+ text-align: center;
804
+ color: var(--admin-text-muted);
805
+ margin-top: 40px;
806
+ font-size: 1.1em;
807
+ }
808
+ .alert {
809
+ background-color: var(--admin-danger-bg);
810
+ border-left: 5px solid var(--admin-danger-border);
811
+ margin-bottom: var(--padding-lg);
812
+ padding: var(--padding-md);
813
+ color: var(--admin-danger-text);
814
+ border-radius: var(--border-radius-md);
815
+ text-align: center;
816
+ font-weight: 500;
817
+ }
818
+ .total-users {
819
+ text-align: center;
820
+ font-size: 1.1em;
821
+ color: var(--admin-text-muted);
822
+ margin-bottom: var(--padding-lg);
823
+ }
824
+ .button-container {
825
+ text-align: center;
826
+ margin-bottom: 20px;
827
+ }
828
+ .button-container button {
829
+ padding: 10px 20px;
830
+ font-size: 1em;
831
+ cursor: pointer;
832
+ border: none;
833
+ border-radius: 6px;
834
+ background-color: var(--admin-accent);
835
+ color: white;
836
+ transition: background-color 0.3s ease;
837
+ }
838
+ .button-container button:hover {
839
+ background-color: #2563eb; /* Darker blue */
840
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841
  </style>
842
  </head>
843
  <body>
844
+ <h1>Панель Администратора - Посетители</h1>
845
+ <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div>
846
+
847
+ <div class="button-container">
848
+ <form method="POST" action="{{ url_for('force_backup') }}" style="display: inline;">
849
+ <button type="submit">Принудительно Загрузить на HF</button>
850
+ </form>
851
+ <form method="POST" action="{{ url_for('force_download') }}" style="display: inline; margin-left: 10px;">
852
+ <button type="submit" style="background-color: #059669;">Принудительно Скачать с HF</button>
853
+ </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  </div>
855
 
856
+
857
+ {% if users %}
858
+ <p class="total-users">Всего уникальных посетителей: {{ users|length }}</p>
859
+ <div class="user-grid">
860
+ {% for user_id, user in users.items()|sort(attribute='1.visited_at', reverse=true) %}
861
+ <div class="user-card">
862
+ <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%23e2e8f0%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=%27Inter, sans-serif%27 fill=%27%2394a3b8%27%3e{{ (user.first_name or '?')[0]|upper }}{{ (user.last_name or '?')[0]|upper if user.last_name }}%3c/text%3e%3c/svg%3e' }}" alt="User Avatar">
863
+ <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
864
+ {% if user.username %}
865
+ <div class="username">@{{ user.username }}</div>
866
+ {% else %}
867
+ <div class="username" style="opacity: 0.5;">(нет username)</div>
868
+ {% endif %}
869
+ <div class="details">
870
+ <span><strong>ID:</strong> {{ user.id }}</span>
871
+ <span><strong>Язык:</strong> {{ user.language_code or 'N/A' }}</span>
872
+ <span><strong>Телефон:</strong> <span style="color: #f87171;">Недоступен</span></span>
873
+ </div>
874
+ <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
875
+ </div>
876
+ {% endfor %}
877
+ </div>
878
+ {% else %}
879
+ <p class="no-users">Пока нет данных о посетителях.</p>
880
+ {% endif %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
881
  </body>
882
  </html>
883
  """
884
 
885
  # --- Flask Routes ---
 
886
  @app.route('/')
887
  def index():
888
  return render_template_string(TEMPLATE)
889
 
890
  @app.route('/verify', methods=['POST'])
891
  def verify_data():
 
892
  try:
893
  data = request.get_json()
894
  init_data_str = data.get('initData')
895
  if not init_data_str:
896
+ logging.warning("Verification request missing initData.")
897
  return jsonify({"status": "error", "message": "Missing initData"}), 400
898
 
899
+ user_data_parsed, is_valid = verify_telegram_data(init_data_str)
 
 
900
 
901
+ user_info_dict = {}
902
+ if user_data_parsed and 'user' in user_data_parsed:
903
  try:
904
+ user_json_str = unquote(user_data_parsed['user'][0])
 
905
  user_info_dict = json.loads(user_json_str)
906
  except Exception as e:
907
  logging.error(f"Could not parse user JSON from initData: {e}")
908
+ user_info_dict = {}
 
 
909
 
910
  if is_valid:
911
+ user_id = user_info_dict.get('id')
912
  if user_id:
913
+ user_id_str = str(user_id) # Use string keys for JSON consistency
914
+ visited_users = load_user_data() # Load current data
915
+
916
  now = time.time()
917
+ user_record = {
 
 
918
  'id': user_id,
919
  'first_name': user_info_dict.get('first_name'),
920
  'last_name': user_info_dict.get('last_name'),
 
922
  'photo_url': user_info_dict.get('photo_url'),
923
  'language_code': user_info_dict.get('language_code'),
924
  'visited_at': now,
925
+ 'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
926
  }
927
+
928
+ # Update existing record or add new one
929
+ visited_users[user_id_str] = user_record
930
+ logging.info(f"User visit recorded/updated for ID: {user_id_str}")
931
+
932
+ save_user_data(visited_users) # Save updated data locally and trigger HF upload
933
 
934
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
935
  else:
936
+ logging.warning(f"Verification failed for potential user: {user_info_dict.get('id')}")
937
  return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
938
 
939
  except Exception as e:
940
+ logging.exception("Critical error in /verify endpoint") # Log full traceback
941
  return jsonify({"status": "error", "message": "Internal server error"}), 500
942
 
943
  @app.route('/admin')
944
  def admin_panel():
945
+ # WARNING: This route is unprotected! Add proper authentication/authorization.
946
+ users_data = load_user_data()
947
+ return render_template_string(ADMIN_TEMPLATE, users=users_data)
948
+
949
+ @app.route('/force_backup', methods=['POST'])
950
+ def force_backup():
951
+ # WARNING: Unprotected route
952
+ logging.info("Admin triggered force backup to Hugging Face.")
953
+ success = upload_user_data_to_hf()
954
+ # Redirect back to admin panel or show a message
955
+ # For now, just redirecting. Add flash messages for better UX.
956
+ return redirect(url_for('admin_panel'))
957
+
958
+ @app.route('/force_download', methods=['POST'])
959
+ def force_download():
960
+ # WARNING: Unprotected route
961
+ logging.info("Admin triggered force download from Hugging Face.")
962
+ download_user_data_from_hf()
963
+ # Redirect back to admin panel
964
+ return redirect(url_for('admin_panel'))
 
 
 
965
 
966
 
967
  # --- Main Execution ---
 
968
  if __name__ == '__main__':
969
+ if not BOT_TOKEN or ':' not in BOT_TOKEN:
970
+ logging.error("FATAL: BOT_TOKEN is not set or invalid.")
971
+ exit(1)
972
+ if not HF_TOKEN_WRITE:
973
+ logging.warning("HF_TOKEN_WRITE is not set. User data upload to Hugging Face will be disabled.")
974
+ if not HF_TOKEN_READ:
975
+ logging.warning("HF_TOKEN_READ is not set. Will try to use HF_TOKEN_WRITE for downloads if available.")
976
+
977
+ # Initial download of user data when the app starts
978
+ logging.info("Attempting initial download of user data...")
979
+ download_user_data_from_hf()
980
+
981
+ # Start the periodic backup thread
982
+ if HF_TOKEN_WRITE and HF_USER_DATA_REPO_ID:
983
+ backup_thread = threading.Thread(target=periodic_user_data_backup, daemon=True)
984
+ backup_thread.start()
985
+ logging.info("Periodic user data backup thread started.")
986
  else:
987
+ logging.warning("Periodic backup disabled due to missing HF configuration.")
988
+
989
+
990
+ logging.info(f"--- SECURITY WARNING ---")
991
+ logging.info(f"The /admin, /force_backup, /force_download routes are NOT protected.")
992
+ logging.info(f"Implement proper security (e.g., password, IP restriction) before production.")
993
+ logging.info(f"------------------------")
994
+ logging.info(f"Starting Flask server on http://{HOST}:{PORT}")
995
+ logging.info(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
996
+ logging.info(f"User data file: {USER_DATA_FILE}")
997
+ logging.info(f"User data HF Repo: {HF_USER_DATA_REPO_ID}")
998
+
999
+ # Use a production-ready server like Waitress or Gunicorn instead of app.run() for deployment
1000
+ # from waitress import serve
1001
+ # serve(app, host=HOST, port=PORT)
1002
+ app.run(host=HOST, port=PORT, debug=False) # debug=False for production