Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| import os | |
| from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for | |
| import hmac | |
| import hashlib | |
| import json | |
| from urllib.parse import unquote, parse_qs, quote | |
| import time | |
| from datetime import datetime | |
| import logging | |
| import threading | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError, HFValidationError | |
| # --- Configuration --- | |
| BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvbTVsqEJVG5SYK5hUlc_Ewo") # Replace with your actual bot token or set env var | |
| HOST = '0.0.0.0' | |
| PORT = 7860 | |
| USER_DATA_FILE = 'data.json' | |
| # Hugging Face Settings for User Data | |
| HF_USER_DATA_REPO_ID = "flpolprojects/teledata" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") # Needs write access to the repo | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", HF_TOKEN_WRITE) # Can use write token if read token not set | |
| # --- Flask App Initialization --- | |
| app = Flask(__name__) | |
| # --- Logging Setup --- | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| # --- Hugging Face Interaction --- | |
| def download_user_data_from_hf(): | |
| if not HF_TOKEN_READ or not HF_USER_DATA_REPO_ID: | |
| logging.warning("Hugging Face read token or repo ID not configured. Skipping download.") | |
| return | |
| try: | |
| logging.info(f"Attempting to download {USER_DATA_FILE} from {HF_USER_DATA_REPO_ID}") | |
| hf_hub_download( | |
| repo_id=HF_USER_DATA_REPO_ID, | |
| filename=USER_DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, # Ensure we get the latest version | |
| etag_timeout=60 # Extend timeout for potentially larger files | |
| ) | |
| logging.info(f"{USER_DATA_FILE} successfully downloaded from Hugging Face.") | |
| except RepositoryNotFoundError: | |
| logging.warning(f"Repository {HF_USER_DATA_REPO_ID} not found on Hugging Face. Will create local file if needed.") | |
| except HFValidationError as e: | |
| logging.error(f"Hugging Face Validation Error during download (Check Token Permissions?): {e}") | |
| except Exception as e: | |
| # Catch specific exceptions like hf_hub.utils._errors.HfHubHTTPError if possible | |
| if "404" in str(e): | |
| logging.warning(f"{USER_DATA_FILE} not found in repository {HF_USER_DATA_REPO_ID}. Will create local file if needed.") | |
| else: | |
| logging.error(f"Error downloading {USER_DATA_FILE} from Hugging Face: {e}") | |
| def upload_user_data_to_hf(): | |
| if not HF_TOKEN_WRITE or not HF_USER_DATA_REPO_ID: | |
| logging.warning("Hugging Face write token or repo ID not configured. Skipping upload.") | |
| return False | |
| if not os.path.exists(USER_DATA_FILE): | |
| logging.warning(f"{USER_DATA_FILE} does not exist locally. Skipping upload.") | |
| return False | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=USER_DATA_FILE, | |
| path_in_repo=USER_DATA_FILE, | |
| repo_id=HF_USER_DATA_REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Update user data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info(f"{USER_DATA_FILE} successfully uploaded to Hugging Face.") | |
| return True | |
| except HFValidationError as e: | |
| logging.error(f"Hugging Face Validation Error during upload (Check Token Permissions?): {e}") | |
| return False | |
| except Exception as e: | |
| logging.error(f"Error uploading {USER_DATA_FILE} to Hugging Face: {e}") | |
| return False | |
| def periodic_user_data_backup(): | |
| while True: | |
| time.sleep(3600) # Backup every hour | |
| logging.info("Performing periodic backup of user data...") | |
| upload_user_data_to_hf() | |
| # --- User Data Handling --- | |
| def load_user_data(): | |
| # Try to get the latest from HF first | |
| # download_user_data_from_hf() # Removed to prevent download on every load, rely on initial download + uploads | |
| try: | |
| with open(USER_DATA_FILE, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| if not isinstance(data, dict): | |
| logging.warning(f"{USER_DATA_FILE} does not contain a dictionary. Resetting.") | |
| return {} | |
| return data | |
| except FileNotFoundError: | |
| logging.info(f"{USER_DATA_FILE} not found locally. Initializing empty data.") | |
| return {} | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding JSON from {USER_DATA_FILE}. Returning empty data.") | |
| return {} | |
| except Exception as e: | |
| logging.error(f"Error loading user data from {USER_DATA_FILE}: {e}") | |
| return {} | |
| def save_user_data(data): | |
| try: | |
| with open(USER_DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(data, f, ensure_ascii=False, indent=4) | |
| logging.info(f"User data saved locally to {USER_DATA_FILE}.") | |
| # Attempt to upload immediately after saving locally | |
| upload_user_data_to_hf() | |
| except Exception as e: | |
| logging.error(f"Error saving user data to {USER_DATA_FILE}: {e}") | |
| # --- Telegram Data Verification --- | |
| def verify_telegram_data(init_data_str): | |
| try: | |
| parsed_data = parse_qs(init_data_str) | |
| received_hash = parsed_data.pop('hash', [None])[0] | |
| if not received_hash: | |
| return None, False | |
| data_check_list = [] | |
| for key, value in sorted(parsed_data.items()): | |
| data_check_list.append(f"{key}={value[0]}") | |
| data_check_string = "\n".join(data_check_list) | |
| secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest() | |
| calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() | |
| if calculated_hash == received_hash: | |
| auth_date = int(parsed_data.get('auth_date', [0])[0]) | |
| current_time = int(time.time()) | |
| if current_time - auth_date > 3600: # 1 hour validity | |
| logging.warning(f"Telegram InitData is older than 1 hour (Auth Date: {auth_date}, Current: {current_time}).") | |
| return parsed_data, True | |
| else: | |
| logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}") | |
| return parsed_data, False | |
| except Exception as e: | |
| logging.error(f"Error verifying Telegram data: {e}") | |
| return None, False | |
| # --- HTML Templates --- | |
| # Main Application Template | |
| TEMPLATE = """ | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no"> | |
| <title>Morshen Group</title> | |
| <script src="https://telegram.org/js/telegram-web-app.js"></script> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --bg-gradient-start: #0f172a; /* Slate 900 */ | |
| --bg-gradient-end: #1e293b; /* Slate 800 */ | |
| --card-bg: #334155; /* Slate 700 */ | |
| --card-bg-hover: #475569; /* Slate 600 */ | |
| --text-primary: #f1f5f9; /* Slate 100 */ | |
| --text-secondary: #cbd5e1; /* Slate 300 */ | |
| --text-muted: #94a3b8; /* Slate 400 */ | |
| --accent-primary-start: #3b82f6; /* Blue 500 */ | |
| --accent-primary-end: #6366f1; /* Indigo 500 */ | |
| --accent-secondary-start: #10b981; /* Emerald 500 */ | |
| --accent-secondary-end: #22c55e; /* Green 500 */ | |
| --tag-bg: rgba(255, 255, 255, 0.1); | |
| --tag-text: #e2e8f0; /* Slate 200 */ | |
| --border-color: #475569; /* Slate 600 */ | |
| --shadow-color: rgba(0, 0, 0, 0.3); | |
| --border-radius-sm: 6px; | |
| --border-radius-md: 12px; | |
| --border-radius-lg: 18px; | |
| --padding-xs: 4px; | |
| --padding-sm: 8px; | |
| --padding-md: 16px; | |
| --padding-lg: 24px; | |
| --padding-xl: 32px; | |
| --font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
| } | |
| * { box-sizing: border-box; margin: 0; padding: 0; } | |
| html { | |
| background: linear-gradient(160deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%); | |
| min-height: 100vh; | |
| } | |
| body { | |
| font-family: var(--font-family); | |
| background: linear-gradient(160deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%); | |
| color: var(--text-primary); | |
| padding: var(--padding-md); | |
| padding-bottom: 120px; /* Space for fixed button */ | |
| overscroll-behavior-y: none; | |
| -webkit-font-smoothing: antialiased; | |
| -moz-osx-font-smoothing: grayscale; | |
| visibility: hidden; /* Hide until ready */ | |
| line-height: 1.6; | |
| } | |
| .container { | |
| max-width: 700px; | |
| margin: 0 auto; | |
| display: flex; | |
| flex-direction: column; | |
| gap: var(--padding-xl); | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: var(--padding-md); | |
| padding: var(--padding-sm) 0; | |
| } | |
| .logo { display: flex; align-items: center; gap: var(--padding-md); } | |
| .logo img { | |
| width: 50px; | |
| height: 50px; | |
| border-radius: 50%; | |
| object-fit: cover; | |
| border: 2px solid rgba(255, 255, 255, 0.1); | |
| box-shadow: 0 4px 15px var(--shadow-color); | |
| transition: transform 0.3s ease; | |
| } | |
| .logo img:hover { transform: scale(1.1); } | |
| .logo span { font-size: 1.6em; font-weight: 700; letter-spacing: -0.5px; } | |
| .btn { | |
| display: inline-flex; align-items: center; justify-content: center; | |
| padding: 12px var(--padding-lg); | |
| border-radius: var(--border-radius-md); | |
| background: linear-gradient(90deg, var(--accent-primary-start), var(--accent-primary-end)); | |
| color: var(--text-primary); | |
| text-decoration: none; | |
| font-weight: 600; | |
| border: none; | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| gap: var(--padding-sm); | |
| font-size: 1em; | |
| box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3); | |
| } | |
| .btn:hover { opacity: 0.9; box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4); transform: translateY(-2px); } | |
| .btn-secondary { | |
| background: var(--card-bg); | |
| color: var(--accent-primary-start); | |
| box-shadow: 0 2px 8px rgba(0,0,0, 0.2); | |
| } | |
| .btn-secondary:hover { background: var(--card-bg-hover); box-shadow: 0 4px 12px rgba(0,0,0, 0.3); } | |
| .btn-cta { | |
| background: linear-gradient(90deg, var(--accent-secondary-start), var(--accent-secondary-end)); | |
| box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3); | |
| } | |
| .btn-cta:hover { | |
| box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4); | |
| } | |
| .tag { | |
| display: inline-block; | |
| background: var(--tag-bg); | |
| color: var(--tag-text); | |
| padding: var(--padding-xs) var(--padding-sm); | |
| border-radius: var(--border-radius-sm); | |
| font-size: 0.8em; | |
| font-weight: 500; | |
| margin: var(--padding-xs) var(--padding-xs) var(--padding-xs) 0; | |
| white-space: nowrap; | |
| border: 1px solid rgba(255, 255, 255, 0.1); | |
| } | |
| .tag i { margin-right: 4px; opacity: 0.8; color: var(--accent-secondary-start); } | |
| .section-card { | |
| background-color: var(--card-bg); | |
| border-radius: var(--border-radius-lg); | |
| padding: var(--padding-lg); | |
| border: 1px solid var(--border-color); | |
| box-shadow: 0 8px 25px var(--shadow-color); | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| overflow: hidden; /* Ensure children don't overflow rounded corners */ | |
| } | |
| .section-card:hover { | |
| transform: translateY(-3px); | |
| box-shadow: 0 12px 30px var(--shadow-color); | |
| } | |
| .section-title { | |
| font-size: 2em; | |
| font-weight: 800; | |
| margin-bottom: var(--padding-sm); | |
| line-height: 1.2; | |
| letter-spacing: -0.8px; | |
| background: linear-gradient(90deg, var(--text-primary), var(--text-secondary)); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| } | |
| .section-subtitle { font-size: 1.1em; font-weight: 500; color: var(--text-secondary); margin-bottom: var(--padding-md); } | |
| .description { font-size: 1em; line-height: 1.7; color: var(--text-secondary); margin-bottom: var(--padding-lg); } | |
| .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: var(--padding-md); margin-top: var(--padding-lg); } | |
| .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;} | |
| .stat-item:hover { background-color: rgba(255, 255, 255, 0.1); } | |
| .stat-value { font-size: 1.8em; font-weight: 700; display: block; color: var(--text-primary); } | |
| .stat-value i { font-size: 0.8em; margin-right: 4px; opacity: 0.7; } | |
| .stat-label { font-size: 0.85em; color: var(--text-muted); display: block; margin-top: var(--padding-xs); text-transform: uppercase; letter-spacing: 0.5px; } | |
| .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; } | |
| .list-item:hover { background-color: rgba(255, 255, 255, 0.1); } | |
| .list-item i { font-size: 1.3em; color: var(--accent-primary-start); opacity: 0.9; } | |
| .footer-greeting { text-align: center; color: var(--text-muted); font-size: 0.9em; margin-top: var(--padding-xl); } | |
| .save-card-button { | |
| position: fixed; | |
| bottom: 20px; | |
| left: 50%; | |
| transform: translateX(-50%); | |
| padding: 14px 28px; | |
| border-radius: 30px; | |
| background: linear-gradient(90deg, var(--accent-secondary-start), var(--accent-secondary-end)); | |
| color: var(--text-primary); | |
| text-decoration: none; | |
| font-weight: 700; | |
| border: none; | |
| cursor: pointer; | |
| transition: all 0.3s ease; | |
| z-index: 1000; | |
| box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4); | |
| font-size: 1.05em; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .save-card-button:hover { opacity: 0.9; transform: translateX(-50%) scale(1.05); box-shadow: 0 8px 25px rgba(16, 185, 129, 0.5); } | |
| /* Modal Styles (Enhanced) */ | |
| .modal { | |
| display: none; position: fixed; z-index: 1001; | |
| left: 0; top: 0; width: 100%; height: 100%; | |
| overflow: auto; background-color: rgba(15, 23, 42, 0.8); /* Slate 900 with opacity */ | |
| backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); | |
| display: flex; align-items: center; justify-content: center; | |
| animation: fadeIn 0.3s ease-out; | |
| } | |
| @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } | |
| .modal-content { | |
| background-color: var(--card-bg); color: var(--text-primary); | |
| margin: auto; padding: var(--padding-xl); | |
| border: 1px solid var(--border-color); | |
| width: 85%; max-width: 450px; | |
| border-radius: var(--border-radius-lg); | |
| text-align: center; position: relative; | |
| box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5); | |
| animation: scaleUp 0.3s ease-out; | |
| } | |
| @keyframes scaleUp { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } } | |
| .modal-close { | |
| color: var(--text-muted); position: absolute; | |
| top: 15px; right: 20px; font-size: 28px; | |
| font-weight: bold; cursor: pointer; line-height: 1; | |
| transition: color 0.3s ease, transform 0.3s ease; | |
| } | |
| .modal-close:hover { color: var(--text-primary); transform: rotate(90deg); } | |
| .modal-text { font-size: 1.15em; line-height: 1.6; margin-bottom: var(--padding-md); word-wrap: break-word; } | |
| .modal-text b { color: var(--accent-secondary-start); font-weight: 700; } | |
| .modal-instruction { font-size: 0.95em; color: var(--text-muted); margin-top: var(--padding-sm); } | |
| /* Icons */ | |
| [class^="icon-"]::before { | |
| display: inline-block; | |
| font-style: normal; | |
| font-variant: normal; | |
| text-rendering: auto; | |
| -webkit-font-smoothing: antialiased; | |
| margin-right: 8px; | |
| opacity: 0.9; | |
| font-size: 1.1em; /* Slightly larger icons */ | |
| } | |
| .icon-save::before { content: '💾'; color: #a7f3d0; } /* Emerald 200 */ | |
| .icon-web::before { content: '🌐'; color: #93c5fd; } /* Blue 300 */ | |
| .icon-mobile::before { content: '📱'; color: #a5b4fc; } /* Indigo 300 */ | |
| .icon-code::before { content: '💻'; color: #fde047; } /* Yellow 400 */ | |
| .icon-ai::before { content: '🧠'; color: #f9a8d4; } /* Pink 300 */ | |
| .icon-quantum::before { content: '⚛️'; color: #d8b4fe; } /* Purple 300 */ | |
| .icon-business::before { content: '💼'; color: #fdba74; } /* Orange 300 */ | |
| .icon-speed::before { content: '⚡️'; color: #facc15; } /* Amber 400 */ | |
| .icon-complexity::before { content: '🧩'; color: #a7f3d0; } /* Emerald 200 */ | |
| .icon-experience::before { content: '⏳'; color: #fca5a5; } /* Red 300 */ | |
| .icon-clients::before { content: '👥'; color: #67e8f9; } /* Cyan 300 */ | |
| .icon-market::before { content: '📈'; color: #86efac; } /* Green 300 */ | |
| .icon-location::before { content: '📍'; color: #f87171; } /* Red 400 */ | |
| .icon-global::before { content: '🌍'; color: #60a5fa; } /* Blue 400 */ | |
| .icon-innovation::before { content: '💡'; color: #fcd34d; } /* Amber 300 */ | |
| .icon-contact::before { content: '💬'; color: #5eead4; } /* Teal 300 */ | |
| .icon-link::before { content: '🔗'; color: #9ca3af; } /* Gray 400 */ | |
| .icon-leader::before { content: '🏆'; color: #fde047; } /* Yellow 400 */ | |
| .icon-company::before { content: '🏢'; color: #a5b4fc; } /* Indigo 300 */ | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <section class="morshen-group-intro section-card" style="border-top: 4px solid var(--accent-primary-start);"> | |
| <div class="header"> | |
| <div class="logo"> | |
| <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Group Logo"> | |
| <span>Morshen Group</span> | |
| </div> | |
| <a href="#" class="btn contact-link"><i class="icon-contact"></i>Связаться</a> | |
| </div> | |
| <div style="margin: var(--padding-sm) 0 var(--padding-md) 0;"> | |
| <span class="tag"><i class="icon-leader"></i>Лидер инноваций 2025</span> | |
| <span class="tag"><i class="icon-global"></i>Международный</span> | |
| </div> | |
| <h1 class="section-title" style="font-size: 2.4em;">Международный IT холдинг</h1> | |
| <p class="description"> | |
| Объединяем передовые технологические компании для создания инновационных | |
| решений мирового уровня, формируя цифровое будущее. | |
| </p> | |
| <a href="#" class="btn btn-cta contact-link" style="width: 100%; margin-top: var(--padding-md); padding: 14px 0;"> | |
| <i class="icon-contact"></i>Связаться с нами | |
| </a> | |
| </section> | |
| <section class="ecosystem-header"> | |
| <div style="text-align: center; margin-bottom: var(--padding-md);"> | |
| <span class="tag"><i class="icon-company"></i>Наши компании</span> | |
| </div> | |
| <h2 class="section-title" style="text-align: center;">Экосистема Инноваций</h2> | |
| <p class="description" style="text-align: center; max-width: 550px; margin-left: auto; margin-right: auto;"> | |
| В состав холдинга входят компании, специализирующиеся на различных | |
| направлениях передовых технологий, от ИИ до веб-разработки. | |
| </p> | |
| </section> | |
| <section class="section-card"> | |
| <div class="logo"> | |
| <img src="https://huggingface.co/spaces/Aleksmorshen/Telemap8/resolve/main/morshengroup.jpg" alt="Morshen Alpha Logo" style="width: 45px; height: 45px;"> | |
| <span style="font-size: 1.5em; font-weight: 700;">Morshen Alpha</span> | |
| </div> | |
| <div style="margin: var(--padding-md) 0;"> | |
| <span class="tag"><i class="icon-ai"></i>Искусственный интеллект</span> | |
| <span class="tag"><i class="icon-quantum"></i>Квантовые технологии</span> | |
| <span class="tag"><i class="icon-business"></i>Бизнес-решения</span> | |
| </div> | |
| <p class="description"> | |
| Флагманская R&D компания холдинга. Специализируемся на разработке прорывных | |
| бизнес-решений, исследованиях в сфере ИИ и квантовых технологий. Наши инновации формируют будущее индустрии. | |
| </p> | |
| <div class="stats-grid"> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-global"></i> 3</span> | |
| <span class="stat-label">Страны</span> | |
| </div> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-clients"></i> 3K+</span> | |
| <span class="stat-label">Клиенты</span> | |
| </div> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-market"></i> 5</span> | |
| <span class="stat-label">Лет на рынке</span> | |
| </div> | |
| </div> | |
| </section> | |
| <section class="section-card"> | |
| <div class="logo"> | |
| <img src="https://huggingface.co/spaces/holmgardstudio/dev/resolve/main/image.jpg" alt="Holmgard Logo" style="width: 45px; height: 45px;"> | |
| <span style="font-size: 1.5em; font-weight: 700;">Holmgard</span> | |
| </div> | |
| <div style="margin: var(--padding-md) 0;"> | |
| <span class="tag"><i class="icon-web"></i>Веб-разработка</span> | |
| <span class="tag"><i class="icon-mobile"></i>Мобильные приложения</span> | |
| <span class="tag"><i class="icon-code"></i>ПО на заказ</span> | |
| </div> | |
| <p class="description"> | |
| Инновационная студия разработки, создающая высокотехнологичные цифровые продукты | |
| для бизнеса любого масштаба. Сайты, мобильные приложения и ПО с использованием | |
| передовых технологий и гибких методологий. | |
| </p> | |
| <div class="stats-grid"> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-experience"></i> 10+</span> | |
| <span class="stat-label">Лет опыта</span> | |
| </div> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-complexity"></i> ∞</span> | |
| <span class="stat-label">Сложность</span> | |
| </div> | |
| <div class="stat-item"> | |
| <span class="stat-value"><i class="icon-speed"></i></span> | |
| <span class="stat-label">Скорость</span> | |
| </div> | |
| </div> | |
| <div style="display: flex; gap: var(--padding-md); margin-top: var(--padding-lg); flex-wrap: wrap;"> | |
| <a href="https://holmgard.ru" target="_blank" class="btn btn-secondary" style="flex-grow: 1;"><i class="icon-link"></i>Веб-сайт</a> | |
| <a href="#" class="btn contact-link" style="flex-grow: 1;"><i class="icon-contact"></i>Связаться</a> | |
| </div> | |
| </section> | |
| <section> | |
| <div style="text-align: center; margin-bottom: var(--padding-md);"> | |
| <span class="tag"><i class="icon-global"></i>Глобальное Присутствие</span> | |
| </div> | |
| <h2 class="section-title" style="text-align: center;">География Присутствия</h2> | |
| <p class="description" style="text-align: center;">Наши инновационные решения активно используются в странах:</p> | |
| <div style="display: flex; flex-direction: column; gap: var(--padding-sm);"> | |
| <div class="list-item"><i class="icon-location"></i>Узбекистан</div> | |
| <div class="list-item"><i class="icon-location"></i>Казахстан</div> | |
| <div class="list-item"><i class="icon-location"></i>Кыргызстан</div> | |
| </div> | |
| </section> | |
| <footer class="footer-greeting"> | |
| <p id="greeting">Загрузка данных пользователя...</p> | |
| </footer> | |
| </div> | |
| <button class="save-card-button" id="save-card-btn"> | |
| <i class="icon-save"></i>Сохранить визитку | |
| </button> | |
| <!-- The Modal --> | |
| <div id="saveModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="modal-close" id="modal-close-btn">×</span> | |
| <p class="modal-text"><b>+996500398754</b></p> | |
| <p class="modal-text">Morshen Group, IT компания</p> | |
| <p class="modal-instruction">Сделайте скриншот экрана, чтобы сохранить контакт.</p> | |
| </div> | |
| </div> | |
| <script> | |
| const tg = window.Telegram.WebApp; | |
| function applyTheme(themeParams) { | |
| // Example of adapting to TG theme (can be more complex) | |
| const isDark = themeParams.bg_color && themeParams.bg_color.startsWith('#') && parseInt(themeParams.bg_color.substring(1), 16) < parseInt('888888', 16); | |
| if (isDark) { | |
| // Use default dark theme or potentially adjust CSS vars based on themeParams | |
| document.body.classList.add('tg-dark'); // Add a class to target specific styles | |
| } else { | |
| // Use default light theme or adjust | |
| document.body.classList.remove('tg-dark'); | |
| } | |
| // Apply specific colors if available (more granular control) | |
| if (themeParams.bg_color) document.documentElement.style.setProperty('--tg-bg-color', themeParams.bg_color); | |
| if (themeParams.text_color) document.documentElement.style.setProperty('--tg-text-color', themeParams.text_color); | |
| if (themeParams.button_color) { | |
| document.documentElement.style.setProperty('--tg-button-color', themeParams.button_color); | |
| // Example: Update accent gradient if needed based on button color | |
| // document.documentElement.style.setProperty('--accent-primary-start', themeParams.button_color); | |
| } | |
| if (themeParams.button_text_color) document.documentElement.style.setProperty('--tg-button-text-color', themeParams.button_text_color); | |
| if (themeParams.secondary_bg_color) document.documentElement.style.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color); | |
| console.log("Applied Telegram Theme:", themeParams); | |
| } | |
| function setupTelegram() { | |
| if (!tg || !tg.initData) { | |
| console.error("Telegram WebApp script not loaded or initData is missing."); | |
| const greetingElement = document.getElementById('greeting'); | |
| if(greetingElement) greetingElement.textContent = 'Не удалось загрузить данные Telegram.'; | |
| document.body.style.visibility = 'visible'; | |
| return; | |
| } | |
| tg.ready(); | |
| tg.expand(); | |
| // Apply Theme | |
| applyTheme(tg.themeParams || {}); | |
| tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); | |
| // Send initData for verification and user logging | |
| fetch('/verify', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json', }, | |
| body: JSON.stringify({ initData: tg.initData }), | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.status === 'ok' && data.verified) { | |
| console.log('Backend verification successful.', data.user); | |
| } else { | |
| console.warn('Backend verification failed:', data.message); | |
| // Optional: Show visual warning in the UI | |
| // const greetingElement = document.getElementById('greeting'); | |
| // if(greetingElement) greetingElement.innerHTML += ' <span style="color: yellow;">(верификация не пройдена)</span>'; | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Error sending initData for verification:', error); | |
| }); | |
| // User Greeting (using unsafe data for speed) | |
| const user = tg.initDataUnsafe?.user; | |
| const greetingElement = document.getElementById('greeting'); | |
| if (user) { | |
| const firstName = user.first_name || ''; | |
| const lastName = user.last_name || ''; | |
| const username = user.username ? `@${user.username}` : ''; | |
| const name = `${firstName} ${lastName}`.trim() || username || 'Гость'; | |
| greetingElement.textContent = `Добро пожаловать, ${name}! 👋`; | |
| } else { | |
| greetingElement.textContent = 'Добро пожаловать!'; | |
| console.warn('Telegram User data not available (initDataUnsafe.user is empty).'); | |
| } | |
| // Contact Links | |
| const contactButtons = document.querySelectorAll('.contact-link'); | |
| contactButtons.forEach(button => { | |
| button.addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| try { | |
| tg.openTelegramLink('https://t.me/morshenkhan'); // Replace with actual contact username | |
| } catch (err) { | |
| console.error("Failed to open TG link:", err); | |
| window.open('https://t.me/morshenkhan', '_blank'); // Fallback | |
| } | |
| }); | |
| }); | |
| // Modal Setup | |
| const modal = document.getElementById("saveModal"); | |
| const saveCardBtn = document.getElementById("save-card-btn"); | |
| const closeBtn = document.getElementById("modal-close-btn"); | |
| if (saveCardBtn && modal && closeBtn) { | |
| saveCardBtn.addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| modal.style.display = "flex"; // Use flex for centering | |
| if (tg.HapticFeedback) { | |
| tg.HapticFeedback.impactOccurred('light'); | |
| } | |
| }); | |
| closeBtn.addEventListener('click', () => { | |
| modal.style.display = "none"; | |
| }); | |
| // Close modal if clicked outside the content (on the backdrop) | |
| modal.addEventListener('click', (event) => { | |
| if (event.target === modal) { // Check if the click is directly on the modal backdrop | |
| modal.style.display = "none"; | |
| } | |
| }); | |
| } else { | |
| console.error("Modal elements not found!"); | |
| } | |
| document.body.style.visibility = 'visible'; // Make body visible now | |
| } | |
| // Initialize Telegram WebApp robustly | |
| try { | |
| if (tg && tg.initData) { | |
| setupTelegram(); | |
| } else { | |
| console.log("Telegram WebApp object not immediately available, waiting for window.load"); | |
| window.addEventListener('load', setupTelegram); | |
| } | |
| } catch (e) { | |
| console.error("Error during initial Telegram WebApp setup:", e); | |
| const greetingElement = document.getElementById('greeting'); | |
| if(greetingElement) greetingElement.textContent = 'Ошибка инициализации Telegram.'; | |
| document.body.style.visibility = 'visible'; // Show body anyway on error | |
| } | |
| // Fallback timeout in case 'load' doesn't fire or TG script fails silently | |
| setTimeout(() => { | |
| if (document.body.style.visibility !== 'visible') { | |
| console.error("Telegram WebApp script fallback timeout triggered. Forcing visibility."); | |
| const greetingElement = document.getElementById('greeting'); | |
| if(greetingElement && greetingElement.textContent.includes('Загрузка')) { | |
| greetingElement.textContent = 'Ошибка загрузки Telegram.'; | |
| } | |
| document.body.style.visibility = 'visible'; | |
| // Attempt setup one last time if it failed | |
| if (typeof window.Telegram !== 'undefined' && typeof window.Telegram.WebApp !== 'undefined') { | |
| setupTelegram(); | |
| } | |
| } | |
| }, 4000); // Increased timeout | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| # Admin Panel Template | |
| ADMIN_TEMPLATE = """ | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Admin - Посетители</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --admin-bg: #f8fafc; /* Slate 50 */ | |
| --admin-text: #1e293b; /* Slate 800 */ | |
| --admin-card-bg: #ffffff; | |
| --admin-border: #e2e8f0; /* Slate 200 */ | |
| --admin-shadow: rgba(0, 0, 0, 0.05); | |
| --admin-accent: #3b82f6; /* Blue 500 */ | |
| --admin-text-muted: #64748b; /* Slate 500 */ | |
| --admin-danger-bg: #fee2e2; /* Red 100 */ | |
| --admin-danger-text: #b91c1c; /* Red 700 */ | |
| --admin-danger-border: #ef4444; /* Red 500 */ | |
| --border-radius-md: 8px; | |
| --padding-md: 16px; | |
| --padding-lg: 24px; | |
| --font-family: 'Inter', sans-serif; | |
| } | |
| body { | |
| font-family: var(--font-family); | |
| background-color: var(--admin-bg); | |
| color: var(--admin-text); | |
| margin: 0; | |
| padding: var(--padding-lg); | |
| line-height: 1.6; | |
| } | |
| h1 { | |
| text-align: center; | |
| color: var(--admin-text); | |
| font-weight: 700; | |
| margin-bottom: var(--padding-lg); | |
| } | |
| .user-grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); | |
| gap: var(--padding-lg); | |
| margin-top: var(--padding-lg); | |
| } | |
| .user-card { | |
| background-color: var(--admin-card-bg); | |
| border-radius: var(--border-radius-md); | |
| padding: var(--padding-lg); | |
| box-shadow: 0 4px 10px var(--admin-shadow); | |
| border: 1px solid var(--admin-border); | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| text-align: center; | |
| transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out; | |
| } | |
| .user-card:hover { | |
| transform: translateY(-3px); | |
| box-shadow: 0 6px 15px rgba(0,0,0,0.08); | |
| } | |
| .user-card img { | |
| width: 80px; | |
| height: 80px; | |
| border-radius: 50%; | |
| margin-bottom: var(--padding-md); | |
| object-fit: cover; | |
| border: 3px solid var(--admin-border); | |
| background-color: #f1f5f9; /* Placeholder bg */ | |
| } | |
| .user-card .name { | |
| font-weight: 600; | |
| font-size: 1.15em; | |
| margin-bottom: 4px; | |
| color: var(--admin-text); | |
| } | |
| .user-card .username { | |
| color: var(--admin-accent); | |
| margin-bottom: var(--padding-md); | |
| font-size: 0.95em; | |
| font-weight: 500; | |
| } | |
| .user-card .details { | |
| font-size: 0.9em; | |
| color: var(--admin-text-muted); | |
| word-break: break-word; /* Ensure long IDs don't overflow */ | |
| width: 100%; | |
| line-height: 1.5; | |
| } | |
| .user-card .details span { display: block; margin-bottom: 4px; } | |
| .user-card .details strong { color: #475569; } /* Slate 600 */ | |
| .user-card .timestamp { | |
| font-size: 0.8em; | |
| color: #94a3b8; /* Slate 400 */ | |
| margin-top: var(--padding-md); | |
| } | |
| .no-users { | |
| text-align: center; | |
| color: var(--admin-text-muted); | |
| margin-top: 40px; | |
| font-size: 1.1em; | |
| } | |
| .alert { | |
| background-color: var(--admin-danger-bg); | |
| border-left: 5px solid var(--admin-danger-border); | |
| margin-bottom: var(--padding-lg); | |
| padding: var(--padding-md); | |
| color: var(--admin-danger-text); | |
| border-radius: var(--border-radius-md); | |
| text-align: center; | |
| font-weight: 500; | |
| } | |
| .total-users { | |
| text-align: center; | |
| font-size: 1.1em; | |
| color: var(--admin-text-muted); | |
| margin-bottom: var(--padding-lg); | |
| } | |
| .button-container { | |
| text-align: center; | |
| margin-bottom: 20px; | |
| } | |
| .button-container button { | |
| padding: 10px 20px; | |
| font-size: 1em; | |
| cursor: pointer; | |
| border: none; | |
| border-radius: 6px; | |
| background-color: var(--admin-accent); | |
| color: white; | |
| transition: background-color 0.3s ease; | |
| } | |
| .button-container button:hover { | |
| background-color: #2563eb; /* Darker blue */ | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Панель Администратора - Посетители</h1> | |
| <div class="alert">ВНИМАНИЕ: Этот раздел не защищен! Добавьте аутентификацию для реального использования.</div> | |
| <div class="button-container"> | |
| <form method="POST" action="{{ url_for('force_backup') }}" style="display: inline;"> | |
| <button type="submit">Принудительно Загрузить на HF</button> | |
| </form> | |
| <form method="POST" action="{{ url_for('force_download') }}" style="display: inline; margin-left: 10px;"> | |
| <button type="submit" style="background-color: #059669;">Принудительно Скачать с HF</button> | |
| </form> | |
| </div> | |
| {% if users %} | |
| <p class="total-users">Всего уникальных посетителей: {{ users|length }}</p> | |
| <div class="user-grid"> | |
| {% for user_id, user in users.items()|sort(attribute='1.visited_at', reverse=true) %} | |
| <div class="user-card"> | |
| <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"> | |
| <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div> | |
| {% if user.username %} | |
| <div class="username">@{{ user.username }}</div> | |
| {% else %} | |
| <div class="username" style="opacity: 0.5;">(нет username)</div> | |
| {% endif %} | |
| <div class="details"> | |
| <span><strong>ID:</strong> {{ user.id }}</span> | |
| <span><strong>Язык:</strong> {{ user.language_code or 'N/A' }}</span> | |
| <span><strong>Телефон:</strong> <span style="color: #f87171;">Недоступен</span></span> | |
| </div> | |
| <div class="timestamp">Визит: {{ user.visited_at_str }}</div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p class="no-users">Пока нет данных о посетителях.</p> | |
| {% endif %} | |
| </body> | |
| </html> | |
| """ | |
| # --- Flask Routes --- | |
| def index(): | |
| return render_template_string(TEMPLATE) | |
| def verify_data(): | |
| try: | |
| data = request.get_json() | |
| init_data_str = data.get('initData') | |
| if not init_data_str: | |
| logging.warning("Verification request missing initData.") | |
| return jsonify({"status": "error", "message": "Missing initData"}), 400 | |
| user_data_parsed, is_valid = verify_telegram_data(init_data_str) | |
| user_info_dict = {} | |
| if user_data_parsed and 'user' in user_data_parsed: | |
| try: | |
| user_json_str = unquote(user_data_parsed['user'][0]) | |
| user_info_dict = json.loads(user_json_str) | |
| except Exception as e: | |
| logging.error(f"Could not parse user JSON from initData: {e}") | |
| user_info_dict = {} | |
| if is_valid: | |
| user_id = user_info_dict.get('id') | |
| if user_id: | |
| user_id_str = str(user_id) # Use string keys for JSON consistency | |
| visited_users = load_user_data() # Load current data | |
| now = time.time() | |
| user_record = { | |
| 'id': user_id, | |
| 'first_name': user_info_dict.get('first_name'), | |
| 'last_name': user_info_dict.get('last_name'), | |
| 'username': user_info_dict.get('username'), | |
| 'photo_url': user_info_dict.get('photo_url'), | |
| 'language_code': user_info_dict.get('language_code'), | |
| 'visited_at': now, | |
| 'visited_at_str': datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S') | |
| } | |
| # Update existing record or add new one | |
| visited_users[user_id_str] = user_record | |
| logging.info(f"User visit recorded/updated for ID: {user_id_str}") | |
| save_user_data(visited_users) # Save updated data locally and trigger HF upload | |
| return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200 | |
| else: | |
| logging.warning(f"Verification failed for potential user: {user_info_dict.get('id')}") | |
| return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 | |
| except Exception as e: | |
| logging.exception("Critical error in /verify endpoint") # Log full traceback | |
| return jsonify({"status": "error", "message": "Internal server error"}), 500 | |
| def admin_panel(): | |
| # WARNING: This route is unprotected! Add proper authentication/authorization. | |
| users_data = load_user_data() | |
| return render_template_string(ADMIN_TEMPLATE, users=users_data) | |
| def force_backup(): | |
| # WARNING: Unprotected route | |
| logging.info("Admin triggered force backup to Hugging Face.") | |
| success = upload_user_data_to_hf() | |
| # Redirect back to admin panel or show a message | |
| # For now, just redirecting. Add flash messages for better UX. | |
| return redirect(url_for('admin_panel')) | |
| def force_download(): | |
| # WARNING: Unprotected route | |
| logging.info("Admin triggered force download from Hugging Face.") | |
| download_user_data_from_hf() | |
| # Redirect back to admin panel | |
| return redirect(url_for('admin_panel')) | |
| # --- Main Execution --- | |
| if __name__ == '__main__': | |
| if not BOT_TOKEN or ':' not in BOT_TOKEN: | |
| logging.error("FATAL: BOT_TOKEN is not set or invalid.") | |
| exit(1) | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_WRITE is not set. User data upload to Hugging Face will be disabled.") | |
| if not HF_TOKEN_READ: | |
| logging.warning("HF_TOKEN_READ is not set. Will try to use HF_TOKEN_WRITE for downloads if available.") | |
| # Initial download of user data when the app starts | |
| logging.info("Attempting initial download of user data...") | |
| download_user_data_from_hf() | |
| # Start the periodic backup thread | |
| if HF_TOKEN_WRITE and HF_USER_DATA_REPO_ID: | |
| backup_thread = threading.Thread(target=periodic_user_data_backup, daemon=True) | |
| backup_thread.start() | |
| logging.info("Periodic user data backup thread started.") | |
| else: | |
| logging.warning("Periodic backup disabled due to missing HF configuration.") | |
| logging.info(f"--- SECURITY WARNING ---") | |
| logging.info(f"The /admin, /force_backup, /force_download routes are NOT protected.") | |
| logging.info(f"Implement proper security (e.g., password, IP restriction) before production.") | |
| logging.info(f"------------------------") | |
| logging.info(f"Starting Flask server on http://{HOST}:{PORT}") | |
| logging.info(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}") | |
| logging.info(f"User data file: {USER_DATA_FILE}") | |
| logging.info(f"User data HF Repo: {HF_USER_DATA_REPO_ID}") | |
| # Use a production-ready server like Waitress or Gunicorn instead of app.run() for deployment | |
| # from waitress import serve | |
| # serve(app, host=HOST, port=PORT) | |
| app.run(host=HOST, port=PORT, debug=False) # debug=False for production |