# -*- coding: utf-8 -*- """ ================================================================================ 💫 BUNKER NEON LOADER v1.3.1 — CRASH-PROOF & FULL-COLOR EDITION ================================================================================ Автор: Бункер Кота (@BUNKER_K0TA / @k0tlux) Версия: 1.3.1 Назначение: Ультимативная кастомизация лоадеров, спиннеров и кнопок загрузки медиа (фото, видео, кружочки Video Notes, файлы) в чатах. Неоновые цвета, плавная RGB-радуга, iOS-минимализм, настраиваемая толщина кольца, OLED-подложка. Совместимость: AyuGram / ExteraGram / NimarkoGram / NekoX. ================================================================================ """ import math import os import re import threading import time import urllib.request from typing import Any, List, Optional, Tuple # Android SDK & Java bridge from android.content import ClipData, Context from android.graphics import Color, Paint from android.os import SystemClock from android.widget import Toast from android_utils import log, run_on_ui_thread from base_plugin import BasePlugin, MethodHook from hook_utils import find_class, get_private_field from java import jarray from org.telegram.messenger import AndroidUtilities, ApplicationLoader from ui.settings import Divider, Header, Selector, Switch, Text __id__ = "bunker_neon_loader" __name__ = "Bunker Neon Loader 💫" __description__ = ( "Кастомный лоадер и спиннер загрузки медиа (фото, видео, кружочки) в стиле " "Неон, RGB-Радуга, iOS Minimal, Sunset и Cyberpunk. 100% совместимость." ) __author__ = "@k0tlux & Бункер Кота" __version__ = "1.3.1" __icon__ = "bunker_plugins/loader" __min_version__ = "11.10.0" UPDATE_URL_GITHUB = "https://raw.githubusercontent.com/ANT1VEN0M/Bunker-Auto-Engine/main/plugins/bunker_neon_loader.plugin" UPDATE_URL_MIRROR = "https://ghfast.top/https://raw.githubusercontent.com/ANT1VEN0M/Bunker-Auto-Engine/main/plugins/bunker_neon_loader.plugin" REPO_URL = "https://raw.githubusercontent.com/ANT1VEN0M/Bunker-Auto-Engine/main/extera-plugins.json" def _log(msg: str): try: log(f"[BunkerLoader] {msg}") except Exception: pass def safe_notify(msg: str): """Отображает всплывающее уведомление (Toast) на главном UI-потоке.""" try: def _toast(): try: ctx = ApplicationLoader.applicationContext if ctx: Toast.makeText(ctx, str(msg), Toast.LENGTH_SHORT).show() except Exception: pass run_on_ui_thread(_toast) except Exception: _log(f"Notify: {msg}") def _to_signed_32(val: int) -> int: """Преобразует 32-битное число в знаковый int для Java/Android.""" val = val & 0xFFFFFFFF if val >= 0x80000000: val -= 0x100000000 return int(val) def _hsv_to_argb(h: float, s: float, v: float, a: int = 255) -> int: """Чистый генератор ARGB цвета из HSV без зависимости от сторонних библиотек.""" h = (float(h) % 360.0) / 60.0 i = int(h) f = h - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) if i == 0: r, g, b = v, t, p elif i == 1: r, g, b = q, v, p elif i == 2: r, g, b = p, v, t elif i == 3: r, g, b = p, q, v elif i == 4: r, g, b = t, p, v else: r, g, b = v, p, q ir = int(r * 255.0) & 0xFF ig = int(g * 255.0) & 0xFF ib = int(b * 255.0) & 0xFF ia = int(a) & 0xFF raw = (ia << 24) | (ir << 16) | (ig << 8) | ib return _to_signed_32(raw) # ============================================================================== # ХУКИ ДЛЯ RadialProgress2 (Основной контейнер ChatMessageCell: фото, видео, кружки) # ============================================================================== class RadialProgress2DrawHook(MethodHook): """ Перехватывает RadialProgress2.draw(Canvas). Применяет кастомные цвета непосредственно перед отрисовкой в чате. """ def __init__(self, plugin: "BunkerNeonLoaderPlugin"): super().__init__() self.plugin = plugin def before_hooked_method(self, param): if not self.plugin.is_enabled(): return try: rp2 = param.thisObject if rp2 is None: return color = self.plugin.get_current_color() backdrop = self.plugin.get_backdrop_color() # 1. Устанавливаем цвета в объект RadialProgress2 try: rp2.setColors(backdrop, backdrop, color, color) except Exception: pass # 2. Настраиваем circlePaint подложки try: cp = rp2.circlePaint except Exception: cp = get_private_field(rp2, "circlePaint") if cp is not None: cp.setColor(backdrop) # 3. Настраиваем толщину и круглые концы для MediaActionDrawable try: mad = None try: mad = rp2.getMediaActionDrawable() except Exception: pass if mad is None: try: mad = rp2.mediaActionDrawable except Exception: mad = get_private_field(rp2, "mediaActionDrawable") if mad is not None: try: mad.setColor(color) except Exception: pass try: mad.setBackColor(backdrop) except Exception: pass p = None try: p = mad.paint except Exception: p = get_private_field(mad, "paint") if p is not None: p.setStyle(Paint.Style.STROKE) p.setStrokeCap(Paint.Cap.ROUND) p.setStrokeWidth(self.plugin.get_stroke_width()) p.setColor(color) try: p.clearShadowLayer() except Exception: pass except Exception: pass except Exception: pass class RadialProgress2SetColorsHook(MethodHook): """Перехватывает попытки Telegram установить цвета через setColors.""" def __init__(self, plugin: "BunkerNeonLoaderPlugin"): super().__init__() self.plugin = plugin def before_hooked_method(self, param): if not self.plugin.is_enabled(): return try: color = self.plugin.get_current_color() backdrop = self.plugin.get_backdrop_color() if param.args is not None and len(param.args) >= 4: param.args[0] = backdrop param.args[1] = backdrop param.args[2] = color param.args[3] = color except Exception: pass class RadialProgress2SetColorKeysHook(MethodHook): """ Срабатывает ПОСЛЕ того, как Telegram привязал ключи темы через setColorKeys. Возвращает наши цвета обратно без опасной подмены ключей на -1. """ def __init__(self, plugin: "BunkerNeonLoaderPlugin"): super().__init__() self.plugin = plugin def after_hooked_method(self, param): if not self.plugin.is_enabled(): return try: rp2 = param.thisObject if rp2 is None: return color = self.plugin.get_current_color() backdrop = self.plugin.get_backdrop_color() try: rp2.setColors(backdrop, backdrop, color, color) except Exception: pass except Exception: pass # ============================================================================== # ХУКИ ДЛЯ RadialProgressView (Полноэкранный просмотрщик PhotoViewer и диалоги) # ============================================================================== class RadialProgressViewDrawHook(MethodHook): """Перехватывает отрисовку современного RadialProgressView (PhotoViewer, профили).""" def __init__(self, plugin: "BunkerNeonLoaderPlugin"): super().__init__() self.plugin = plugin def before_hooked_method(self, param): if not self.plugin.is_enabled(): return try: rpv = param.thisObject if rpv is None: return color = self.plugin.get_current_color() stroke_width = self.plugin.get_stroke_width() try: rpv.setProgressColor(color) except Exception: pass try: paint = rpv.progressPaint except Exception: paint = get_private_field(rpv, "progressPaint") if paint is not None: paint.setColor(color) paint.setStrokeCap(Paint.Cap.ROUND) paint.setStrokeWidth(stroke_width) try: paint.clearShadowLayer() except Exception: pass except Exception: pass # ============================================================================== # ГЛАВНЫЙ КЛАСС ПЛАГИНА # ============================================================================== class BunkerNeonLoaderPlugin(BasePlugin): """Основной класс плагина Bunker Neon Loader.""" STYLE_RGB_RAINBOW = 0 STYLE_NEON_CYAN = 1 STYLE_IOS_MINIMAL = 2 STYLE_SUNSET_FIRE = 3 STYLE_EMERALD_MATRIX = 4 STYLE_PURPLE_VELVET = 5 STYLE_ELECTRIC_GOLD = 6 def __init__(self): super().__init__() self._hooks = [] self._alive = False def is_enabled(self) -> bool: if not self._alive: return False val = self.get_setting("enabled", True) if isinstance(val, bool): return val if isinstance(val, str): return val.lower() in ("true", "1", "yes") if isinstance(val, (int, float)): return bool(val) return True def get_style(self) -> int: """Безопасно извлекает выбранный стиль как целочисленный индекс.""" val = self.get_setting("style", self.STYLE_RGB_RAINBOW) if isinstance(val, int): return val if isinstance(val, str): val_s = val.strip() if val_s.isdigit(): return int(val_s) if "Радуга" in val_s or "RGB" in val_s: return self.STYLE_RGB_RAINBOW elif "Киберпанк" in val_s or "Cyan" in val_s: return self.STYLE_NEON_CYAN elif "iOS" in val_s: return self.STYLE_IOS_MINIMAL elif "закат" in val_s or "Sunset" in val_s: return self.STYLE_SUNSET_FIRE elif "Изумруд" in val_s or "Matrix" in val_s or "Emerald" in val_s: return self.STYLE_EMERALD_MATRIX elif "Аметист" in val_s or "Purple" in val_s or "Velvet" in val_s: return self.STYLE_PURPLE_VELVET elif "янтарь" in val_s or "Gold" in val_s: return self.STYLE_ELECTRIC_GOLD return self.STYLE_RGB_RAINBOW def on_plugin_load(self): self._alive = True _log(f"Bunker Neon Loader v{__version__} loading...") # 1. Хуки RadialProgress2 (ChatMessageCell) try: rp2_cls = find_class("org.telegram.ui.Components.RadialProgress2") if rp2_cls is not None: h_draw = self.hook_all_methods(rp2_cls, "draw", RadialProgress2DrawHook(self)) if h_draw: self._hooks.extend(h_draw) h_colors = self.hook_all_methods(rp2_cls, "setColors", RadialProgress2SetColorsHook(self)) if h_colors: self._hooks.extend(h_colors) h_keys = self.hook_all_methods(rp2_cls, "setColorKeys", RadialProgress2SetColorKeysHook(self)) if h_keys: self._hooks.extend(h_keys) _log("RadialProgress2 hooked successfully") except Exception as e: _log(f"Failed to hook RadialProgress2: {e}") # 2. Хуки RadialProgressView (PhotoViewer) try: rpv_cls = find_class("org.telegram.ui.Components.RadialProgressView") if rpv_cls is not None: h_draw1 = self.hook_all_methods(rpv_cls, "onDraw", RadialProgressViewDrawHook(self)) if h_draw1: self._hooks.extend(h_draw1) h_draw2 = self.hook_all_methods(rpv_cls, "draw", RadialProgressViewDrawHook(self)) if h_draw2: self._hooks.extend(h_draw2) _log("RadialProgressView hooked successfully") except Exception as e: _log(f"Failed to hook RadialProgressView: {e}") # Фоновая проверка обновлений if bool(self.get_setting("auto_update", True)): def delayed_check(): time.sleep(3.0) try: self._check_and_apply_update(manual=False) except Exception as ex: _log(f"Auto-update check error: {ex}") threading.Thread(target=delayed_check, daemon=True).start() _log(f"Bunker Neon Loader v{__version__} loaded successfully! 🔥") def on_plugin_unload(self): self._alive = False try: self.unhook_all() except Exception: pass self._hooks.clear() _log("Bunker Neon Loader unloaded") def get_current_color(self) -> int: """Вычисляет текущий цвет спиннера на основе выбранного стиля и тайминга.""" try: style = self.get_style() now = SystemClock.uptimeMillis() if style == self.STYLE_RGB_RAINBOW: # Плавная RGB-радуга: полный круг спектра за 3.6 секунды hue = float((now // 10) % 360) return _hsv_to_argb(hue, 0.95, 1.0) elif style == self.STYLE_NEON_CYAN: # Неоновый Киберпанк Cyan return _to_signed_32(0xFF00F0FF) elif style == self.STYLE_IOS_MINIMAL: # Чистый серебристо-белый в стиле iOS return _to_signed_32(0xFFFFFFFF) elif style == self.STYLE_SUNSET_FIRE: # Огненный закат: волна от рубинового к янтарному wave = 0.5 + 0.5 * math.sin(now / 550.0) hue = 345.0 + wave * 50.0 if hue >= 360.0: hue -= 360.0 return _hsv_to_argb(hue, 0.92, 1.0) elif style == self.STYLE_EMERALD_MATRIX: # Неоновый изумруд Matrix return _to_signed_32(0xFF00FF66) elif style == self.STYLE_PURPLE_VELVET: # Глубокий неоновый аметист return _to_signed_32(0xFFA855F7) elif style == self.STYLE_ELECTRIC_GOLD: # Электрический золотой янтарь return _to_signed_32(0xFFFFB703) return _to_signed_32(0xFF00F0FF) except Exception: return _to_signed_32(0xFF00F0FF) def get_backdrop_color(self) -> int: """Возвращает цвет подложки лоадера.""" try: if not bool(self.get_setting("custom_backdrop", True)): return _to_signed_32(0x55000000) style = self.get_style() if style == self.STYLE_IOS_MINIMAL: return _to_signed_32(0x40000000) elif style == self.STYLE_NEON_CYAN: return _to_signed_32(0xD0030C16) elif style == self.STYLE_SUNSET_FIRE: return _to_signed_32(0xD01A0704) return _to_signed_32(0xBF000000) except Exception: return _to_signed_32(0xBF000000) def get_stroke_width(self) -> float: """Возвращает толщину линии спиннера.""" try: stroke_val = self.get_setting("stroke_width", 1) stroke_idx = 1 if isinstance(stroke_val, int): stroke_idx = stroke_val elif isinstance(stroke_val, str) and stroke_val.isdigit(): stroke_idx = int(stroke_val) elif isinstance(stroke_val, str): if "Тонкий" in stroke_val: stroke_idx = 0 elif "Жирный" in stroke_val: stroke_idx = 2 style = self.get_style() if style == self.STYLE_IOS_MINIMAL and stroke_idx == 1: return float(AndroidUtilities.dp(1.8)) if stroke_idx == 0: return float(AndroidUtilities.dp(1.8)) elif stroke_idx == 2: return float(AndroidUtilities.dp(4.2)) return float(AndroidUtilities.dp(3.0)) except Exception: return 8.0 def _copy_repo_url(self): """Копирует ссылку на репозиторий плагинов Бункера в буфер обмена.""" try: ctx_app = ApplicationLoader.applicationContext cm = ctx_app.getSystemService(Context.CLIPBOARD_SERVICE) clip = ClipData.newPlainText("repo_url", REPO_URL) cm.setPrimaryClip(clip) safe_notify("Ссылка на репозиторий скопирована в буфер обмена! 🐈‍⬛") except Exception as e: safe_notify(f"Ошибка копирования: {e}") def _check_and_apply_update(self, manual: bool = False): """Проверяет обновления на GitHub и автоматически обновляет файл плагина.""" try: if manual: safe_notify("🔍 Проверяю наличие обновлений Bunker Loader...") remote_code = None urls = [UPDATE_URL_MIRROR, UPDATE_URL_GITHUB] for url in urls: try: req = urllib.request.Request( url, headers={"User-Agent": "BunkerNeonLoaderPlugin/1.3"} ) with urllib.request.urlopen(req, timeout=12.0) as resp: if resp.getcode() == 200: data = resp.read().decode("utf-8", errors="replace") if "__version__" in data and "BunkerNeonLoaderPlugin" in data: remote_code = data break except Exception as ex: _log(f"Update fetch failed from {url}: {ex}") continue if not remote_code: if manual: safe_notify("❌ Не удалось проверить обновления. Проверьте интернет.") return ver_match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', remote_code) if not ver_match: if manual: safe_notify("⚠️ Ошибка формата версии на сервере.") return remote_ver = ver_match.group(1).strip() local_ver = __version__.strip() def parse_ver(v_str: str) -> Tuple[int, ...]: parts = [] for p in re.findall(r"\d+", v_str): try: parts.append(int(p)) except Exception: pass return tuple(parts) if parse_ver(remote_ver) <= parse_ver(local_ver): if manual: safe_notify(f"У вас самая свежая версия (v{local_ver}) ✅") return target_file = None if globals().get("__file__") and os.path.isfile(__file__): target_file = __file__ if not target_file: try: ctx_app = ApplicationLoader.applicationContext if ctx_app: app_files_dir = ctx_app.getFilesDir().getAbsolutePath() p_path = os.path.join(app_files_dir, "plugins", f"{__id__}.plugin") if os.path.exists(p_path): target_file = p_path except Exception: pass if not target_file: for cand_dir in [ "/data/user/0/com.ayugram.telegram/files/plugins", "/data/data/com.ayugram.telegram/files/plugins", "/data/user/0/app.nimarkogram.messenger/files/plugins", "/data/data/app.nimarkogram.messenger/files/plugins", "/data/user/0/com.exteragram.messenger/files/plugins", "/data/data/com.exteragram.messenger/files/plugins", ]: cand_path = os.path.join(cand_dir, f"{__id__}.plugin") if os.path.exists(cand_path): target_file = cand_path break if target_file and os.path.exists(target_file): try: with open(target_file, "w", encoding="utf-8") as f: f.write(remote_code) _log(f"Плагин успешно перезаписан: {target_file} -> v{remote_ver}") safe_notify(f"🎉 Bunker Loader обновлён до v{remote_ver}! Перезапустите Telegram.") return except Exception as wr_err: _log(f"Ошибка перезаписи {target_file}: {wr_err}") if manual: safe_notify(f"Доступна новая v{remote_ver}! Скачайте из канала Бункера.") except Exception as exc: _log(f"Update error: {exc}") if manual: safe_notify(f"Ошибка обновления: {exc}") def create_settings(self) -> List[Any]: """Формирует меню настроек плагина в NimarkoGram / ExteraGram / AyuGram.""" return [ Header(text="Визуальный стиль лоадера"), Switch( key="enabled", text="Включить кастомный лоадер", subtext="Заменяет стандартный серый кружок со стрелочкой на дизайнерский спиннер", default=True, icon="msg_round_attachement", ), Selector( key="style", text="Тема лоадера", items=[ "🌈 RGB-Радуга (Плавные переливы)", "⚡ Неоновый Киберпанк (Cyber Cyan)", "🍏 iOS Минимализм (Тонкий серебристый)", "🌅 Огненный закат (Sunset Gradient)", "💚 Изумруд Matrix (Neon Emerald)", "💜 Аметист Cyber (Neon Purple)", "💛 Золотой янтарь (Electric Gold)", ], default=self.STYLE_RGB_RAINBOW, icon="msg_colors", ), Selector( key="stroke_width", text="Толщина спиннера", items=[ "Тонкий (1.8 dp — стиль iOS)", "Стандартный (3.0 dp)", "Жирный неоновый (4.2 dp — Cyber)", ], default=1, icon="msg_customize", ), Divider(), Header(text="Эффекты анимации"), Switch( key="custom_backdrop", text="OLED-подложка", subtext="Стильный затемнённый высококонтрастный фон вместо стандартного серого", default=True, icon="msg_theme", ), Divider(), Header(text="Обновления плагина"), Switch( key="auto_update", text="Автообновление", subtext="Автоматически загружать новые версии и стили с GitHub Бункера", default=True, icon="msg_retry", ), Text( text="Проверить обновления сейчас", subtext=f"Текущая версия: v{__version__}", icon="msg_download", accent=True, on_click=lambda _: threading.Thread( target=self._check_and_apply_update, args=(True,), daemon=True ).start(), ), Text( text="Скопировать ссылку на репозиторий", subtext="Добавьте в Настройки Telegram -> Плагины -> Репозитории", icon="msg_link", on_click=lambda _: self._copy_repo_url(), ), Divider(), Header(text="О плагине"), Text( text="Bunker Neon Loader v1.3.1 (Full Color & Crash-Proof)", subtext="Бункер Кота (@BUNKER_K0TA / @k0tlux)", icon="msg_info", ), ]