Aleksmorshen commited on
Commit
cd297af
·
verified ·
1 Parent(s): dcb96db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -397
app.py CHANGED
@@ -14,7 +14,7 @@ import threading
14
  from huggingface_hub import HfApi, hf_hub_download
15
  from huggingface_hub.utils import RepositoryNotFoundError
16
  from pytonapi import Tonapi
17
-
18
 
19
  BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvtTVsqEJVG5SYK5hUlc_Ewo")
20
  HOST = '0.0.0.0'
@@ -26,7 +26,7 @@ HF_DATA_FILE_PATH = "data.json"
26
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
27
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
28
 
29
- TONAPI_KEY = os.getenv("TONAPI_KEY")
30
 
31
  app = Flask(__name__)
32
  logging.basicConfig(level=logging.INFO)
@@ -35,15 +35,12 @@ app.secret_key = os.urandom(24)
35
  _data_lock = threading.Lock()
36
  visitor_data_cache = {}
37
 
38
- tonapi = None
39
- if TONAPI_KEY:
40
- try:
41
- tonapi = Tonapi(api_key=TONAPI_KEY)
42
- logging.info("TONAPI initialized.")
43
- except Exception as e:
44
- logging.error(f"Failed to initialize TONAPI: {e}")
45
- else:
46
- logging.warning("TONAPI_KEY not set. TON wallet functionality will be limited.")
47
 
48
 
49
  def download_data_from_hf():
@@ -98,14 +95,12 @@ def load_visitor_data():
98
  visitor_data_cache = {}
99
  return visitor_data_cache
100
 
101
- def save_visitor_data(data_entry):
102
  with _data_lock:
103
  try:
104
- current_data = visitor_data_cache.copy()
105
- current_data.update(data_entry)
106
- visitor_data_cache.update(data_entry)
107
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
108
- json.dump(current_data, f, ensure_ascii=False, indent=4)
109
  logging.info(f"Visitor data successfully saved to {DATA_FILE}.")
110
  upload_data_to_hf_async()
111
  except Exception as e:
@@ -190,7 +185,6 @@ TEMPLATE = """
190
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
191
  <title>Morshen Group</title>
192
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
193
- <script src="https://unpkg.com/@tonconnect/sdk@2.0.0/dist/tonconnect-sdk.min.js"></script>
194
  <link rel="preconnect" href="https://fonts.googleapis.com">
195
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
196
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
@@ -211,7 +205,6 @@ TEMPLATE = """
211
  --text-secondary-color: var(--tg-theme-hint-color);
