| 1 | from __future__ import annotations |
| 2 | |
| 3 | import importlib |
| 4 | import importlib.util |
| 5 | import shutil |
| 6 | import subprocess |
| 7 | import sys |
| 8 | import threading |
| 9 | from pathlib import Path |
| 10 | |
| 11 | from helpers.errors import format_error |
| 12 | from helpers.print_style import PrintStyle |
| 13 | |
| 14 | |
| 15 | _LOCK = threading.Lock() |
| 16 | _CHECKED = False |
| 17 | _PLUGIN_DIR = Path(__file__).resolve().parents[1] |
| 18 | _REQUIREMENTS_FILE = _PLUGIN_DIR / "requirements.txt" |
| 19 | |
| 20 | |
| 21 | def has_aiogram() -> bool: |
| 22 | return importlib.util.find_spec("aiogram") is not None |
| 23 | |
| 24 | |
| 25 | def ensure_dependencies() -> None: |
| 26 | global _CHECKED |
| 27 | |
| 28 | if _CHECKED and has_aiogram(): |
| 29 | return |
| 30 | |
| 31 | with _LOCK: |
| 32 | if _CHECKED and has_aiogram(): |
| 33 | return |
| 34 | if has_aiogram(): |
| 35 | _CHECKED = True |
| 36 | return |
| 37 | |
| 38 | _install_aiogram() |
| 39 | importlib.invalidate_caches() |
| 40 | |
| 41 | if not has_aiogram(): |
| 42 | raise RuntimeError("Telegram dependency 'aiogram' is still unavailable after installation") |
| 43 | |
| 44 | _CHECKED = True |
| 45 | |
| 46 | |
| 47 | def _install_aiogram() -> None: |
| 48 | uv = shutil.which("uv") |
| 49 | if not uv: |
| 50 | raise RuntimeError("Telegram plugin requires 'uv' to install aiogram automatically") |
| 51 | if not _REQUIREMENTS_FILE.is_file(): |
| 52 | raise RuntimeError(f"Telegram plugin requirements file not found: {_REQUIREMENTS_FILE}") |
| 53 | |
| 54 | cmd = [ |
| 55 | uv, |
| 56 | "pip", |
| 57 | "install", |
| 58 | "--python", |
| 59 | sys.executable, |
| 60 | "-r", |
| 61 | str(_REQUIREMENTS_FILE), |
| 62 | ] |
| 63 | |
| 64 | PrintStyle.info("Telegram: aiogram not found, installing plugin dependency") |
| 65 | try: |
| 66 | subprocess.check_call(cmd, cwd=str(_PLUGIN_DIR)) |
| 67 | except Exception as e: |
| 68 | raise RuntimeError(f"Failed to install Telegram dependency 'aiogram': {format_error(e)}") from e |