Spaces:
Sleeping
Sleeping
Download app.py from AaaTestosonet/Examplebonus33: direct link, hf CLI and curl.
- Browser
- Download file 54.1 kB
-
https://huggingface.co/spaces/AaaTestosonet/Examplebonus33/resolve/main/app.py
- Command line
-
hf download hf://spaces/AaaTestosonet/Examplebonus33/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AaaTestosonet/Examplebonus33/resolve/main/app.py
54.1 kB
| #!/usr/bin/env python3 | |
| """Локальная панель управления Instagram через instagrapi. | |
| Важно: это НЕ публичный мост для ChatGPT и не выдаёт ссылку для удалённого | |
| управления. По умолчанию сервер привязан только к 127.0.0.1. Для запуска в | |
| публичном Hugging Face Space явно задайте PUBLIC_MODE=1 и длинный пароль панели. | |
| Пароль Instagram не сохраняется; зашифрованная сессия хранится отдельно от data.json | |
| и не отправляется в Hugging Face. | |
| Зависимости: | |
| python -m pip install flask instagrapi huggingface_hub cryptography | |
| Пример запуска (Linux/macOS): | |
| export DASHBOARD_PASSWORD='длинный-случайный-пароль-для-панели' | |
| export HF_TOKEN_READ='...' # необязательно, если data.json уже есть локально | |
| export HF_TOKEN_WRITE='...' # необязательно; включает резервную копию в HF | |
| python instagram_connector.py | |
| Локально откройте: http://127.0.0.1:7860/admhosto | |
| В Hugging Face Space панель доступна по адресу Space + /admhosto. | |
| В Space режим определяется по SPACE_ID автоматически; если платформа не задаёт эту | |
| переменную, добавьте Variable PUBLIC_MODE=1. Задайте Secret DASHBOARD_PASSWORD | |
| (случайная строка минимум 16 символов); порт по умолчанию 7860. | |
| Скрипт использует data.json и Hugging Face Dataset из исходного проекта. | |
| Если включена HF_TOKEN_WRITE, в HF отправляется весь data.json — как и в исходном | |
| приложении. Не включайте синхронизацию, пока не убедитесь, что репозиторий HF приватный. | |
| Не запускайте этот файл одновременно с исходным приложением, пишущим в тот же data.json. | |
| """ | |
| from __future__ import annotations | |
| import hmac | |
| import ipaddress | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import secrets | |
| import shutil | |
| import sys | |
| import tempfile | |
| from importlib.metadata import PackageNotFoundError, version as package_version | |
| import threading | |
| import time | |
| from collections import deque | |
| from datetime import datetime, timedelta, timezone | |
| from functools import wraps | |
| from pathlib import Path | |
| from typing import Any | |
| from cryptography.fernet import Fernet, InvalidToken | |
| from flask import ( | |
| Flask, | |
| abort, | |
| flash, | |
| redirect, | |
| render_template_string, | |
| request, | |
| session, | |
| url_for, | |
| ) | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from instagrapi import Client | |
| # ---------- Настройки: совместимы с исходным data.json / HF Dataset ---------- | |
| BASE_DIR = Path(__file__).resolve().parent | |
| def local_path(env_name: str, default_name: str) -> Path: | |
| value = Path(os.environ.get(env_name, default_name)).expanduser() | |
| return value if value.is_absolute() else BASE_DIR / value | |
| DATA_FILE = local_path("DATA_FILE", "data.json") | |
| SESSION_FILE = local_path("IG_SESSION_FILE", ".instagram_session.enc") | |
| SESSION_KEY_FILE = local_path("IG_SESSION_KEY_FILE", ".instagram_session.key") | |
| FLASK_SECRET_FILE = local_path("FLASK_SECRET_FILE", ".instagram_flask_secret") | |
| REPO_ID = os.getenv("HF_REPO_ID", "flpolprojects/examplebonus") | |
| HF_DATA_FILE_PATH = os.getenv("HF_DATA_FILE_PATH", "data.json") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") | |
| ALLOW_HF_WRITE_WITHOUT_READ = os.getenv("ALLOW_HF_WRITE_WITHOUT_READ", "").strip().lower() in {"1", "true", "yes"} | |
| _PUBLIC_MODE_ENV = os.getenv("PUBLIC_MODE") | |
| # В Space используем публичный bind автоматически; локально по умолчанию localhost. | |
| # Если платформа не задаёт SPACE_ID, задайте PUBLIC_MODE=1 вручную. | |
| PUBLIC_MODE = ( | |
| bool(os.getenv("SPACE_ID")) | |
| if _PUBLIC_MODE_ENV is None | |
| else _PUBLIC_MODE_ENV.strip().lower() in {"1", "true", "yes"} | |
| ) | |
| ADMIN_PATH = "/admhosto" | |
| HOST = "0.0.0.0" if PUBLIC_MODE else "127.0.0.1" | |
| PORT = int(os.getenv("PORT", "7860")) | |
| DASHBOARD_PASSWORD = os.getenv("DASHBOARD_PASSWORD", "") | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s %(levelname)s %(message)s", | |
| ) | |
| # Не записываем тела запросов и не выводим пароли/коды в журнал. | |
| logging.getLogger("werkzeug").setLevel(logging.WARNING) | |
| _store_lock = threading.RLock() | |
| _hf_upload_lock = threading.Lock() | |
| _instagram_lock = threading.RLock() | |
| _login_lock = threading.Lock() | |
| _login_job_lock = threading.RLock() | |
| _dm_lock = threading.Lock() | |
| _LOGIN_JOBS: dict[str, dict[str, Any]] = {} | |
| _ACTIVE_LOGIN_JOB_ID: str | None = None | |
| STORE: dict[str, Any] = {"instagram_connector": {"audit": []}} | |
| _HF_SYNC_SAFE = False | |
| _ACTIVE_CLIENT: Client | None = None | |
| _ACTIVE_USERNAME: str | None = None | |
| _LAST_DM_TIME = 0.0 | |
| _LOGIN_FAILURES: deque[float] = deque() | |
| # ---------- Безопасная запись файлов и JSON-хранилище ---------- | |
| def atomic_write(path: Path, content: bytes, mode: int = 0o600) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) | |
| try: | |
| if hasattr(os, "fchmod"): | |
| os.fchmod(fd, mode) | |
| with os.fdopen(fd, "wb") as handle: | |
| handle.write(content) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| os.replace(temp_name, path) | |
| try: | |
| os.chmod(path, mode) | |
| except OSError: | |
| pass | |
| finally: | |
| try: | |
| if os.path.exists(temp_name): | |
| os.unlink(temp_name) | |
| except OSError: | |
| pass | |
| def download_data_from_hf_if_needed() -> bool: | |
| """Загружает базу из HF и возвращает True только при успешном скачивании.""" | |
| if DATA_FILE.exists() or not HF_TOKEN_READ: | |
| return False | |
| try: | |
| logging.info("Локальной базы нет; пробую загрузить data.json из HF Dataset.") | |
| downloaded = hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=HF_DATA_FILE_PATH, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| ) | |
| DATA_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(downloaded, DATA_FILE) | |
| try: | |
| os.chmod(DATA_FILE, 0o600) | |
| except OSError: | |
| pass | |
| return True | |
| except Exception as exc: | |
| # Не печатаем URL, токены или содержимое исключения. | |
| logging.warning("Не удалось загрузить базу из HF (%s). Будет создана пустая.", type(exc).__name__) | |
| return False | |
| def load_store() -> None: | |
| global STORE, _HF_SYNC_SAFE | |
| if not DATA_FILE.exists(): | |
| download_data_from_hf_if_needed() | |
| loaded: dict[str, Any] = {} | |
| valid_local_data = False | |
| if DATA_FILE.exists(): | |
| try: | |
| with DATA_FILE.open("r", encoding="utf-8") as handle: | |
| value = json.load(handle) | |
| if isinstance(value, dict): | |
| loaded = value | |
| valid_local_data = True | |
| else: | |
| logging.warning("Корень data.json не является JSON-объектом; начну с пустого объекта.") | |
| except Exception as exc: | |
| logging.warning("Не удалось прочитать data.json (%s). Начну с пустого объекта.", type(exc).__name__) | |
| else: | |
| logging.info("data.json не найден; запись журнала отключена до успешной загрузки базы HF.") | |
| # Не перезаписываем удалённую базу пустым JSON, если HF вернул 401/ошибку. | |
| _HF_SYNC_SAFE = valid_local_data | |
| if HF_TOKEN_WRITE and not _HF_SYNC_SAFE and not ALLOW_HF_WRITE_WITHOUT_READ: | |
| logging.warning("HF-запись отключена: сначала исправьте HF_TOKEN_READ/доступ к репозиторию.") | |
| connector = loaded.get("instagram_connector") | |
| if not isinstance(connector, dict): | |
| connector = {} | |
| audit = connector.get("audit") | |
| if not isinstance(audit, list): | |
| connector["audit"] = [] | |
| loaded["instagram_connector"] = connector | |
| with _store_lock: | |
| STORE = loaded | |
| def upload_data_to_hf() -> None: | |
| """Резервирует полный data.json тем же HF Dataset, что и исходный проект.""" | |
| if not HF_TOKEN_WRITE or not DATA_FILE.exists(): | |
| return | |
| if not _HF_SYNC_SAFE and not ALLOW_HF_WRITE_WITHOUT_READ: | |
| logging.warning("HF-upload пропущен: удалённая база не была прочитана; защищаю её от перезаписи пустым JSON.") | |
| return | |
| with _hf_upload_lock: | |
| try: | |
| HfApi().upload_file( | |
| path_or_fileobj=str(DATA_FILE), | |
| path_in_repo=HF_DATA_FILE_PATH, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Update connector data {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}", | |
| ) | |
| logging.info("Резервная копия data.json отправлена в HF Dataset.") | |
| except Exception as exc: | |
| logging.warning("Не удалось отправить резервную копию в HF (%s).", type(exc).__name__) | |
| def schedule_hf_upload() -> None: | |
| if HF_TOKEN_WRITE: | |
| threading.Thread(target=upload_data_to_hf, daemon=True).start() | |
| def periodic_backup() -> None: | |
| if not HF_TOKEN_WRITE: | |
| return | |
| while True: | |
| time.sleep(3600) | |
| upload_data_to_hf() | |
| def record_event(action: str, success: bool) -> None: | |
| """Сохраняет только тип действия и результат — без текста сообщений и логинов.""" | |
| can_persist = _HF_SYNC_SAFE or ALLOW_HF_WRITE_WITHOUT_READ | |
| with _store_lock: | |
| connector = STORE.setdefault("instagram_connector", {}) | |
| if not isinstance(connector, dict): | |
| connector = {} | |
| STORE["instagram_connector"] = connector | |
| audit = connector.setdefault("audit", []) | |
| if not isinstance(audit, list): | |
| audit = [] | |
| connector["audit"] = audit | |
| audit.append( | |
| { | |
| "time": datetime.now(timezone.utc).isoformat(timespec="seconds"), | |
| "action": action, | |
| "success": bool(success), | |
| } | |
| ) | |
| del audit[:-300] | |
| if can_persist: | |
| content = json.dumps(STORE, ensure_ascii=False, indent=2).encode("utf-8") | |
| atomic_write(DATA_FILE, content) | |
| if can_persist: | |
| schedule_hf_upload() | |
| else: | |
| logging.warning("Журнал не сохранён: база HF не загружена. Исправьте HF_TOKEN_READ и перезапустите Space.") | |
| # ---------- Локальные секреты и зашифрованная Instagram-сессия ---------- | |
| def load_or_create_secret(path: Path, env_name: str) -> str: | |
| value = os.getenv(env_name) | |
| if value: | |
| return value | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| try: | |
| fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) | |
| with os.fdopen(fd, "wb") as handle: | |
| secret = secrets.token_bytes(32) | |
| handle.write(secret) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| except FileExistsError: | |
| pass | |
| except OSError as exc: | |
| raise RuntimeError(f"Не удалось создать локальный секрет {path.name}") from exc | |
| try: | |
| os.chmod(path, 0o600) | |
| except OSError: | |
| pass | |
| return path.read_bytes().hex() | |
| def get_fernet() -> Fernet: | |
| env_key = os.getenv("IG_SESSION_KEY") | |
| if env_key: | |
| key = env_key.strip().encode("ascii") | |
| else: | |
| SESSION_KEY_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| try: | |
| fd = os.open( | |
| str(SESSION_KEY_FILE), | |
| os.O_CREAT | os.O_EXCL | os.O_WRONLY, | |
| 0o600, | |
| ) | |
| with os.fdopen(fd, "wb") as handle: | |
| handle.write(Fernet.generate_key()) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| except FileExistsError: | |
| pass | |
| except OSError as exc: | |
| raise RuntimeError("Не удалось создать локальный ключ сессии") from exc | |
| try: | |
| os.chmod(SESSION_KEY_FILE, 0o600) | |
| except OSError: | |
| pass | |
| key = SESSION_KEY_FILE.read_bytes().strip() | |
| try: | |
| return Fernet(key) | |
| except Exception as exc: | |
| raise RuntimeError("IG_SESSION_KEY или локальный ключ сессии некорректен") from exc | |
| def remove_password_fields(value: Any) -> Any: | |
| """Защитная фильтрация на случай, если библиотека вернёт пароль в settings.""" | |
| forbidden = {"password", "passwd", "login_password"} | |
| if isinstance(value, dict): | |
| return { | |
| key: remove_password_fields(item) | |
| for key, item in value.items() | |
| if str(key).casefold() not in forbidden | |
| } | |
| if isinstance(value, list): | |
| return [remove_password_fields(item) for item in value] | |
| return value | |
| def load_saved_settings(username: str) -> dict[str, Any] | None: | |
| if not SESSION_FILE.exists(): | |
| return None | |
| try: | |
| payload = get_fernet().decrypt(SESSION_FILE.read_bytes()) | |
| document = json.loads(payload.decode("utf-8")) | |
| if str(document.get("username", "")).casefold() != username.casefold(): | |
| return None | |
| settings = document.get("settings") | |
| return settings if isinstance(settings, dict) else None | |
| except (InvalidToken, ValueError, OSError, json.JSONDecodeError): | |
| logging.warning("Не удалось расшифровать локальную сессию; войдите заново.") | |
| return None | |
| except Exception as exc: | |
| logging.warning("Не удалось прочитать локальную сессию (%s).", type(exc).__name__) | |
| return None | |
| def save_encrypted_settings(username: str, client: Client) -> None: | |
| settings = remove_password_fields(client.get_settings()) | |
| document = { | |
| "username": username, | |
| "settings": settings, | |
| "saved_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), | |
| } | |
| raw = json.dumps(document, ensure_ascii=False, separators=(",", ":")).encode("utf-8") | |
| encrypted = get_fernet().encrypt(raw) | |
| atomic_write(SESSION_FILE, encrypted, mode=0o600) | |
| # ---------- Flask и защита панели ---------- | |
| class AdminPrefixMiddleware: | |
| """Монтирует всё приложение под /admhosto, сохраняя корректный url_for().""" | |
| def __init__(self, application, prefix: str): | |
| self.application = application | |
| self.prefix = prefix.rstrip("/") | |
| def __call__(self, environ, start_response): | |
| path_info = environ.get("PATH_INFO", "") or "/" | |
| if path_info == self.prefix or path_info.startswith(self.prefix + "/"): | |
| suffix = path_info[len(self.prefix):] or "/" | |
| environ["PATH_INFO"] = suffix | |
| script_name = environ.get("SCRIPT_NAME", "") | |
| if not script_name.endswith(self.prefix): | |
| environ["SCRIPT_NAME"] = script_name + self.prefix | |
| return self.application(environ, start_response) | |
| if path_info in {"", "/"}: | |
| body = b"" | |
| start_response("302 Found", [("Location", self.prefix + "/"), ("Content-Length", "0"), ("Cache-Control", "no-store")]) | |
| return [body] | |
| body = b"Not Found" | |
| start_response("404 Not Found", [("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body)))]) | |
| return [body] | |
| app = Flask(__name__) | |
| app.wsgi_app = AdminPrefixMiddleware(app.wsgi_app, ADMIN_PATH) | |
| app.secret_key = load_or_create_secret(FLASK_SECRET_FILE, "FLASK_SECRET_KEY") | |
| app.config.update( | |
| SESSION_COOKIE_HTTPONLY=True, | |
| SESSION_COOKIE_SAMESITE="Lax", | |
| SESSION_COOKIE_PATH=ADMIN_PATH, | |
| SESSION_COOKIE_SECURE=PUBLIC_MODE, # в публичном Space cookie передаётся только по HTTPS | |
| PERMANENT_SESSION_LIFETIME=timedelta(hours=8), | |
| MAX_CONTENT_LENGTH=64 * 1024, | |
| ) | |
| def csrf_token() -> str: | |
| if "_csrf" not in session: | |
| session["_csrf"] = secrets.token_urlsafe(32) | |
| return str(session["_csrf"]) | |
| def enforce_localhost_and_csrf() -> None: | |
| # В обычном режиме принимаем запросы только с loopback. В PUBLIC_MODE | |
| # Space доступен извне, но все операции остаются за паролем панели и CSRF. | |
| if not PUBLIC_MODE: | |
| remote = request.remote_addr or "" | |
| try: | |
| if not ipaddress.ip_address(remote).is_loopback: | |
| abort(403) | |
| except ValueError: | |
| abort(403) | |
| if request.method in {"POST", "PUT", "PATCH", "DELETE"}: | |
| expected = str(session.get("_csrf", "")) | |
| supplied = request.form.get("csrf_token", "") or request.headers.get("X-CSRF-Token", "") | |
| if not expected or not hmac.compare_digest(expected, supplied): | |
| abort(400, "CSRF token is missing or invalid") | |
| def set_security_headers(response): | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| response.headers["X-Frame-Options"] = "DENY" | |
| response.headers["Referrer-Policy"] = "no-referrer" | |
| response.headers["Cache-Control"] = "no-store" | |
| response.headers["Content-Security-Policy"] = ( | |
| "default-src 'self'; style-src 'unsafe-inline'; img-src 'self' data:; " | |
| "script-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'" | |
| ) | |
| return response | |
| def admin_required(function): | |
| def wrapped(*args, **kwargs): | |
| if not session.get("admin_authenticated"): | |
| return redirect(url_for("panel_login")) | |
| return function(*args, **kwargs) | |
| return wrapped | |
| LOGIN_PAGE = r"""<!doctype html> | |
| <html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | |
| <title>Панель Instagram</title> | |
| <style> | |
| :root{color-scheme:dark;--bg:#101018;--card:#191924;--line:#30303c;--text:#f4f1f8;--muted:#b3adbd;--accent:#c13584;--accent2:#f77737} | |
| *{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 80% 0,#3e1740 0,transparent 38%),var(--bg);color:var(--text);font:16px system-ui,-apple-system,Segoe UI,sans-serif;min-height:100vh;display:grid;place-items:center;padding:20px} | |
| .card{width:min(100%,460px);background:rgba(25,25,36,.97);border:1px solid var(--line);border-radius:20px;padding:28px;box-shadow:0 20px 70px #0007}h1{margin:0 0 8px;font-size:25px}.muted{color:var(--muted);line-height:1.55}.warning{border:1px solid #795b29;background:#392e1b;color:#ffe3a1;padding:12px;border-radius:12px;margin:18px 0;font-size:14px} | |
| label{display:block;margin:16px 0 7px;font-weight:650}input{width:100%;background:#101018;border:1px solid var(--line);border-radius:10px;padding:12px;color:var(--text);font:inherit}button{width:100%;border:0;border-radius:10px;padding:12px;margin-top:18px;background:linear-gradient(100deg,var(--accent),var(--accent2));color:white;font-weight:750;font-size:16px;cursor:pointer}.flash{padding:10px 12px;border-radius:10px;background:#43252b;margin:10px 0} | |
| </style></head><body><main class="card"><h1>Локальная Instagram-панель</h1><p class="muted">{% if public_mode %}Вход в защищённую панель Instagram в Hugging Face Space.{% else %}Вход в панель управления, работающую только на этом компьютере.{% endif %}</p> | |
| <div class="warning">Не отправляйте ссылку, пароль панели, пароль Instagram или файлы сессии другим людям. Эта панель не подключает ChatGPT к аккаунту.</div> | |
| {% with messages = get_flashed_messages() %}{% for message in messages %}<div class="flash">{{ message }}</div>{% endfor %}{% endwith %} | |
| <form method="post" action="{{ url_for('panel_login') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"> | |
| <label for="password">Пароль панели</label><input id="password" name="password" type="password" required autocomplete="current-password"> | |
| <button type="submit">Войти</button></form></main></body></html>""" | |
| LOGIN_WAIT_PAGE = r"""<!doctype html> | |
| <html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | |
| {% if elapsed < 120 %}<meta http-equiv="refresh" content="4;url={{ poll_url }}">{% endif %} | |
| <title>Подключение Instagram</title> | |
| <style> | |
| :root{color-scheme:dark;--bg:#101018;--card:#191924;--line:#30303c;--text:#f4f1f8;--muted:#b3adbd;--accent:#c13584} | |
| *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:16px system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:20px}.card{width:min(100%,540px);background:var(--card);border:1px solid var(--line);border-radius:18px;padding:26px}.muted{color:var(--muted);line-height:1.55}.spinner{width:25px;height:25px;border:3px solid #ffffff30;border-top-color:var(--accent);border-radius:50%;animation:spin 1s linear infinite;display:inline-block;vertical-align:middle;margin-right:10px}@keyframes spin{to{transform:rotate(360deg)}}a{color:#f3a4d0} | |
| </style></head><body><main class="card"><h1><span class="spinner"></span>Подключаем Instagram</h1> | |
| <p>Запрос выполняется в фоне, страница не должна зависнуть. Первичная авторизация может занять до минуты.</p> | |
| <p class="muted">{{ message }}</p> | |
| {% if elapsed >= 120 %}<p class="muted">Вход длится уже {{ elapsed }} секунд. Возможно, Instagram не отвечает или ожидает challenge. Не отправляйте форму повторно; проверьте логи Space и затем обновите статус.</p>{% endif %} | |
| <p class="muted">Прошло {{ elapsed }} сек.</p><a href="{{ poll_url }}">Обновить статус</a> · <a href="{{ home_url }}">Вернуться в панель</a> | |
| </main></body></html>""" | |
| APP_PAGE = r"""<!doctype html> | |
| <html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | |
| <title>Instagram — локальная панель</title> | |
| <style> | |
| :root{color-scheme:dark;--bg:#101018;--card:#191924;--line:#30303c;--text:#f4f1f8;--muted:#b3adbd;--accent:#c13584;--accent2:#f77737;--green:#4ac08a;--red:#ff8585} | |
| *{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 88% -5%,#47183f 0,transparent 35%),var(--bg);color:var(--text);font:15px system-ui,-apple-system,Segoe UI,sans-serif;min-height:100vh} | |
| header{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:18px max(20px,calc((100vw - 1100px)/2));border-bottom:1px solid var(--line);background:#101018c9;position:sticky;top:0;backdrop-filter:blur(12px);z-index:2} | |
| .brand{font-weight:800;font-size:18px}.brand span{background:linear-gradient(100deg,#c13584,#f77737,#ffdc80);color:transparent;background-clip:text}.wrap{width:min(1100px,calc(100% - 32px));margin:24px auto 60px}.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}.card{background:rgba(25,25,36,.97);border:1px solid var(--line);border-radius:17px;padding:20px;box-shadow:0 12px 38px #0002}.wide{grid-column:1/-1}h1{margin:0 0 8px;font-size:24px}h2{font-size:18px;margin:0 0 14px}h3{font-size:15px;margin:0 0 8px}.muted{color:var(--muted);line-height:1.55}.status{display:inline-flex;gap:8px;align-items:center;padding:7px 11px;border-radius:999px;background:#252631;color:var(--muted);font-size:13px}.dot{width:8px;height:8px;border-radius:50%;background:var(--green)}.danger-dot{background:#777} | |
| label{display:block;font-weight:650;margin:12px 0 6px}input,textarea{width:100%;background:#101018;border:1px solid var(--line);border-radius:10px;padding:11px 12px;color:var(--text);font:inherit}textarea{resize:vertical;min-height:95px}input:focus,textarea:focus{outline:2px solid #c1358466;border-color:#c13584}button,.button{border:0;border-radius:10px;padding:10px 14px;margin-top:12px;background:linear-gradient(100deg,var(--accent),var(--accent2));color:white;font-weight:750;font:inherit;cursor:pointer;text-decoration:none;display:inline-block}button.secondary{background:#2a2a36;border:1px solid var(--line)}button.danger{background:#542832}.inline{display:inline}.flash{padding:11px 13px;border:1px solid #74424a;background:#39242a;border-radius:11px;margin:0 0 14px}.flash.success{border-color:#285d49;background:#1d372d}.warning{border:1px solid #70552c;background:#382f20;color:#ffe3a1;padding:12px 14px;border-radius:12px;line-height:1.5;margin:14px 0} | |
| .list{display:grid;gap:10px;margin-top:14px}.item{padding:13px;border:1px solid var(--line);border-radius:12px;background:#15151e}.item-top{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.title{font-weight:700}.small{font-size:13px;color:var(--muted);line-height:1.45}.message{border-bottom:1px solid var(--line);padding:10px 0;overflow-wrap:anywhere}.message:last-child{border-bottom:0}.sender{font-size:12px;color:#d4a4ca;font-weight:700}.check{display:flex;gap:9px;align-items:flex-start;font-weight:500;color:var(--muted);font-size:13px}.check input{width:auto;margin-top:3px}.bar{display:flex;gap:8px;align-items:center}.bar form{margin:0}.spacer{flex:1}.empty{color:var(--muted);padding:12px 0} | |
| @media(max-width:760px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}header{padding:14px 16px}.wrap{width:calc(100% - 22px);margin:14px auto 36px}.card{padding:16px}} | |
| </style></head><body> | |
| <header><div class="brand"><span>Instagram</span> · локальная панель</div><div class="bar"><span class="status"><i class="dot {{ ' ' if connected else 'danger-dot' }}"></i>{% if connected %}@{{ ig_username }} подключён{% else %}не подключён{% endif %}</span> | |
| <form method="post" action="{{ url_for('panel_logout') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="secondary" type="submit">Выйти из панели</button></form></div></header> | |
| <main class="wrap"> | |
| {% with messages = get_flashed_messages(with_categories=true) %}{% for category,message in messages %}<div class="flash {{ 'success' if category == 'success' else '' }}">{{ message }}</div>{% endfor %}{% endwith %} | |
| <div class="warning">{% if public_mode %}Это публичный Space: защищайте его паролем панели и не передавайте пароль третьим лицам. Он не подключает ChatGPT к аккаунту.{% else %}Панель доступна только на этом компьютере и не создаёт публичную ссылку.{% endif %} Instagrapi использует неофициальный интерфейс Instagram; возможны проверки безопасности или блокировка входа.</div> | |
| {% if not connected %} | |
| <section class="card"><h1>Подключить Instagram</h1><p class="muted">Введите данные только в локальной панели. Пароль используется для входа в памяти процесса и не записывается в data.json. Файл сессии хранится отдельно в зашифрованном виде.</p> | |
| <form method="post" action="{{ url_for('instagram_connect') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"> | |
| <label for="ig_username">Имя пользователя</label><input id="ig_username" name="ig_username" required maxlength="30" autocomplete="username" placeholder="username"> | |
| <label for="ig_password">Пароль Instagram</label><input id="ig_password" name="ig_password" type="password" required autocomplete="new-password"> | |
| <label for="verification_code">Код 2FA (если запрашивается)</label><input id="verification_code" name="verification_code" inputmode="numeric" maxlength="12" autocomplete="one-time-code" placeholder="необязательно"> | |
| <button type="submit">Войти в Instagram</button></form> | |
| <p class="small">Если Instagram запросит подтверждение устройства или challenge, завершите проверку в официальном приложении/на сайте и повторите вход.</p></section> | |
| {% else %} | |
| <div class="grid"> | |
| <section class="card"><h2>Входящие сообщения</h2><p class="muted">Загрузка последних 20 диалогов. Содержимое диалогов показывается только по отдельному нажатию.</p> | |
| <form method="post" action="{{ url_for('load_inbox') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button type="submit">Загрузить входящие</button></form> | |
| {% if inbox is defined %}{% if inbox %}<div class="list">{% for item in inbox %}<article class="item"><div class="item-top"><div><div class="title">{{ item.title }}</div><div class="small">{{ item.preview }}</div></div> | |
| <form method="post" action="{{ url_for('show_thread', thread_id=item.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="secondary" type="submit">Открыть</button></form></div></article>{% endfor %}</div>{% else %}<div class="empty">Диалогов не найдено.</div>{% endif %}{% endif %}</section> | |
| <section class="card"><h2>Поиск пользователей</h2><p class="muted">Поиск публичных профилей по имени пользователя или запросу.</p> | |
| <form method="post" action="{{ url_for('search_users') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><label for="query">Запрос</label><input id="query" name="query" maxlength="80" required placeholder="например, username"><button type="submit">Искать</button></form> | |
| {% if search_results is defined %}{% if search_results %}<div class="list">{% for user in search_results %}<article class="item"><div class="title">@{{ user.username }}</div><div class="small">{{ user.full_name }}</div></article>{% endfor %}</div>{% else %}<div class="empty">Совпадений не найдено.</div>{% endif %}{% endif %}</section> | |
| <section class="card"><h2>Отправить одно сообщение</h2><p class="muted">Только одному явно указанному пользователю за раз. Перед отправкой проверьте адресата и текст.</p> | |
| <form method="post" action="{{ url_for('send_dm') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><label for="recipient">Получатель</label><input id="recipient" name="recipient" maxlength="31" required placeholder="@username"><label for="message_text">Текст сообщения</label><textarea id="message_text" name="message_text" maxlength="1000" required></textarea> | |
| <label class="check"><input type="checkbox" name="confirm_send" value="yes" required><span>Я проверил(а) получателя и подтверждаю отправку этого сообщения.</span></label><button type="submit">Отправить DM</button></form></section> | |
| <section class="card"><h2>Отключить Instagram</h2><p class="muted">Выйти из Instagram-сессии на сервере панели и удалить сохранённую зашифрованную сессию.</p> | |
| <form method="post" action="{{ url_for('instagram_disconnect') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><label class="check"><input type="checkbox" name="confirm_disconnect" value="yes" required><span>Подтверждаю отключение.</span></label><button class="danger" type="submit">Отключить и удалить сессию</button></form></section> | |
| {% if thread is defined %}<section class="card wide"><div class="item-top"><div><h2>Диалог: {{ thread.title }}</h2><div class="small">ID диалога: {{ thread.id }}</div></div></div> | |
| {% if thread.messages %}<div class="list">{% for message in thread.messages %}<article class="message"><div class="sender">{{ message.sender }}{% if message.time %} · {{ message.time }}{% endif %}</div><div>{{ message.text }}</div></article>{% endfor %}</div>{% else %}<div class="empty">Сообщений не найдено.</div>{% endif %} | |
| <form method="post" action="{{ url_for('reply_thread', thread_id=thread.id) }}"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><label for="reply_text">Ответить в этом диалоге</label><textarea id="reply_text" name="message_text" maxlength="1000" required></textarea><label class="check"><input type="checkbox" name="confirm_send" value="yes" required><span>Я проверил(а) этот диалог и подтверждаю отправку ответа.</span></label><button type="submit">Отправить ответ</button></form></section>{% endif %} | |
| </div> | |
| {% endif %} | |
| <p class="small" style="margin:16px 2px">Сохраняется только журнал типа действия и результата. Текст сообщений, пароль и сессия в data.json не записываются.</p> | |
| </main></body></html>""" | |
| def render_dashboard(**context): | |
| with _instagram_lock: | |
| connected = _ACTIVE_CLIENT is not None | |
| username = _ACTIVE_USERNAME or "" | |
| defaults = { | |
| "csrf_token": csrf_token(), | |
| "connected": connected, | |
| "ig_username": username, | |
| "public_mode": PUBLIC_MODE, | |
| } | |
| defaults.update(context) | |
| return render_template_string(APP_PAGE, **defaults) | |
| def get_attr(obj: Any, name: str, default: Any = None) -> Any: | |
| if isinstance(obj, dict): | |
| return obj.get(name, default) | |
| return getattr(obj, name, default) | |
| def object_id(obj: Any) -> str | None: | |
| value = get_attr(obj, "id") or get_attr(obj, "thread_id") or get_attr(obj, "pk") | |
| if value is None: | |
| return None | |
| result = str(value) | |
| return result if result.isdigit() else None | |
| def thread_summary(thread: Any) -> dict[str, str] | None: | |
| thread_id = object_id(thread) | |
| if not thread_id: | |
| return None | |
| users = get_attr(thread, "users", []) or [] | |
| usernames = [str(get_attr(user, "username", "")).strip() for user in users] | |
| usernames = [name for name in usernames if name] | |
| title = get_attr(thread, "thread_title") or (", ".join("@" + name for name in usernames) if usernames else "Диалог") | |
| messages = get_attr(thread, "messages", []) or [] | |
| last = messages[0] if messages else None | |
| preview = get_attr(last, "text", "") if last is not None else "" | |
| if not preview and last is not None: | |
| preview = "[вложение или сообщение без текста]" | |
| return {"id": thread_id, "title": str(title), "preview": str(preview)[:220]} | |
| def thread_for_display(thread_id: int, thread: Any, client: Client) -> dict[str, Any]: | |
| users = get_attr(thread, "users", []) or [] | |
| user_names: dict[str, str] = {} | |
| for user in users: | |
| uid = get_attr(user, "pk") or get_attr(user, "id") | |
| uname = get_attr(user, "username") | |
| if uid is not None and uname: | |
| user_names[str(uid)] = "@" + str(uname) | |
| my_id = str(getattr(client, "user_id", "")) | |
| messages = get_attr(thread, "messages", []) or [] | |
| shown: list[dict[str, str]] = [] | |
| for item in list(messages)[:40]: | |
| sender_id = str(get_attr(item, "user_id", "")) | |
| sender = "Я" if sender_id and sender_id == my_id else user_names.get(sender_id, "Собеседник") | |
| text = get_attr(item, "text", "") or "" | |
| if not text: | |
| kind = get_attr(item, "item_type", "вложение") or "вложение" | |
| text = f"[{kind}]" | |
| stamp = get_attr(item, "timestamp", "") or "" | |
| if isinstance(stamp, datetime): | |
| stamp = stamp.isoformat(timespec="minutes") | |
| shown.append({"sender": sender, "text": str(text)[:4000], "time": str(stamp)[:80]}) | |
| title = get_attr(thread, "thread_title") or ", ".join("@" + str(get_attr(u, "username", "")) for u in users if get_attr(u, "username")) or "Диалог" | |
| return {"id": str(thread_id), "title": str(title), "messages": shown} | |
| # ---------- Панель ---------- | |
| def panel_login(): | |
| if session.get("admin_authenticated"): | |
| return redirect(url_for("home")) | |
| if request.method == "POST": | |
| now = time.monotonic() | |
| with _login_lock: | |
| while _LOGIN_FAILURES and now - _LOGIN_FAILURES[0] > 60: | |
| _LOGIN_FAILURES.popleft() | |
| locked = len(_LOGIN_FAILURES) >= 5 | |
| supplied = request.form.get("password", "") | |
| if not locked and DASHBOARD_PASSWORD and hmac.compare_digest(supplied, DASHBOARD_PASSWORD): | |
| session.clear() | |
| session.permanent = True | |
| session["admin_authenticated"] = True | |
| session["_csrf"] = secrets.token_urlsafe(32) | |
| return redirect(url_for("home")) | |
| with _login_lock: | |
| _LOGIN_FAILURES.append(now) | |
| flash("Неверный пароль панели или временная блокировка после неудачных попыток.") | |
| return render_template_string(LOGIN_PAGE, csrf_token=csrf_token(), public_mode=PUBLIC_MODE) | |
| def panel_logout(): | |
| session.clear() | |
| return redirect(url_for("panel_login")) | |
| def home(): | |
| return render_dashboard() | |
| def update_login_job(job_id: str, state: str, message: str) -> None: | |
| with _login_job_lock: | |
| job = _LOGIN_JOBS.get(job_id) | |
| if job is not None: | |
| job["state"] = state | |
| job["message"] = message | |
| job["updated"] = time.time() | |
| def instagram_login_worker(job_id: str, username: str, password: str, verification_code: str) -> None: | |
| """Выполняет сетевой вход вне Flask-запроса, чтобы браузер не висел.""" | |
| global _ACTIVE_CLIENT, _ACTIVE_USERNAME | |
| try: | |
| update_login_job(job_id, "running", "Связываемся с Instagram. Не отправляйте форму повторно.") | |
| # Настройки retry/timeout передаём при создании Client: после создания | |
| # библиотека уже монтирует HTTP adapters и изменение атрибутов не всегда | |
| # меняет их retry-политику (в логах это выглядело как паузы примерно по минуте). | |
| settings = dict(load_saved_settings(username) or {}) | |
| settings.update({ | |
| "request_timeout": 20, | |
| "public_request_retries_count": 0, | |
| "public_request_retries_timeout": 0, | |
| "session_retry_total": 0, | |
| "session_retry_backoff_factor": 0, | |
| }) | |
| client = Client(settings=settings) | |
| update_login_job(job_id, "running", "Instagram обрабатывает запрос авторизации…") | |
| if verification_code: | |
| success = client.login(username, password, verification_code=verification_code) | |
| else: | |
| success = client.login(username, password) | |
| if not success: | |
| raise RuntimeError("login returned false") | |
| update_login_job(job_id, "running", "Вход выполнен; сохраняю зашифрованную сессию…") | |
| save_encrypted_settings(username, client) | |
| with _instagram_lock: | |
| _ACTIVE_CLIENT = client | |
| _ACTIVE_USERNAME = username | |
| try: | |
| record_event("connect", True) | |
| except Exception as exc: | |
| logging.warning("Не удалось сохранить журнал входа (%s).", type(exc).__name__) | |
| update_login_job(job_id, "done", f"Instagram подключён как @{username}.") | |
| except Exception as exc: | |
| # Текст исключения не выводим, чтобы случайно не раскрыть чувствительные данные. | |
| error_type = type(exc).__name__ | |
| logging.warning("Ошибка входа Instagram (%s).", error_type) | |
| try: | |
| record_event("connect", False) | |
| except Exception: | |
| pass | |
| update_login_job( | |
| job_id, | |
| "error", | |
| f"Вход не завершился ({error_type}). Проверьте пароль, 2FA/challenge и доступ Space к Instagram; подробности — в логах Space.", | |
| ) | |
| finally: | |
| # Пароль и одноразовый код используются только в памяти рабочего потока. | |
| password = "" | |
| verification_code = "" | |
| def instagram_connect(): | |
| global _ACTIVE_LOGIN_JOB_ID | |
| username = request.form.get("ig_username", "").strip().lstrip("@") | |
| password = request.form.get("ig_password", "") | |
| verification_code = request.form.get("verification_code", "").strip() | |
| if not re.fullmatch(r"[A-Za-z0-9._]{1,30}", username) or not password: | |
| flash("Проверьте имя пользователя и пароль.", "error") | |
| return redirect(url_for("home")) | |
| with _login_job_lock: | |
| active_id = _ACTIVE_LOGIN_JOB_ID | |
| if active_id and _LOGIN_JOBS.get(active_id, {}).get("state") == "running": | |
| password = "" | |
| verification_code = "" | |
| return redirect(url_for("instagram_login_status", job_id=active_id)) | |
| now = time.time() | |
| for old_id, old_job in list(_LOGIN_JOBS.items()): | |
| if old_job.get("state") != "running" and now - old_job.get("started", now) > 3600: | |
| _LOGIN_JOBS.pop(old_id, None) | |
| job_id = secrets.token_urlsafe(18) | |
| _LOGIN_JOBS[job_id] = { | |
| "state": "running", | |
| "message": "Подготавливаю подключение…", | |
| "started": now, | |
| "updated": now, | |
| "username": username, | |
| } | |
| _ACTIVE_LOGIN_JOB_ID = job_id | |
| worker = threading.Thread( | |
| target=instagram_login_worker, | |
| args=(job_id, username, password, verification_code), | |
| daemon=True, | |
| name="instagram-login", | |
| ) | |
| worker.start() | |
| password = "" | |
| verification_code = "" | |
| return redirect(url_for("instagram_login_status", job_id=job_id)) | |
| def instagram_login_status(job_id: str): | |
| with _login_job_lock: | |
| job = dict(_LOGIN_JOBS.get(job_id, {})) | |
| if not job: | |
| abort(404) | |
| if job.get("state") == "done": | |
| flash(job.get("message", "Instagram подключён."), "success") | |
| return redirect(url_for("home")) | |
| if job.get("state") == "error": | |
| flash(job.get("message", "Вход не завершился."), "error") | |
| return redirect(url_for("home")) | |
| elapsed = max(0, int(time.time() - job.get("started", time.time()))) | |
| return render_template_string( | |
| LOGIN_WAIT_PAGE, | |
| elapsed=elapsed, | |
| message=job.get("message", "Ожидаю ответ Instagram…"), | |
| poll_url=url_for("instagram_login_status", job_id=job_id), | |
| home_url=url_for("home"), | |
| ) | |
| def instagram_disconnect(): | |
| global _ACTIVE_CLIENT, _ACTIVE_USERNAME | |
| if request.form.get("confirm_disconnect") != "yes": | |
| flash("Отключение не подтверждено.", "error") | |
| return redirect(url_for("home")) | |
| logout_ok = True | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is not None: | |
| try: | |
| client.logout() | |
| except Exception as exc: | |
| logout_ok = False | |
| logging.warning("Instagram logout завершился ошибкой (%s).", type(exc).__name__) | |
| _ACTIVE_CLIENT = None | |
| _ACTIVE_USERNAME = None | |
| try: | |
| SESSION_FILE.unlink(missing_ok=True) | |
| except OSError: | |
| logout_ok = False | |
| record_event("disconnect", logout_ok) | |
| flash("Локальная сессия отключена и удалена." if logout_ok else "Локальная сессия удалена; Instagram мог не принять запрос выхода.", "success" if logout_ok else "error") | |
| return redirect(url_for("home")) | |
| def load_inbox(): | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is None: | |
| flash("Сначала подключите Instagram.", "error") | |
| return redirect(url_for("home")) | |
| try: | |
| threads = client.direct_threads(amount=20) | |
| inbox = [summary for summary in (thread_summary(item) for item in threads) if summary] | |
| except Exception as exc: | |
| logging.warning("Ошибка чтения входящих (%s).", type(exc).__name__) | |
| record_event("inbox_read", False) | |
| flash("Не удалось загрузить входящие. Возможно, Instagram запросил повторную проверку.", "error") | |
| return render_dashboard(inbox=[]) | |
| record_event("inbox_read", True) | |
| return render_dashboard(inbox=inbox) | |
| def search_users(): | |
| query = request.form.get("query", "").strip() | |
| if not query or len(query) > 80: | |
| flash("Введите запрос длиной до 80 символов.", "error") | |
| return redirect(url_for("home")) | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is None: | |
| flash("Сначала подключите Instagram.", "error") | |
| return redirect(url_for("home")) | |
| try: | |
| found = client.search_users(query) | |
| results = [] | |
| for user in list(found)[:25]: | |
| username = str(get_attr(user, "username", "") or "") | |
| if username: | |
| results.append({ | |
| "username": username[:30], | |
| "full_name": str(get_attr(user, "full_name", "") or "")[:100], | |
| }) | |
| except Exception as exc: | |
| logging.warning("Ошибка поиска Instagram (%s).", type(exc).__name__) | |
| record_event("user_search", False) | |
| flash("Не удалось выполнить поиск.", "error") | |
| return render_dashboard(search_results=[]) | |
| record_event("user_search", True) | |
| return render_dashboard(search_results=results) | |
| def allow_one_dm() -> bool: | |
| global _LAST_DM_TIME | |
| with _dm_lock: | |
| now = time.monotonic() | |
| if now - _LAST_DM_TIME < 10: | |
| return False | |
| _LAST_DM_TIME = now | |
| return True | |
| def send_dm(): | |
| target = request.form.get("recipient", "").strip().lstrip("@").strip() | |
| text = request.form.get("message_text", "").strip() | |
| if request.form.get("confirm_send") != "yes": | |
| flash("Отправка не подтверждена.", "error") | |
| return redirect(url_for("home")) | |
| if not re.fullmatch(r"[A-Za-z0-9._]{1,30}", target) or not text or len(text) > 1000: | |
| flash("Укажите одного получателя и текст сообщения до 1000 символов.", "error") | |
| return redirect(url_for("home")) | |
| if not allow_one_dm(): | |
| flash("Подождите не менее 10 секунд перед следующей отправкой.", "error") | |
| return redirect(url_for("home")) | |
| try: | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is None: | |
| flash("Сначала подключите Instagram.", "error") | |
| return redirect(url_for("home")) | |
| user_id = client.user_id_from_username(target) | |
| client.direct_send(text, user_ids=[user_id]) | |
| record_event("dm_send", True) | |
| flash("Сообщение отправлено одному выбранному получателю.", "success") | |
| except Exception as exc: | |
| logging.warning("Ошибка отправки DM (%s).", type(exc).__name__) | |
| record_event("dm_send", False) | |
| flash("Не удалось отправить сообщение. Проверьте имя пользователя и состояние аккаунта.", "error") | |
| finally: | |
| text = "" | |
| return redirect(url_for("home")) | |
| def show_thread(thread_id: str): | |
| if not thread_id.isdigit(): | |
| abort(404) | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is None: | |
| flash("Сначала подключите Instagram.", "error") | |
| return redirect(url_for("home")) | |
| try: | |
| raw_thread = client.direct_thread(int(thread_id), amount=40) | |
| result = thread_for_display(int(thread_id), raw_thread, client) | |
| except Exception as exc: | |
| logging.warning("Ошибка чтения диалога (%s).", type(exc).__name__) | |
| record_event("thread_read", False) | |
| flash("Не удалось открыть диалог.", "error") | |
| return redirect(url_for("home")) | |
| record_event("thread_read", True) | |
| return render_dashboard(thread=result) | |
| def reply_thread(thread_id: str): | |
| if not thread_id.isdigit(): | |
| abort(404) | |
| text = request.form.get("message_text", "").strip() | |
| if request.form.get("confirm_send") != "yes": | |
| flash("Отправка не подтверждена.", "error") | |
| return redirect(url_for("home")) | |
| if not text or len(text) > 1000: | |
| flash("Введите текст ответа длиной до 1000 символов.", "error") | |
| return redirect(url_for("home")) | |
| if not allow_one_dm(): | |
| flash("Подождите не менее 10 секунд перед следующей отправкой.", "error") | |
| return redirect(url_for("home")) | |
| try: | |
| with _instagram_lock: | |
| client = _ACTIVE_CLIENT | |
| if client is None: | |
| flash("Сначала подключите Instagram.", "error") | |
| return redirect(url_for("home")) | |
| client.direct_answer(int(thread_id), text) | |
| raw_thread = client.direct_thread(int(thread_id), amount=40) | |
| result = thread_for_display(int(thread_id), raw_thread, client) | |
| record_event("dm_reply", True) | |
| flash("Ответ отправлен.", "success") | |
| return render_dashboard(thread=result) | |
| except Exception as exc: | |
| logging.warning("Ошибка ответа в DM (%s).", type(exc).__name__) | |
| record_event("dm_reply", False) | |
| flash("Не удалось отправить ответ.", "error") | |
| finally: | |
| text = "" | |
| return redirect(url_for("home")) | |
| def main() -> None: | |
| if len(DASHBOARD_PASSWORD) < 16: | |
| raise SystemExit( | |
| "Задайте переменную окружения DASHBOARD_PASSWORD длиной минимум 16 символов. " | |
| "Не вписывайте пароль в исходный код." | |
| ) | |
| load_store() | |
| try: | |
| installed_instagrapi = package_version("instagrapi") | |
| except PackageNotFoundError: | |
| installed_instagrapi = "unknown" | |
| logging.info("Runtime Python %s; instagrapi %s", sys.version.split()[0], installed_instagrapi) | |
| if HF_TOKEN_WRITE: | |
| threading.Thread(target=periodic_backup, daemon=True).start() | |
| if PUBLIC_MODE: | |
| logging.warning("Публичный режим включён: защищайте Space секретом DASHBOARD_PASSWORD.") | |
| logging.info("Слушаю 0.0.0.0:%s; панель смонтирована на %s", PORT, ADMIN_PATH) | |
| else: | |
| logging.info("Локальная панель: http://127.0.0.1:%s%s", PORT, ADMIN_PATH) | |
| logging.info("Пароли и тексты сообщений не записываются в журнал приложения.") | |
| app.run(host=HOST, port=PORT, debug=False, use_reloader=False, threaded=True) | |
| if __name__ == "__main__": | |
| main() | |