212
  --accent-gradient: linear-gradient(95deg, var(--tg-theme-button-color, #007aff), #5856d6);
213
  --accent-gradient-green: linear-gradient(95deg, #34c759, #30d158);
214
- --accent-gradient-ton: linear-gradient(95deg, #0098EA, #00baff); /* TON Gradient */
215
  --tag-bg: rgba(255, 255, 255, 0.1);
216
  --border-radius-s: 8px;
217
  --border-radius-m: 14px;
@@ -292,14 +285,6 @@ TEMPLATE = """
292
  background: rgba(44, 44, 46, 0.95);
293
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), var(--shadow-medium);
294
  }
295
- .btn-ton {
296
- background: var(--accent-gradient-ton);
297
- color: var(--tg-theme-button-text-color);
298
- }
299
- .btn-ton:hover {
300
- background: linear-gradient(95deg, #00baff, #0098EA);
301
- }
302
-
303
  .tag {
304
  display: inline-block; background: var(--tag-bg); color: var(--text-secondary-color);
305
  padding: 6px 12px; border-radius: var(--border-radius-s); font-size: 0.85em;
@@ -392,59 +377,6 @@ TEMPLATE = """
392
  }
393
  .save-card-button i { font-size: 1.2em; }
394
 
395
- .ton-wallet-section {
396
- margin-top: var(--padding-l);
397
- text-align: center;
398
- background-color: var(--card-bg);
399
- border-radius: var(--border-radius-l);
400
- padding: var(--padding-l);
401
- box-shadow: var(--shadow-medium);
402
- border: 1px solid rgba(255, 255, 255, 0.08);
403
- backdrop-filter: blur(var(--backdrop-blur));
404
- -webkit-backdrop-filter: blur(var(--backdrop-blur));
405
- }
406
- .ton-wallet-section h3 {
407
- font-size: 1.5em;
408
- font-weight: 600;
409
- margin-bottom: var(--padding-s);
410
- color: var(--tg-theme-link-color);
411
- }
412
- .ton-wallet-section .status-message {
413
- font-size: 1em;
414
- color: var(--text-secondary-color);
415
- margin-bottom: var(--padding-m);
416
- }
417
- .ton-wallet-section .wallet-info {
418
- margin-top: var(--padding-m);
419
- padding: var(--padding-m);
420
- background-color: var(--card-bg-solid);
421
- border-radius: var(--border-radius-m);
422
- text-align: left;
423
- border: 1px solid rgba(255, 255, 255, 0.08);
424
- }
425
- .ton-wallet-section .wallet-info p {
426
- margin-bottom: 0.5rem;
427
- word-break: break-all;
428
- }
429
- .ton-wallet-section .wallet-info strong {
430
- color: var(--tg-theme-text-color);
431
- font-weight: 600;
432
- }
433
- .ton-wallet-section .wallet-info .balance {
434
- font-size: 1.3em;
435
- font-weight: 700;
436
- color: var(--accent-gradient-ton-start, #0098EA); /* Use TON color */
437
- margin-top: 1rem;
438
- }
439
- .ton-wallet-section .wallet-info .balance span {
440
- font-size: 0.8em;
441
- font-weight: 500;
442
- color: var(--text-secondary-color);
443
- margin-left: 5px;
444
- }
445
-
446
-
447
- /* Modal Styles */
448
  .modal {
449
  display: none; position: fixed; z-index: 1001;
450
  left: 0; top: 0; width: 100%; height: 100%;
@@ -475,8 +407,21 @@ TEMPLATE = """
475
  .modal-text { font-size: 1.2em; line-height: 1.6; margin-bottom: var(--padding-s); word-wrap: break-word; }
476
  .modal-text b { color: var(--tg-theme-link-color); font-weight: 600; }
477
  .modal-instruction { font-size: 1em; color: var(--text-secondary-color); margin-top: var(--padding-m); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
 
479
- /* Icons */
480
  .icon { display: inline-block; width: 1.2em; text-align: center; margin-right: 8px; opacity: 0.9; }
481
  .icon-save::before { content: '💾'; }
482
  .icon-web::before { content: '🌐'; }
@@ -497,10 +442,9 @@ TEMPLATE = """
497
  .icon-link::before { content: '🔗'; }
498
  .icon-leader::before { content: '🏆'; }
499
  .icon-company::before { content: '🏢'; }
500
- .icon-ton::before { content: '💎'; }
501
 
502
 
503
- /* Responsive adjustments */
504
  @media (max-width: 480px) {
505
  .section-title { font-size: 1.8em; }
506
  .logo span { font-size: 1.4em; }
@@ -509,8 +453,6 @@ TEMPLATE = """
509
  .stats-grid { grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); gap: var(--padding-s); }
510
  .stat-value { font-size: 1.5em; }
511
  .modal-content { margin: 25% auto; width: 92%; }
512
- .ton-wallet-section h3 { font-size: 1.3em; }
513
- .ton-wallet-section .wallet-info .balance { font-size: 1.1em; }
514
  }
515
  </style>
516
  </head>
@@ -538,19 +480,6 @@ TEMPLATE = """
538
  </a>
539
  </section>
540
 
541
- <!-- TON Wallet Section -->
542
- <section class="ton-wallet-section">
543
- <h3><i class="icon icon-ton"></i>TON Wallet</h3>
544
- <div id="ton-status" class="status-message">Подключение к TON...</div>
545
- <button id="connect-ton-btn" class="btn btn-ton" style="display: none; width: 100%;">Подключить TON Кошелек</button>
546
- <div id="wallet-info" class="wallet-info" style="display: none;">
547
- <p><strong>Адрес:</strong> <span id="ton-address"></span></p>
548
- <p><strong>Баланс:</strong> <span id="ton-balance" class="balance"></span></p>
549
- </div>
550
- </section>
551
- <!-- End TON Wallet Section -->
552
-
553
-
554
  <section class="ecosystem-header">
555
  <h2 class="section-title"><i class="icon icon-company"></i>Экосистема инноваций</h2>
556
  <p class="description">
@@ -624,6 +553,20 @@ TEMPLATE = """
624
  </div>
625
  </section>
626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  <section class="section-card">
628
  <h2 class="section-title"><i class="icon icon-global"></i>Глобальное присутствие</h2>
629
  <p class="description">Наши инновационные решения и экспертиза доступны в странах Центральной Азии и за ее пределами:</p>
@@ -645,7 +588,6 @@ TEMPLATE = """
645
  <i class="icon icon-save"></i>Сохранить визитку
646
  </button>
647
 
648
- <!-- The Modal -->
649
  <div id="saveModal" class="modal">
650
  <div class="modal-content">
651
  <span class="modal-close" id="modal-close-btn">×</span>
@@ -679,136 +621,67 @@ TEMPLATE = """
679
  } catch (e) {
680
  root.style.setProperty('--tg-theme-bg-color-rgb', `18, 18, 18`);
681
  }
682
- }
683
-
684
- const TON_MANIFEST_URL = window.location.origin + '/.well-known/ton-connect/manifest.json';
685
- let connector = null;
686
-
687
- function setupTonConnect() {
688
- if (!window.TonConnectSDK) {
689
- console.error("TON Connect SDK not loaded.");
690
- document.getElementById('ton-status').textContent = 'Ошибка загрузки TON SDK.';
691
- document.getElementById('connect-ton-btn').style.display = 'none';
692
- return;
693
- }
694
- document.getElementById('ton-status').textContent = 'Инициализация TON Connect...';
695
-
696
  try {
697
- connector = new TonConnectSDK.TonConnect({
698
- manifestUrl: TON_MANIFEST_URL,
699
- });
 
 
 
 
 
700
 
701
- connector.onStatusChange(wallet => {
702
- console.log('TON Wallet status changed:', wallet);
703
- updateWalletUI(wallet);
704
- if (wallet) {
705
- // Wallet connected or changed, save address and fetch balance
706
- saveTonWalletAddress(wallet.account.address);
707
- fetchTonBalance();
708
- } else {
709
- // Wallet disconnected
710
- document.getElementById('ton-status').textContent = 'TON Кошелек не подключен.';
711
- }
712
- });
713
 
714
- document.getElementById('connect-ton-btn').addEventListener('click', () => {
715
- if (connector) {
716
- document.getElementById('ton-status').textContent = 'Подключение... Ожидайте в кошельке.';
717
- connector.connect();
718
- if (tg.HapticFeedback) {
719
- tg.HapticFeedback.impactOccurred('light');
720
- }
721
- }
722
- });
723
 
724
- // Attempt to restore existing connection
725
- connector.restoreConnection();
 
 
 
 
 
726
 
727
- } catch (e) {
728
- console.error("Failed to initialize TON Connect:", e);
729
- document.getElementById('ton-status').textContent = 'Ошибка инициализации TON Connect.';
730
- document.getElementById('connect-ton-btn').style.display = 'none';
731
- }
732
- }
733
 
734
- function updateWalletUI(wallet) {
735
- const connectBtn = document.getElementById('connect-ton-btn');
736
- const walletInfoDiv = document.getElementById('wallet-info');
737
- const statusDiv = document.getElementById('ton-status');
738
- const addressSpan = document.getElementById('ton-address');
739
- const balanceSpan = document.getElementById('ton-balance');
740
-
741
- if (wallet) {
742
- connectBtn.style.display = 'none';
743
- walletInfoDiv.style.display = 'block';
744
- statusDiv.textContent = 'TON Кошелек подключен.';
745
- addressSpan.textContent = TonConnectSDK.toUserFriendlyAddress(wallet.account.address, wallet.account.chain);
746
- balanceSpan.textContent = 'Загрузка...'; // Placeholder while fetching balance
747
- } else {
748
- connectBtn.style.display = 'block';
749
- walletInfoDiv.style.display = 'none';
750
- addressSpan.textContent = '';
751
- balanceSpan.textContent = '';
752
- statusDiv.textContent = 'TON Кошелек не подключен.';
753
- }
754
- }
755
 
756
- function saveTonWalletAddress(address) {
757
- if (!tg || !tg.initData) {
758
- console.error("Telegram WebApp initData is missing for saving wallet.");
759
- return;
760
- }
761
- fetch('/save_ton_wallet', {
762
- method: 'POST',
763
- headers: { 'Content-Type': 'application/json' },
764
- body: JSON.stringify({ initData: tg.initData, tonAddress: address }),
765
- })
766
- .then(response => response.json())
767
- .then(data => {
768
- if (data.status === 'ok') {
769
- console.log('TON wallet address saved successfully.');
770
- } else {
771
- console.error('Failed to save TON wallet address:', data.message);
772
- }
773
- })
774
- .catch(error => {
775
- console.error('Error sending TON wallet address to backend:', error);
776
- });
777
- }
778
 
779
- function fetchTonBalance() {
780
- if (!tg || !tg.initData) {
781
- console.error("Telegram WebApp initData is missing for fetching balance.");
782
- document.getElementById('ton-balance').textContent = 'Ошибка (нет данных ТГ)';
783
- return;
784
- }
785
- const balanceSpan = document.getElementById('ton-balance');
786
- balanceSpan.textContent = 'Загрузка...';
 
 
787
 
788
- fetch('/get_ton_balance', {
789
- method: 'POST',
790
- headers: { 'Content-Type': 'application/json' },
791
- body: JSON.stringify({ initData: tg.initData }),
792
- })
793
- .then(response => {
794
- if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
795
- return response.json();
796
- })
797
- .then(data => {
798
- if (data.status === 'ok') {
799
- // Balance is in nanoton, convert to TON
800
- const balanceTon = (data.balance / 1e9).toFixed(4);
801
- balanceSpan.innerHTML = `${balanceTon} <span>TON</span>`;
802
- } else {
803
- balanceSpan.textContent = `Ошибка: ${data.message}`;
804
- console.error('Failed to fetch TON balance:', data.message);
805
- }
806
- })
807
- .catch(error => {
808
- balanceSpan.textContent = `Ошибка: ${error.message}`;
809
- console.error('Error fetching TON balance:', error);
810
- });
811
- }
812
 
813
 
814
  function setupTelegram() {
@@ -817,7 +690,6 @@ TEMPLATE = """
817
  const greetingElement = document.getElementById('greeting');
818
  if(greetingElement) greetingElement.textContent = 'Не удалось связаться с Telegram.';
819
  document.body.style.visibility = 'visible';
820
- setupTonConnect(); // Try setting up TON anyway, it might work in standard browser
821
  return;
822
  }
823
 
@@ -835,28 +707,18 @@ TEMPLATE = """
835
  },
836
  body: JSON.stringify({ initData: tg.initData }),
837
  })
838
- .then(response => {
839
- if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
840
- return response.json();
841
- })
842
  .then(data => {
843
  if (data.status === 'ok' && data.verified) {
844
  console.log('Backend verification successful.');
845
- // Verification successful, now setup TON Connect
846
- setupTonConnect();
847
  } else {
848
  console.warn('Backend verification failed:', data.message);
849
- document.getElementById('ton-status').textContent = 'Проверка Telegram данных не пройдена.';
850
- document.getElementById('connect-ton-btn').style.display = 'none';
851
  }
852
  })
853
  .catch(error => {
854
  console.error('Error sending initData for verification:', error);
855
- document.getElementById('ton-status').textContent = 'Ошибка связи с сервером для проверки.';
856
- document.getElementById('connect-ton-btn').style.display = 'none';
857
  });
858
 
859
-
860
  const user = tg.initDataUnsafe?.user;
861
  const greetingElement = document.getElementById('greeting');
862
  if (user) {
@@ -901,6 +763,21 @@ TEMPLATE = """
901
  console.error("Modal elements not found!");
902
  }
903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
904
  document.body.style.visibility = 'visible';
905
  }
906
 
@@ -915,7 +792,6 @@ TEMPLATE = """
915
  const greetingElement = document.getElementById('greeting');
916
  if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса Telegram.';
917
  document.body.style.visibility = 'visible';
918
- setupTonConnect(); // Still try TON Connect even without Telegram initData fully
919
  }
920
  }, 3500);
921
  }
@@ -991,17 +867,9 @@ ADMIN_TEMPLATE = """
991
  }
992
  .user-card .name { font-weight: 600; font-size: 1.2em; margin-bottom: 0.3rem; color: var(--admin-primary); }
993
  .user-card .username { color: var(--admin-secondary); margin-bottom: 0.8rem; font-size: 0.95em; }
994
- .user-card .details { font-size: 0.9em; color: #495057; word-break: break-word; text-align: left; width: 100%; }
995
  .user-card .detail-item { margin-bottom: 0.3rem; }
996
- .user-card .detail-item strong { color: var(--admin-text); margin-right: 5px;}
997
- .user-card .detail-item .ton-address-text {
998
- display: block;
999
- font-size: 0.8em;
1000
- color: #6c757d;
1001
- margin-top: 5px;
1002
- word-break: break-all;
1003
- }
1004
-
1005
  .user-card .timestamp { font-size: 0.8em; color: var(--admin-secondary); margin-top: 1rem; }
1006
  .no-users { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; }
1007
  .alert {
@@ -1024,7 +892,6 @@ ADMIN_TEMPLATE = """
1024
  }
1025
  .refresh-btn:hover { background-color: #0b5ed7; }
1026
 
1027
- /* Admin Controls */
1028
  .admin-controls {
1029
  background: var(--admin-card-bg);
1030
  padding: var(--padding);
@@ -1090,14 +957,6 @@ ADMIN_TEMPLATE = """
1090
  <div class="detail-item"><strong>Язык:</strong> {{ user.language_code or 'N/A' }}</div>
1091
  <div class="detail-item"><strong>Premium:</strong> {{ 'Да' if user.is_premium else 'Нет' }}</div>
1092
  <div class="detail-item"><strong>Телефон:</strong> {{ user.phone_number or 'Недоступен' }}</div>
1093
- <div class="detail-item">
1094
- <strong>TON:</strong>
1095
- {% if user.ton_wallet %}
1096
- <span class="ton-address-text">{{ user.ton_wallet }}</span>
1097
- {% else %}
1098
- Не подключен
1099
- {% endif %}
1100
- </div>
1101
  </div>
1102
  <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
1103
  </div>
@@ -1154,17 +1013,6 @@ def index():
1154
  theme_params = {}
1155
  return render_template_string(TEMPLATE, theme=theme_params)
1156
 
1157
- @app.route('/.well-known/ton-connect/manifest.json')
1158
- def tonconnect_manifest():
1159
- manifest = {
1160
- "url": request.url_root.rstrip('/') ,
1161
- "name": "Morshen Group TMA",
1162
- "iconUrl": request.url_root.rstrip('/') + "/static/morshengroup_icon.png", # Ensure you have a static folder and this icon
1163
- "termsOfUseUrl": "", # Optional
1164
- "privacyPolicyUrl": "" # Optional
1165
- }
1166
- return jsonify(manifest)
1167
-
1168
  @app.route('/verify', methods=['POST'])
1169
  def verify_data():
1170
  try:
@@ -1176,134 +1024,71 @@ def verify_data():
1176
  user_data_parsed, is_valid = verify_telegram_data(init_data_str)
1177
 
1178
  user_info_dict = {}
1179
- user_id = None
1180
  if user_data_parsed and 'user' in user_data_parsed:
1181
  try:
1182
  user_json_str = unquote(user_data_parsed['user'][0])
1183
  user_info_dict = json.loads(user_json_str)
1184
- user_id = user_info_dict.get('id')
1185
  except Exception as e:
1186
- logging.error(f"Could not parse user JSON from initData: {e}")
1187
  user_info_dict = {}
1188
 
1189
- if is_valid and user_id:
1190
- now = time.time()
1191
- user_entry = {
1192
- str(user_id): {
1193
- 'id': user_id,
1194
- 'first_name': user_info_dict.get('first_name'),
1195
- 'last_name': user_info_dict.get('last_name'),
1196
- 'username': user_info_dict.get('username'),
1197
- 'photo_url': user_info_dict.get('photo_url'),
1198
- 'language_code': user_info_dict.get('language_code'),
1199
- 'is_premium': user_info_dict.get('is_premium', False),
1200
- 'phone_number': user_info_dict.get('phone_number'),
1201
- 'visited_at': now,
1202
- 'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
 
 
 
1203
  }
1204
- }
1205
- save_visitor_data(user_entry)
1206
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
1207
  else:
1208
- logging.warning(f"Verification failed or user_id missing for initData.")
1209
- return jsonify({"status": "error", "verified": False, "message": "Invalid data or missing user ID"}), 403
1210
 
1211
  except Exception as e:
1212
  logging.exception("Error in /verify endpoint")
1213
  return jsonify({"status": "error", "message": "Internal server error"}), 500
1214
 
1215
- @app.route('/save_ton_wallet', methods=['POST'])
1216
- def save_ton_wallet():
1217
- try:
1218
- req_data = request.get_json()
1219
- init_data_str = req_data.get('initData')
1220
- ton_address = req_data.get('tonAddress')
1221
-
1222
- if not init_data_str or not ton_address:
1223
- return jsonify({"status": "error", "message": "Missing initData or tonAddress"}), 400
1224
-
1225
- user_data_parsed, is_valid = verify_telegram_data(init_data_str)
1226
-
1227
- user_id = None
1228
- if user_data_parsed and 'user' in user_data_parsed:
1229
- try:
1230
- user_json_str = unquote(user_data_parsed['user'][0])
1231
- user_info_dict = json.loads(user_json_str)
1232
- user_id = user_info_dict.get('id')
1233
- except Exception as e:
1234
- logging.error(f"Could not parse user JSON from initData during save_ton_wallet: {e}")
1235
-
1236
-
1237
- if is_valid and user_id:
1238
- user_id_str = str(user_id)
1239
- current_data = load_visitor_data()
1240
- if user_id_str not in current_data:
1241
- current_data[user_id_str] = {'id': user_id} # Ensure user entry exists
1242
-
1243
- # Update only the ton_wallet field
1244
- user_entry_update = {
1245
- user_id_str: {
1246
- 'ton_wallet': ton_address
1247
- }
1248
- }
1249
- save_visitor_data(user_entry_update)
1250
-
1251
- return jsonify({"status": "ok", "message": "TON wallet address saved."}), 200
1252
- else:
1253
- logging.warning(f"Invalid initData or missing user ID during save_ton_wallet.")
1254
- return jsonify({"status": "error", "message": "Invalid Telegram data or missing user ID"}), 403
1255
-
1256
- except Exception as e:
1257
- logging.exception("Error in /save_ton_wallet endpoint")
1258
- return jsonify({"status": "error", "message": "Internal server error"}), 500
1259
-
1260
-
1261
  @app.route('/get_ton_balance', methods=['POST'])
1262
- def get_ton_balance():
1263
- if not tonapi:
1264
- return jsonify({"status": "error", "message": "TONAPI is not initialized (check TONAPI_KEY)."}), 503
1265
 
1266
  try:
1267
  req_data = request.get_json()
1268
- init_data_str = req_data.get('initData')
1269
 
1270
- if not init_data_str:
1271
- return jsonify({"status": "error", "message": "Missing initData"}), 400
1272
 
1273
- user_data_parsed, is_valid = verify_telegram_data(init_data_str)
1274
 
1275
- user_id = None
1276
- if user_data_parsed and 'user' in user_data_parsed:
1277
- try:
1278
- user_json_str = unquote(user_data_parsed['user'][0])
1279
- user_info_dict = json.loads(user_json_str)
1280
- user_id = user_info_dict.get('id')
1281
- except Exception as e:
1282
- logging.error(f"Could not parse user JSON from initData during get_ton_balance: {e}")
1283
-
1284
- if is_valid and user_id:
1285
- user_id_str = str(user_id)
1286
- current_data = load_visitor_data()
1287
- user_data = current_data.get(user_id_str)
1288
-
1289
- if user_data and 'ton_wallet' in user_data and user_data['ton_wallet']:
1290
- ton_address = user_data['ton_wallet']
1291
- try:
1292
- account_info = tonapi.account.get_wallet_v4(account_id=ton_address)
1293
- balance_nanoton = account_info.balance
1294
- return jsonify({"status": "ok", "balance": balance_nanoton, "address": ton_address}), 200
1295
- except Exception as e:
1296
- logging.error(f"Error fetching TON balance for {ton_address}: {e}")
1297
- return jsonify({"status": "error", "message": f"Failed to fetch balance: {e}"}), 500
1298
- else:
1299
- return jsonify({"status": "error", "message": "TON wallet not linked for this user."}), 404
1300
- else:
1301
- logging.warning(f"Invalid initData or missing user ID during get_ton_balance.")
1302
- return jsonify({"status": "error", "message": "Invalid Telegram data or missing user ID"}), 403
1303
 
1304
  except Exception as e:
1305
  logging.exception("Error in /get_ton_balance endpoint")
1306
- return jsonify({"status": "error", "message": "Internal server error"}), 500
1307
 
1308
 
1309
  @app.route('/admin')
@@ -1327,16 +1112,6 @@ def admin_trigger_upload():
1327
  upload_data_to_hf_async()
1328
  return jsonify({"status": "ok", "message": "Загрузка данных на Hugging Face запущена в фоновом режиме."})
1329
 
1330
- @app.route('/static/<filename>')
1331
- def static_files(filename):
1332
- if filename == 'morshengroup_icon.png':
1333
- # Basic handling for the manifest icon
1334
- try:
1335
- return app.send_static_file(filename)
1336
- except FileNotFoundError:
1337
- return "Icon not found", 404
1338
- return "Not found", 404
1339
-
1340
 
1341
  if __name__ == '__main__':
1342
  print("---")
@@ -1357,14 +1132,13 @@ if __name__ == '__main__':
1357
  print("--- Attempting initial data download from Hugging Face...")
1358
  download_data_from_hf()
1359
 
1360
- if not TONAPI_KEY:
1361
  print("---")
1362
- print("--- WARNING: TONAPI_KEY NOT SET ---")
1363
- print("--- TON wallet functionality will be disabled. Set TONAPI_KEY environment variable.")
1364
  print("---")
1365
  else:
1366
- print("--- TONAPI_KEY found. TON wallet functionality enabled.")
1367
-
1368
 
1369
  load_visitor_data()
1370
 
@@ -1381,22 +1155,5 @@ if __name__ == '__main__':
1381
  else:
1382
  print("--- Periodic backup disabled (HF_TOKEN_WRITE missing).")
1383
 
1384
- # Create a static directory if it doesn't exist and add a dummy icon
1385
- if not os.path.exists('static'):
1386
- os.makedirs('static')
1387
- dummy_icon_path = os.path.join('static', 'morshengroup_icon.png')
1388
- if not os.path.exists(dummy_icon_path):
1389
- try:
1390
- # Create a minimal dummy PNG (1x1 transparent)
1391
- import base64
1392
- dummy_png = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\xfc\xff\xff?\x03\x00\x08\xfb\x02\xfe\xa7\xcd\x8c\x00\x00\x00\x00IEND\xaeB`\x82'
1393
- with open(dummy_icon_path, 'wb') as f:
1394
- f.write(dummy_png)
1395
- print(f"Created dummy icon at {dummy_icon_path} for TON Connect manifest.")
1396
- except Exception as e:
1397
- print(f"Could not create dummy icon: {e}. TON Connect manifest icon might fail.")
1398
-
1399
-
1400
  print("--- Server Ready ---")
1401
-
1402
  app.run(host=HOST, port=PORT, debug=False)
 
14
  from huggingface_hub import HfApi, hf_hub_download
15
  from huggingface_hub.utils import RepositoryNotFoundError
16
  from pytonapi import Tonapi
17
+ from pytonapi.exceptions import AccountNotFoundError
18
 
19
  BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvtTVsqEJVG5SYK5hUlc_Ewo")
20
  HOST = '0.0.0.0'
 
26
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
27
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
28
 
29
+ TON_API_KEY = os.getenv("TON_API_KEY", "AE7WM7YGSNNKW5YAAAABMLCTU2KXDSRSNZM3Y4GF27OXBPZLAJPKXB6237ZFNQVLSX6F5NA")
30
 
31
  app = Flask(__name__)
32
  logging.basicConfig(level=logging.INFO)
 
35
  _data_lock = threading.Lock()
36
  visitor_data_cache = {}
37
 
38
+ try:
39
+ tonapi = Tonapi(api_key=TON_API_KEY)
40
+ logging.info("pytonapi initialized successfully.")
41
+ except Exception as e:
42
+ logging.error(f"Failed to initialize pytonapi: {e}")
43
+ tonapi = None
 
 
 
44
 
45
 
46
  def download_data_from_hf():
 
95
  visitor_data_cache = {}
96
  return visitor_data_cache
97
 
98
+ def save_visitor_data(data):
99
  with _data_lock:
100
  try:
101
+ visitor_data_cache.update(data)
 
 
102
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
103
+ json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
104
  logging.info(f"Visitor data successfully saved to {DATA_FILE}.")
105
  upload_data_to_hf_async()
106
  except Exception as e:
 
185
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
186
  <title>Morshen Group</title>
187
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
 
188
  <link rel="preconnect" href="https://fonts.googleapis.com">
189
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
190
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
 
205
  --text-secondary-color: var(--tg-theme-hint-color);
206
  --accent-gradient: linear-gradient(95deg, var(--tg-theme-button-color, #007aff), #5856d6);
207
  --accent-gradient-green: linear-gradient(95deg, #34c759, #30d158);
 
208
  --tag-bg: rgba(255, 255, 255, 0.1);
209
  --border-radius-s: 8px;
210
  --border-radius-m: 14px;
 
285
  background: rgba(44, 44, 46, 0.95);
286
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2), var(--shadow-medium);
287
  }
 
 
 
 
 
 
 
 
288
  .tag {
289
  display: inline-block; background: var(--tag-bg); color: var(--text-secondary-color);
290
  padding: 6px 12px; border-radius: var(--border-radius-s); font-size: 0.85em;
 
377
  }
378
  .save-card-button i { font-size: 1.2em; }
379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  .modal {
381
  display: none; position: fixed; z-index: 1001;
382
  left: 0; top: 0; width: 100%; height: 100%;
 
407
  .modal-text { font-size: 1.2em; line-height: 1.6; margin-bottom: var(--padding-s); word-wrap: break-word; }
408
  .modal-text b { color: var(--tg-theme-link-color); font-weight: 600; }
409
  .modal-instruction { font-size: 1em; color: var(--text-secondary-color); margin-top: var(--padding-m); }
410
+ .ton-info {
411
+ margin-top: var(--padding-m);
412
+ padding: var(--padding-m);
413
+ border-radius: var(--border-radius-m);
414
+ background-color: rgba(255, 255, 255, 0.08);
415
+ border: 1px solid rgba(255, 255, 255, 0.1);
416
+ text-align: center;
417
+ }
418
+ .ton-info p { margin-bottom: 0.5rem; }
419
+ .ton-info strong { color: var(--tg-theme-link-color); }
420
+ .ton-address { font-size: 0.9em; color: var(--text-secondary-color); word-break: break-all; margin-top: 0.5rem; }
421
+ .ton-balance { font-size: 1.4em; font-weight: 600; color: var(--accent-gradient-green-end, #30d158); margin-top: 0.5rem; }
422
+ .ton-error { font-size: 1em; color: var(--admin-danger, #dc3545); margin-top: 0.5rem; }
423
+
424
 
 
425
  .icon { display: inline-block; width: 1.2em; text-align: center; margin-right: 8px; opacity: 0.9; }
426
  .icon-save::before { content: '💾'; }
427
  .icon-web::before { content: '🌐'; }
 
442
  .icon-link::before { content: '🔗'; }
443
  .icon-leader::before { content: '🏆'; }
444
  .icon-company::before { content: '🏢'; }
445
+ .icon-ton::before { content: '💎'; }
446
 
447
 
 
448
  @media (max-width: 480px) {
449
  .section-title { font-size: 1.8em; }
450
  .logo span { font-size: 1.4em; }
 
453
  .stats-grid { grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); gap: var(--padding-s); }
454
  .stat-value { font-size: 1.5em; }
455
  .modal-content { margin: 25% auto; width: 92%; }
 
 
456
  }
457
  </style>
458
  </head>
 
480
  </a>
481
  </section>
482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  <section class="ecosystem-header">
484
  <h2 class="section-title"><i class="icon icon-company"></i>Экосистема инноваций</h2>
485
  <p class="description">
 
553
  </div>
554
  </section>
555
 
556
+ <section class="section-card">
557
+ <h2 class="section-title"><i class="icon icon-ton"></i>TON Кошелек</h2>
558
+ <p class="description">Проверьте баланс вашего TON кошелька.</p>
559
+ <div style="text-align: center; margin-bottom: var(--padding-m);">
560
+ <button id="ton-button" class="btn"><i class="icon icon-ton"></i> Проверить баланс</button>
561
+ </div>
562
+ <div id="ton-info-display" class="ton-info" style="display: none;">
563
+ <p><strong>Адрес:</strong> <span id="ton-address-display"></span></p>
564
+ <p><strong>Баланс:</strong> <span id="ton-balance-display"></span></p>
565
+ <p id="ton-error-display" class="ton-error" style="display: none;"></p>
566
+ </div>
567
+ </section>
568
+
569
+
570
  <section class="section-card">
571
  <h2 class="section-title"><i class="icon icon-global"></i>Глобальное присутствие</h2>
572
  <p class="description">Наши инновационные решения и экспертиза доступны в странах Центральной Азии и за ее пределами:</p>
 
588
  <i class="icon icon-save"></i>Сохранить визитку
589
  </button>
590
 
 
591
  <div id="saveModal" class="modal">
592
  <div class="modal-content">
593
  <span class="modal-close" id="modal-close-btn">×</span>
 
621
  } catch (e) {
622
  root.style.setProperty('--tg-theme-bg-color-rgb', `18, 18, 18`);
623
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
  try {
625
+ const greenColor = themeParams.button_color || '#34c759'; // Using button color as a base for green gradient end
626
+ const greenGradientEnd = '#' + (parseInt(greenColor.slice(1), 16) + 0x101010).toString(16).padStart(6, '0'); // Darken slightly
627
+ root.style.setProperty('--accent-gradient-green', `linear-gradient(95deg, #34c759, ${themeParams.button_color || '#30d158'})`);
628
+ root.style.setProperty('--accent-gradient-green-end', themeParams.button_color || '#30d158');
629
+ } catch (e) {
630
+ root.style.setProperty('--accent-gradient-green', 'linear-gradient(95deg, #34c759, #30d158)');
631
+ root.style.setProperty('--accent-gradient-green-end', '#30d158');
632
+ }
633
 
634
+ }
 
 
 
 
 
 
 
 
 
 
 
635
 
636
+ async function getTonBalance(address) {
637
+ const tonInfoDisplay = document.getElementById('ton-info-display');
638
+ const tonAddressDisplay = document.getElementById('ton-address-display');
639
+ const tonBalanceDisplay = document.getElementById('ton-balance-display');
640
+ const tonErrorDisplay = document.getElementById('ton-error-display');
641
+ const tonButton = document.getElementById('ton-button');
 
 
 
642
 
643
+ tonInfoDisplay.style.display = 'block';
644
+ tonAddressDisplay.textContent = address;
645
+ tonBalanceDisplay.textContent = 'Загрузка...';
646
+ tonBalanceDisplay.style.color = 'var(--tg-theme-hint-color)';
647
+ tonErrorDisplay.style.display = 'none';
648
+ tonButton.disabled = true;
649
+ tonButton.style.opacity = 0.7;
650
 
 
 
 
 
 
 
651
 
652
+ try {
653
+ const response = await fetch('/get_ton_balance', {
654
+ method: 'POST',
655
+ headers: { 'Content-Type': 'application/json' },
656
+ body: JSON.stringify({ wallet_address: address })
657
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
 
659
+ const data = await response.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660
 
661
+ if (response.ok && data.status === 'ok') {
662
+ tonBalanceDisplay.textContent = `${data.balance} TON`;
663
+ tonBalanceDisplay.style.color = 'var(--accent-gradient-green-end, #30d158)';
664
+ } else {
665
+ tonBalanceDisplay.textContent = '';
666
+ tonErrorDisplay.textContent = data.message || 'Неизвестная ошибка';
667
+ tonErrorDisplay.style.display = 'block';
668
+ tonBalanceDisplay.style.color = 'var(--admin-danger, #dc3545)';
669
+ console.error('TON Balance Error:', data.message);
670
+ if (tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('error');
671
 
672
+ }
673
+ } catch (error) {
674
+ tonBalanceDisplay.textContent = '';
675
+ tonErrorDisplay.textContent = `Ошибка сети: ${error.message}`;
676
+ tonErrorDisplay.style.display = 'block';
677
+ tonBalanceDisplay.style.color = 'var(--admin-danger, #dc3545)';
678
+ console.error('Fetch Error:', error);
679
+ if (tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('error');
680
+ } finally {
681
+ tonButton.disabled = false;
682
+ tonButton.style.opacity = 1;
683
+ }
684
+ }
 
 
 
 
 
 
 
 
 
 
 
685
 
686
 
687
  function setupTelegram() {
 
690
  const greetingElement = document.getElementById('greeting');
691
  if(greetingElement) greetingElement.textContent = 'Не удалось связаться с Telegram.';
692
  document.body.style.visibility = 'visible';
 
693
  return;
694
  }
695
 
 
707
  },
708
  body: JSON.stringify({ initData: tg.initData }),
709
  })
710
+ .then(response => response.json())
 
 
 
711
  .then(data => {
712
  if (data.status === 'ok' && data.verified) {
713
  console.log('Backend verification successful.');
 
 
714
  } else {
715
  console.warn('Backend verification failed:', data.message);
 
 
716
  }
717
  })
718
  .catch(error => {
719
  console.error('Error sending initData for verification:', error);
 
 
720
  });
721
 
 
722
  const user = tg.initDataUnsafe?.user;
723
  const greetingElement = document.getElementById('greeting');
724
  if (user) {
 
763
  console.error("Modal elements not found!");
764
  }
765
 
766
+ const tonButton = document.getElementById('ton-button');
767
+ if (tonButton) {
768
+ tonButton.addEventListener('click', async () => {
769
+ const address = prompt("Пожалуйста, введите адрес вашего TON кошелька:");
770
+ if (address) {
771
+ await getTonBalance(address.trim());
772
+ } else {
773
+ alert("Адрес кошелька не введен.");
774
+ }
775
+ });
776
+ } else {
777
+ console.error("TON button not found!");
778
+ }
779
+
780
+
781
  document.body.style.visibility = 'visible';
782
  }
783
 
 
792
  const greetingElement = document.getElementById('greeting');
793
  if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса Telegram.';
794
  document.body.style.visibility = 'visible';
 
795
  }
796
  }, 3500);
797
  }
 
867
  }
868
  .user-card .name { font-weight: 600; font-size: 1.2em; margin-bottom: 0.3rem; color: var(--admin-primary); }
869
  .user-card .username { color: var(--admin-secondary); margin-bottom: 0.8rem; font-size: 0.95em; }
870
+ .user-card .details { font-size: 0.9em; color: #495057; word-break: break-word; }
871
  .user-card .detail-item { margin-bottom: 0.3rem; }
872
+ .user-card .detail-item strong { color: var(--admin-text); }
 
 
 
 
 
 
 
 
873
  .user-card .timestamp { font-size: 0.8em; color: var(--admin-secondary); margin-top: 1rem; }
874
  .no-users { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; }
875
  .alert {
 
892
  }
893
  .refresh-btn:hover { background-color: #0b5ed7; }
894
 
 
895
  .admin-controls {
896
  background: var(--admin-card-bg);
897
  padding: var(--padding);
 
957
  <div class="detail-item"><strong>Язык:</strong> {{ user.language_code or 'N/A' }}</div>
958
  <div class="detail-item"><strong>Premium:</strong> {{ 'Да' if user.is_premium else 'Нет' }}</div>
959
  <div class="detail-item"><strong>Телефон:</strong> {{ user.phone_number or 'Недоступен' }}</div>
 
 
 
 
 
 
 
 
960
  </div>
961
  <div class="timestamp">Визит: {{ user.visited_at_str }}</div>
962
  </div>
 
1013
  theme_params = {}
1014
  return render_template_string(TEMPLATE, theme=theme_params)
1015
 
 
 
 
 
 
 
 
 
 
 
 
1016
  @app.route('/verify', methods=['POST'])
1017
  def verify_data():
1018
  try:
 
1024
  user_data_parsed, is_valid = verify_telegram_data(init_data_str)
1025
 
1026
  user_info_dict = {}
 
1027
  if user_data_parsed and 'user' in user_data_parsed:
1028
  try:
1029
  user_json_str = unquote(user_data_parsed['user'][0])
1030
  user_info_dict = json.loads(user_json_str)
 
1031
  except Exception as e:
1032
+ logging.error(f"Could not parse user JSON: {e}")
1033
  user_info_dict = {}
1034
 
1035
+ if is_valid:
1036
+ user_id = user_info_dict.get('id')
1037
+ if user_id:
1038
+ now = time.time()
1039
+ user_entry = {
1040
+ str(user_id): {
1041
+ 'id': user_id,
1042
+ 'first_name': user_info_dict.get('first_name'),
1043
+ 'last_name': user_info_dict.get('last_name'),
1044
+ 'username': user_info_dict.get('username'),
1045
+ 'photo_url': user_info_dict.get('photo_url'),
1046
+ 'language_code': user_info_dict.get('language_code'),
1047
+ 'is_premium': user_info_dict.get('is_premium', False),
1048
+ 'phone_number': user_info_dict.get('phone_number'),
1049
+ 'visited_at': now,
1050
+ 'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
1051
+ }
1052
  }
1053
+ save_visitor_data(user_entry)
 
1054
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
1055
  else:
1056
+ logging.warning(f"Verification failed for user: {user_info_dict.get('id')}")
1057
+ return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
1058
 
1059
  except Exception as e:
1060
  logging.exception("Error in /verify endpoint")
1061
  return jsonify({"status": "error", "message": "Internal server error"}), 500
1062
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1063
  @app.route('/get_ton_balance', methods=['POST'])
1064
+ def get_ton_balance_route():
1065
+ if tonapi is None:
1066
+ return jsonify({"status": "error", "message": "TON API not initialized on server."}), 500
1067
 
1068
  try:
1069
  req_data = request.get_json()
1070
+ wallet_address = req_data.get('wallet_address')
1071
 
1072
+ if not wallet_address:
1073
+ return jsonify({"status": "error", "message": "Адрес кошелька не предоставлен."}), 400
1074
 
1075
+ wallet_address = wallet_address.strip()
1076
 
1077
+ try:
1078
+ account_info = tonapi.account.get_info(account_id=wallet_address)
1079
+ balance_nano = account_info.balance
1080
+ balance_ton = balance_nano / 1e9
1081
+ return jsonify({"status": "ok", "balance": f"{balance_ton:,.9f}"}), 200
1082
+ except AccountNotFoundError:
1083
+ logging.warning(f"Account not found for address: {wallet_address}")
1084
+ return jsonify({"status": "error", "message": "TON кошелек не найден."}), 404
1085
+ except Exception as e:
1086
+ logging.error(f"Error fetching TON balance for {wallet_address}: {e}")
1087
+ return jsonify({"status": "error", "message": f"Ошибка получения баланса: {str(e)}"}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1088
 
1089
  except Exception as e:
1090
  logging.exception("Error in /get_ton_balance endpoint")
1091
+ return jsonify({"status": "error", "message": "Внутрен��яя ошибка сервера."}), 500
1092
 
1093
 
1094
  @app.route('/admin')
 
1112
  upload_data_to_hf_async()
1113
  return jsonify({"status": "ok", "message": "Загрузка данных на Hugging Face запущена в фоновом режиме."})
1114
 
 
 
 
 
 
 
 
 
 
 
1115
 
1116
  if __name__ == '__main__':
1117
  print("---")
 
1132
  print("--- Attempting initial data download from Hugging Face...")
1133
  download_data_from_hf()
1134
 
1135
+ if not TON_API_KEY:
1136
  print("---")
1137
+ print("--- WARNING: TON_API_KEY NOT SET ---")
1138
+ print("--- TON balance check functionality will not work. Set TON_API_KEY environment variable.")
1139
  print("---")
1140
  else:
1141
+ print("--- TON_API_KEY found.")
 
1142
 
1143
  load_visitor_data()
1144
 
 
1155
  else:
1156
  print("--- Periodic backup disabled (HF_TOKEN_WRITE missing).")
1157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1158
  print("--- Server Ready ---")
 
1159
  app.run(host=HOST, port=PORT, debug=False)