loader.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. """Loads and registers modules"""
  2. # Friendly Telegram (telegram userbot)
  3. # Copyright (C) 2018-2021 The Authors
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Affero General Public License for more details.
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  15. # █▀█ █ █ █ █▀█ █▀▄ █
  16. # © Copyright 2022
  17. # https://t.me/hikariatama
  18. #
  19. # 🔒 Licensed under the GNU AGPLv3
  20. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  21. # scope: inline
  22. import asyncio
  23. import contextlib
  24. import copy
  25. import functools
  26. import importlib
  27. import inspect
  28. import logging
  29. import os
  30. import re
  31. import ast
  32. import sys
  33. import time
  34. import uuid
  35. from collections import ChainMap
  36. from importlib.machinery import ModuleSpec
  37. from typing import Optional, Union
  38. from urllib.parse import urlparse
  39. import requests
  40. import telethon
  41. from telethon.tl.types import Message, Channel
  42. from telethon.tl.functions.channels import JoinChannelRequest
  43. from .. import loader, main, utils
  44. from ..compat import geek
  45. from ..inline.types import InlineCall
  46. from .._types import CoreOverwriteError, CoreUnloadError
  47. logger = logging.getLogger(__name__)
  48. @loader.tds
  49. class LoaderMod(loader.Module):
  50. """Loads modules"""
  51. strings = {
  52. "name": "Loader",
  53. "repo_config_doc": "Fully qualified URL to a module repo",
  54. "avail_header": "<b>📲 Official modules from repo</b>",
  55. "select_preset": "<b>⚠️ Please select a preset</b>",
  56. "no_preset": "<b>🚫 Preset not found</b>",
  57. "preset_loaded": "<b>✅ Preset loaded</b>",
  58. "no_module": "<b>🚫 Module not available in repo.</b>",
  59. "no_file": "<b>🚫 File not found</b>",
  60. "provide_module": "<b>⚠️ Provide a module to load</b>",
  61. "bad_unicode": "<b>🚫 Invalid Unicode formatting in module</b>",
  62. "load_failed": "<b>🚫 Loading failed. See logs for details</b>",
  63. "loaded": "<b>🔭 Module </b><code>{}</code>{}<b> loaded {}</b>{}{}{}{}{}{}",
  64. "no_class": "<b>What class needs to be unloaded?</b>",
  65. "unloaded": "<b>🧹 Module {} unloaded.</b>",
  66. "not_unloaded": "<b>🚫 Module not unloaded.</b>",
  67. "requirements_failed": "<b>🚫 Requirements installation failed</b>",
  68. "requirements_failed_termux": (
  69. "🕶🚫 <b>Requirements installation failed</b>\n<b>The most common reason is"
  70. " that Termux doesn't support many libraries. Don't report it as bug, this"
  71. " can't be solved.</b>"
  72. ),
  73. "heroku_install_failed": (
  74. "♓️⚠️ <b>This module requires additional libraries to be installed, which"
  75. " can't be done on Heroku. Don't report it as bug, this can't be"
  76. " solved.</b>"
  77. ),
  78. "requirements_installing": "<b>🔄 Installing requirements:\n\n{}</b>",
  79. "requirements_restart": (
  80. "<b>🔄 Requirements installed, but a restart is required for"
  81. " </b><code>{}</code><b> to apply</b>"
  82. ),
  83. "all_modules_deleted": "<b>✅ All modules deleted</b>",
  84. "single_cmd": "\n▫️ <code>{}{}</code> {}",
  85. "undoc_cmd": "🦥 No docs",
  86. "ihandler": "\n🎹 <code>{}</code> {}",
  87. "undoc_ihandler": "🦥 No docs",
  88. "inline_init_failed": (
  89. "🚫 <b>This module requires Hikka inline feature and "
  90. "initialization of InlineManager failed</b>\n"
  91. "<i>Please, remove one of your old bots from @BotFather and "
  92. "restart userbot to load this module</i>"
  93. ),
  94. "version_incompatible": (
  95. "🚫 <b>This module requires Hikka {}+\nPlease, update with"
  96. " </b><code>.update</code>"
  97. ),
  98. "ffmpeg_required": (
  99. "🚫 <b>This module requires FFMPEG, which is not installed</b>"
  100. ),
  101. "developer": "\n\n💻 <b>Developer: </b>{}",
  102. "depends_from": "\n\n📦 <b>Dependencies: </b>\n{}",
  103. "by": "by",
  104. "module_fs": (
  105. "💿 <b>Would you like to save this module to filesystem, so it won't get"
  106. " unloaded after restart?</b>"
  107. ),
  108. "save": "💿 Save",
  109. "no_save": "🚫 Don't save",
  110. "save_for_all": "💽 Always save to fs",
  111. "never_save": "🚫 Never save to fs",
  112. "will_save_fs": (
  113. "💽 Now all modules, loaded with .loadmod will be saved to filesystem"
  114. ),
  115. "add_repo_config_doc": "Additional repos to load from",
  116. "share_link_doc": "Share module link in result message of .dlmod",
  117. "modlink": "\n\n🌍 <b>Link: </b><code>{}</code>",
  118. "blob_link": (
  119. "\n🚸 <b>Do not use `blob` links to download modules. Consider switching to"
  120. " `raw` instead</b>"
  121. ),
  122. "suggest_subscribe": (
  123. "\n\n💬 <b>This module is made by {}. Do you want to join this channel to"
  124. " support developer?</b>"
  125. ),
  126. "subscribe": "💬 Subscribe",
  127. "no_subscribe": "🚫 Don't subscribe",
  128. "subscribed": "💬 Subscribed",
  129. "not_subscribed": "🚫 I will no longer suggest subscribing to this channel",
  130. "confirm_clearmodules": "⚠️ <b>Are you sure you want to clear all modules?</b>",
  131. "clearmodules": "🗑 Clear modules",
  132. "cancel": "🚫 Cancel",
  133. "overwrite_module": (
  134. "🚫 <b>This module attempted to override the core one"
  135. " (</b><code>{}</code><b>)</b>\n\n<i>💡 Don't report it as bug. It's a"
  136. " security measure to prevent replacing core modules with some junk</i>"
  137. ),
  138. "overwrite_command": (
  139. "🚫 <b>This module attempted to override the core command"
  140. " (</b><code>{}{}</code><b>)</b>\n\n<i>💡 Don't report it as bug. It's a"
  141. " security measure to prevent replacing core modules' commands with some"
  142. " junk</i>"
  143. ),
  144. "unload_core": (
  145. "🚫 <b>You can't unload core module"
  146. " </b><code>{}</code><b></b>\n\n<i>💡 Don't report it as bug. It's a"
  147. " security measure to prevent replacing core modules with some junk</i>"
  148. ),
  149. "cannot_unload_lib": "🚫 <b>You can't unload library</b>",
  150. "wait_channel_approve": (
  151. "💫 <b>Module </b><code>{}</code><b> requests permission to join channel <a"
  152. ' href="https://t.me/{}">{}</a>.\n\n<b>❓ Reason: {}</b>\n\n<i>Waiting for'
  153. ' <a href="https://t.me/{}">approval</a>...</i>'
  154. ),
  155. }
  156. strings_ru = {
  157. "repo_config_doc": "Ссылка для загрузки модулей",
  158. "add_repo_config_doc": "Дополнительные репозитории",
  159. "avail_header": "<b>📲 Официальные модули из репозитория</b>",
  160. "select_preset": "<b>⚠️ Выбери пресет</b>",
  161. "no_preset": "<b>🚫 Пресет не найден</b>",
  162. "preset_loaded": "<b>✅ Пресет загружен</b>",
  163. "no_module": "<b>🚫 Модуль недоступен в репозитории.</b>",
  164. "no_file": "<b>🚫 Файл не найден</b>",
  165. "provide_module": "<b>⚠️ Укажи модуль для загрузки</b>",
  166. "bad_unicode": "<b>🚫 Неверная кодировка модуля</b>",
  167. "load_failed": "<b>🚫 Загрузка не увенчалась успехом. Смотри логи.</b>",
  168. "loaded": "<b>🔭 Модуль </b><code>{}</code>{}<b> загружен {}</b>{}{}{}{}{}{}",
  169. "no_class": "<b>А что выгружать то?</b>",
  170. "unloaded": "<b>🧹 Модуль {} выгружен.</b>",
  171. "not_unloaded": "<b>🚫 Модуль не выгружен.</b>",
  172. "requirements_failed": "<b>🚫 Ошибка установки зависимостей</b>",
  173. "requirements_failed_termux": (
  174. "🕶🚫 <b>Ошибка установки зависимостей</b>\n<b>Наиболее часто возникает из-за"
  175. " того, что Termux не поддерживает многие библиотеки. Не сообщайте об этом"
  176. " как об ошибке, это не может быть исправлено.</b>"
  177. ),
  178. "heroku_install_failed": (
  179. "♓️⚠️ <b>Этому модулю требуются дополнительные библиотеки, которые нельзя"
  180. " установить на Heroku. Не сообщайте об этом как об ошибке, это не может"
  181. " быть исправлено</b>"
  182. ),
  183. "requirements_installing": "<b>🔄 Устанавливаю зависимости:\n\n{}</b>",
  184. "requirements_restart": (
  185. "<b>🔄 Зависимости установлены, но нужна перезагрузка для применения"
  186. " </b><code>{}</code>"
  187. ),
  188. "all_modules_deleted": "<b>✅ Модули удалены</b>",
  189. "single_cmd": "\n▫️ <code>{}{}</code> {}",
  190. "undoc_cmd": "🦥 Нет описания",
  191. "ihandler": "\n🎹 <code>{}</code> {}",
  192. "undoc_ihandler": "🦥 Нет описания",
  193. "version_incompatible": (
  194. "🚫 <b>Этому модулю требуется Hikka версии {}+\nОбновись с помощью"
  195. " </b><code>.update</code>"
  196. ),
  197. "ffmpeg_required": (
  198. "🚫 <b>Этому модулю требуется FFMPEG, который не установлен</b>"
  199. ),
  200. "developer": "\n\n💻 <b>Разработчик: </b>{}",
  201. "depends_from": "\n\n📦 <b>Зависимости: </b>\n{}",
  202. "by": "от",
  203. "module_fs": (
  204. "💿 <b>Ты хочешь сохранить модуль на жесткий диск, чтобы он не выгружался"
  205. " при перезагрузке?</b>"
  206. ),
  207. "save": "💿 Сохранить",
  208. "no_save": "🚫 Не сохранять",
  209. "save_for_all": "💽 Всегда сохранять",
  210. "never_save": "🚫 Никогда не сохранять",
  211. "will_save_fs": (
  212. "💽 Теперь все модули, загруженные из файла, будут сохраняться на жесткий"
  213. " диск"
  214. ),
  215. "inline_init_failed": (
  216. "🚫 <b>Этому модулю нужен HikkaInline, а инициализация менеджера инлайна"
  217. " неудачна</b>\n<i>Попробуй удалить одного из старых ботов в @BotFather и"
  218. " перезагрузить юзербота</i>"
  219. ),
  220. "_cmd_doc_dlmod": "Скачивает и устаналвивает модуль из репозитория",
  221. "_cmd_doc_dlpreset": "Скачивает и устанавливает определенный набор модулей",
  222. "_cmd_doc_loadmod": "Скачивает и устанавливает модуль из файла",
  223. "_cmd_doc_unloadmod": "Выгружает (удаляет) модуль",
  224. "_cmd_doc_clearmodules": "Выгружает все установленные модули",
  225. "_cls_doc": "Загружает модули",
  226. "share_link_doc": "Указывать ссылку на модуль после загрузки через .dlmod",
  227. "modlink": "\n\n🌍 <b>Ссылка: </b><code>{}</code>",
  228. "blob_link": (
  229. "\n🚸 <b>Не используй `blob` ссылки для загрузки модулей. Лучше загружать из"
  230. " `raw`</b>"
  231. ),
  232. "raw_link": "\n🌍 <b>Ссылка: </b><code>{}</code>",
  233. "suggest_subscribe": (
  234. "\n\n💬 <b>Этот модуль сделан {}. Подписаться на него, чтобы поддержать"
  235. " разработчика?</b>"
  236. ),
  237. "subscribe": "💬 Подписаться",
  238. "no_subscribe": "🚫 Не подписываться",
  239. "subscribed": "💬 Подписался!",
  240. "unsubscribed": "🚫 Я больше не буду предлагать подписаться на этот канал",
  241. "confirm_clearmodules": (
  242. "⚠️ <b>Вы уверены, что хотите выгрузить все модули?</b>"
  243. ),
  244. "clearmodules": "🗑 Выгрузить модули",
  245. "cancel": "🚫 Отмена",
  246. "overwrite_module": (
  247. "🚫 <b>Этот модуль попытался перезаписать встроенный"
  248. " (</b><code>{}</code><b>)</b>\n\n<i>💡 Это не ошибка, а мера безопасности,"
  249. " требуемая для предотвращения замены встроенных модулей всяким хламом. Не"
  250. " сообщайте о ней в support чате</i>"
  251. ),
  252. "overwrite_command": (
  253. "🚫 <b>Этот модуль попытался перезаписать встроенную команду"
  254. " (</b><code>{}</code><b>)</b>\n\n<i>💡 Это не ошибка, а мера безопасности,"
  255. " требуемая для предотвращения замены команд встроенных модулей всяким"
  256. " хламом. Не сообщайте о ней в support чате</i>"
  257. ),
  258. "unload_core": (
  259. "🚫 <b>Ты не можешь выгрузить встроенный модуль"
  260. " </b><code>{}</code><b></b>\n\n<i>💡 Это не ошибка, а мера безопасности,"
  261. " требуемая для предотвращения замены встроенных модулей всяким хламом. Не"
  262. " сообщайте о ней в support чате</i>"
  263. ),
  264. "cannot_unload_lib": "🚫 <b>Ты не можешь выгрузить библиотеку</b>",
  265. "wait_channel_approve": (
  266. "💫 <b>Модуль </b><code>{}</code><b> запрашивает разрешение на вступление в"
  267. ' канал <a href="https://t.me/{}">{}</a>.\n\n<b>❓ Причина:'
  268. ' {}</b>\n\n<i>Ожидание <a href="https://t.me/{}">подтверждения</a>...</i>'
  269. ),
  270. }
  271. _fully_loaded = False
  272. _links_cache = {}
  273. def __init__(self):
  274. self.config = loader.ModuleConfig(
  275. loader.ConfigValue(
  276. "MODULES_REPO",
  277. "https://mods.hikariatama.ru",
  278. lambda: self.strings("repo_config_doc"),
  279. validator=loader.validators.Link(),
  280. ),
  281. loader.ConfigValue(
  282. "ADDITIONAL_REPOS",
  283. # Currenly the trusted developers are specified
  284. [
  285. "https://github.com/hikariatama/host/raw/master",
  286. "https://github.com/MoriSummerz/ftg-mods/raw/main",
  287. "https://gitlab.com/CakesTwix/friendly-userbot-modules/-/raw/master",
  288. ],
  289. lambda: self.strings("add_repo_config_doc"),
  290. validator=loader.validators.Series(validator=loader.validators.Link()),
  291. ),
  292. loader.ConfigValue(
  293. "share_link",
  294. doc=lambda: self.strings("share_link_doc"),
  295. validator=loader.validators.Boolean(),
  296. ),
  297. )
  298. async def client_ready(self, *_):
  299. self.allmodules.add_aliases(self.lookup("settings").get("aliases", {}))
  300. main.hikka.ready.set()
  301. asyncio.ensure_future(self._update_modules())
  302. asyncio.ensure_future(self.get_repo_list("full"))
  303. self._react_queue = []
  304. @loader.loop(interval=120, autostart=True)
  305. async def _react_processor(self):
  306. if not self._react_queue:
  307. return
  308. developer_entity, modname = self._react_queue.pop(0)
  309. try:
  310. await (
  311. await self._client.get_messages(
  312. developer_entity, limit=1, search=modname
  313. )
  314. )[0].react("❤️")
  315. self.set(
  316. "reacted",
  317. self.get("reacted", []) + [f"{developer_entity.id}/{modname}"],
  318. )
  319. except Exception:
  320. logger.debug(f"Unable to react to {developer_entity.id} about {modname}")
  321. @loader.loop(interval=3, wait_before=True, autostart=True)
  322. async def _config_autosaver(self):
  323. for mod in self.allmodules.modules:
  324. if not hasattr(mod, "config") or not mod.config:
  325. continue
  326. for option, config in mod.config._config.items():
  327. if not hasattr(config, "_save_marker"):
  328. continue
  329. delattr(mod.config._config[option], "_save_marker")
  330. self._db.setdefault(mod.__class__.__name__, {}).setdefault(
  331. "__config__", {}
  332. )[option] = config.value
  333. for lib in self.allmodules.libraries:
  334. if not hasattr(lib, "config") or not lib.config:
  335. continue
  336. for option, config in lib.config._config.items():
  337. if not hasattr(config, "_save_marker"):
  338. continue
  339. delattr(lib.config._config[option], "_save_marker")
  340. self._db.setdefault(lib.__class__.__name__, {}).setdefault(
  341. "__config__", {}
  342. )[option] = config.value
  343. self._db.save()
  344. def _update_modules_in_db(self):
  345. if self.allmodules.secure_boot:
  346. return
  347. self.set(
  348. "loaded_modules",
  349. {
  350. module.__class__.__name__: module.__origin__
  351. for module in self.allmodules.modules
  352. if module.__origin__.startswith("http")
  353. },
  354. )
  355. @loader.owner
  356. async def dlmodcmd(self, message: Message):
  357. """Downloads and installs a module from the official module repo"""
  358. if args := utils.get_args(message):
  359. args = args[0]
  360. await self.download_and_install(args, message)
  361. if self._fully_loaded:
  362. self._update_modules_in_db()
  363. else:
  364. await self.inline.list(
  365. message,
  366. [
  367. self.strings("avail_header")
  368. + f"\n☁️ {repo.strip('/')}\n\n"
  369. + "\n".join(
  370. [
  371. " | ".join(chunk)
  372. for chunk in utils.chunks(
  373. [
  374. f"<code>{i}</code>"
  375. for i in sorted(
  376. [
  377. utils.escape_html(
  378. i.split("/")[-1].split(".")[0]
  379. )
  380. for i in mods.values()
  381. ]
  382. )
  383. ],
  384. 5,
  385. )
  386. ]
  387. )
  388. for repo, mods in (await self.get_repo_list("full")).items()
  389. ],
  390. )
  391. @loader.owner
  392. async def dlpresetcmd(self, message: Message):
  393. """Set modules preset"""
  394. args = utils.get_args(message)
  395. if not args:
  396. await utils.answer(message, self.strings("select_preset"))
  397. return
  398. await self.get_repo_list(args[0])
  399. self.set("chosen_preset", args[0])
  400. await utils.answer(message, self.strings("preset_loaded"))
  401. await self.allmodules.commands["restart"](
  402. await message.reply(f"{self.get_prefix()}restart --force")
  403. )
  404. async def _get_modules_to_load(self):
  405. preset = self.get("chosen_preset")
  406. if preset != "disable":
  407. possible_mods = (
  408. await self.get_repo_list(preset, only_primary=True)
  409. ).values()
  410. todo = dict(ChainMap(*possible_mods))
  411. else:
  412. todo = {}
  413. todo.update(**self.get("loaded_modules", {}))
  414. logger.debug(f"Loading modules: {todo}")
  415. return todo
  416. async def _get_repo(self, repo: str, preset: str) -> str:
  417. repo = repo.strip("/")
  418. preset_id = f"{repo}/{preset}"
  419. if self._links_cache.get(preset_id, {}).get("exp", 0) >= time.time():
  420. return self._links_cache[preset_id]["data"]
  421. res = await utils.run_sync(
  422. requests.get,
  423. f"{repo}/{preset}.txt",
  424. )
  425. if not str(res.status_code).startswith("2"):
  426. logger.debug(f"Can't load {repo=}, {preset=}, {res.status_code=}")
  427. return []
  428. self._links_cache[preset_id] = {
  429. "exp": time.time() + 5 * 60,
  430. "data": [link for link in res.text.strip().splitlines() if link],
  431. }
  432. return self._links_cache[preset_id]["data"]
  433. async def get_repo_list(
  434. self,
  435. preset: Optional[str] = None,
  436. only_primary: Optional[bool] = False,
  437. ) -> dict:
  438. if preset is None or preset == "none":
  439. preset = "minimal"
  440. return {
  441. repo: {
  442. f"Mod/{repo_id}/{i}": f'{repo.strip("/")}/{link}.py'
  443. for i, link in enumerate(set(await self._get_repo(repo, preset)))
  444. }
  445. for repo_id, repo in enumerate(
  446. [self.config["MODULES_REPO"]]
  447. + ([] if only_primary else self.config["ADDITIONAL_REPOS"])
  448. )
  449. if repo.startswith("http")
  450. }
  451. async def get_links_list(self):
  452. def converter(repo_dict: dict) -> list:
  453. return list(dict(ChainMap(*list(repo_dict.values()))).values())
  454. links = await self.get_repo_list("full")
  455. # Make `MODULES_REPO` primary one
  456. main_repo = list(links[self.config["MODULES_REPO"]].values())
  457. del links[self.config["MODULES_REPO"]]
  458. return main_repo + converter(links)
  459. async def _find_link(self, module_name: str) -> Union[str, bool]:
  460. links = await self.get_links_list()
  461. return next(
  462. (
  463. link
  464. for link in links
  465. if link.lower().endswith(f"/{module_name.lower()}.py")
  466. ),
  467. False,
  468. )
  469. async def download_and_install(
  470. self,
  471. module_name: str,
  472. message: Optional[Message] = None,
  473. ):
  474. try:
  475. blob_link = False
  476. module_name = module_name.strip()
  477. if urlparse(module_name).netloc:
  478. url = module_name
  479. if re.match(
  480. r"^(https:\/\/github\.com\/.*?\/.*?\/blob\/.*\.py)|"
  481. r"(https:\/\/gitlab\.com\/.*?\/.*?\/-\/blob\/.*\.py)$",
  482. url,
  483. ):
  484. url = url.replace("/blob/", "/raw/")
  485. blob_link = True
  486. else:
  487. url = await self._find_link(module_name)
  488. if not url:
  489. if message is not None:
  490. await utils.answer(message, self.strings("no_module"))
  491. return False
  492. r = await utils.run_sync(requests.get, url)
  493. if r.status_code == 404:
  494. if message is not None:
  495. await utils.answer(message, self.strings("no_module"))
  496. return False
  497. r.raise_for_status()
  498. return await self.load_module(
  499. r.content.decode("utf-8"),
  500. message,
  501. module_name,
  502. url,
  503. blob_link=blob_link,
  504. )
  505. except Exception:
  506. logger.exception(f"Failed to load {module_name}")
  507. async def _inline__load(
  508. self,
  509. call: InlineCall,
  510. doc: str,
  511. path_: Optional[str],
  512. mode: str,
  513. ):
  514. save = False
  515. if mode == "all_yes":
  516. self._db.set(main.__name__, "permanent_modules_fs", True)
  517. self._db.set(main.__name__, "disable_modules_fs", False)
  518. await call.answer(self.strings("will_save_fs"))
  519. save = True
  520. elif mode == "all_no":
  521. self._db.set(main.__name__, "disable_modules_fs", True)
  522. self._db.set(main.__name__, "permanent_modules_fs", False)
  523. elif mode == "once":
  524. save = True
  525. await self.load_module(doc, call, origin=path_ or "<string>", save_fs=save)
  526. @loader.owner
  527. async def loadmodcmd(self, message: Message):
  528. """Loads the module file"""
  529. msg = message if message.file else (await message.get_reply_message())
  530. if msg is None or msg.media is None:
  531. if args := utils.get_args(message):
  532. try:
  533. path_ = args[0]
  534. with open(path_, "rb") as f:
  535. doc = f.read()
  536. except FileNotFoundError:
  537. await utils.answer(message, self.strings("no_file"))
  538. return
  539. else:
  540. await utils.answer(message, self.strings("provide_module"))
  541. return
  542. else:
  543. path_ = None
  544. doc = await msg.download_media(bytes)
  545. logger.debug("Loading external module...")
  546. try:
  547. doc = doc.decode("utf-8")
  548. except UnicodeDecodeError:
  549. await utils.answer(message, self.strings("bad_unicode"))
  550. return
  551. if (
  552. not self._db.get(
  553. main.__name__,
  554. "disable_modules_fs",
  555. False,
  556. )
  557. and not self._db.get(main.__name__, "permanent_modules_fs", False)
  558. and "DYNO" not in os.environ
  559. ):
  560. if message.file:
  561. await message.edit("")
  562. message = await message.respond("🌘")
  563. if await self.inline.form(
  564. self.strings("module_fs"),
  565. message=message,
  566. reply_markup=[
  567. [
  568. {
  569. "text": self.strings("save"),
  570. "callback": self._inline__load,
  571. "args": (doc, path_, "once"),
  572. },
  573. {
  574. "text": self.strings("no_save"),
  575. "callback": self._inline__load,
  576. "args": (doc, path_, "no"),
  577. },
  578. ],
  579. [
  580. {
  581. "text": self.strings("save_for_all"),
  582. "callback": self._inline__load,
  583. "args": (doc, path_, "all_yes"),
  584. }
  585. ],
  586. [
  587. {
  588. "text": self.strings("never_save"),
  589. "callback": self._inline__load,
  590. "args": (doc, path_, "all_no"),
  591. }
  592. ],
  593. ],
  594. ):
  595. return
  596. if path_ is not None:
  597. await self.load_module(
  598. doc,
  599. message,
  600. origin=path_,
  601. save_fs=self._db.get(main.__name__, "permanent_modules_fs", False)
  602. and not self._db.get(main.__name__, "disable_modules_fs", False),
  603. )
  604. else:
  605. await self.load_module(
  606. doc,
  607. message,
  608. save_fs=self._db.get(main.__name__, "permanent_modules_fs", False)
  609. and not self._db.get(main.__name__, "disable_modules_fs", False),
  610. )
  611. async def _send_stats(self, url: str, retry: bool = False):
  612. """Send anonymous stats to Hikka"""
  613. try:
  614. if not self.get("token"):
  615. self.set(
  616. "token",
  617. (
  618. await (await self._client.get_messages("@hikka_ub", ids=[10]))[
  619. 0
  620. ].click(0)
  621. ).message,
  622. )
  623. res = await utils.run_sync(
  624. requests.post,
  625. "https://heta.hikariatama.ru/stats",
  626. data={"url": url},
  627. headers={"X-Hikka-Token": self.get("token")},
  628. )
  629. if res.status_code == 403:
  630. if retry:
  631. return
  632. self.set("token", None)
  633. return await self._send_stats(url, retry=True)
  634. except Exception:
  635. logger.debug("Failed to send stats", exc_info=True)
  636. async def load_module(
  637. self,
  638. doc: str,
  639. message: Message,
  640. name: Optional[Union[str, None]] = None,
  641. origin: Optional[str] = "<string>",
  642. did_requirements: Optional[bool] = False,
  643. save_fs: Optional[bool] = False,
  644. blob_link: Optional[bool] = False,
  645. ):
  646. if any(
  647. line.replace(" ", "") == "#scope:ffmpeg" for line in doc.splitlines()
  648. ) and os.system("ffmpeg -version 1>/dev/null 2>/dev/null"):
  649. if isinstance(message, Message):
  650. await utils.answer(message, self.strings("ffmpeg_required"))
  651. return
  652. if (
  653. any(line.replace(" ", "") == "#scope:inline" for line in doc.splitlines())
  654. and not self.inline.init_complete
  655. ):
  656. if isinstance(message, Message):
  657. await utils.answer(message, self.strings("inline_init_failed"))
  658. return
  659. if re.search(r"# ?scope: ?hikka_min", doc):
  660. ver = re.search(r"# ?scope: ?hikka_min ((\d+\.){2}\d+)", doc).group(1)
  661. ver_ = tuple(map(int, ver.split(".")))
  662. if main.__version__ < ver_:
  663. if isinstance(message, Message):
  664. if getattr(message, "file", None):
  665. m = utils.get_chat_id(message)
  666. await message.edit("")
  667. else:
  668. m = message
  669. await self.inline.form(
  670. self.strings("version_incompatible").format(ver),
  671. m,
  672. reply_markup=[
  673. {
  674. "text": self.lookup("updater").strings("btn_update"),
  675. "callback": self.lookup("updater").inline_update,
  676. },
  677. {
  678. "text": self.lookup("updater").strings("cancel"),
  679. "action": "close",
  680. },
  681. ],
  682. )
  683. return
  684. developer = re.search(r"# ?meta developer: ?(.+)", doc)
  685. developer = developer.group(1) if developer else False
  686. blob_link = self.strings("blob_link") if blob_link else ""
  687. if utils.check_url(name):
  688. url = copy.deepcopy(name)
  689. elif utils.check_url(origin):
  690. url = copy.deepcopy(origin)
  691. else:
  692. url = None
  693. if name is None:
  694. try:
  695. node = ast.parse(doc)
  696. uid = next(n.name for n in node.body if isinstance(n, ast.ClassDef))
  697. except Exception:
  698. logger.debug(
  699. "Can't parse classname from code, using legacy uid instead",
  700. exc_info=True,
  701. )
  702. uid = "__extmod_" + str(uuid.uuid4())
  703. else:
  704. if name.startswith(self.config["MODULES_REPO"]):
  705. name = name.split("/")[-1].split(".py")[0]
  706. uid = name.replace("%", "%%").replace(".", "%d")
  707. module_name = f"hikka.modules.{uid}"
  708. doc = geek.compat(doc)
  709. async def core_overwrite(e: CoreOverwriteError):
  710. nonlocal message
  711. with contextlib.suppress(Exception):
  712. self.allmodules.modules.remove(instance)
  713. if not message:
  714. return
  715. await utils.answer(
  716. message,
  717. self.strings(f"overwrite_{e.type}").format(
  718. *(e.target,)
  719. if e.type == "module"
  720. else (self.get_prefix(), e.target)
  721. ),
  722. )
  723. try:
  724. try:
  725. spec = ModuleSpec(
  726. module_name,
  727. loader.StringLoader(
  728. doc, f"<string {uid}>" if origin == "<string>" else origin
  729. ),
  730. origin=f"<string {uid}>" if origin == "<string>" else origin,
  731. )
  732. instance = self.allmodules.register_module(
  733. spec,
  734. module_name,
  735. origin,
  736. save_fs=save_fs,
  737. )
  738. except ImportError as e:
  739. logger.info(
  740. "Module loading failed, attemping dependency installation"
  741. f" ({e.name})"
  742. )
  743. # Let's try to reinstall dependencies
  744. try:
  745. requirements = list(
  746. filter(
  747. lambda x: not x.startswith(("-", "_", ".")),
  748. map(
  749. str.strip,
  750. loader.VALID_PIP_PACKAGES.search(doc)[1].split(),
  751. ),
  752. )
  753. )
  754. except TypeError:
  755. logger.warning(
  756. "No valid pip packages specified in code, attemping"
  757. " installation from error"
  758. )
  759. requirements = [e.name]
  760. logger.debug(f"Installing requirements: {requirements}")
  761. if not requirements:
  762. raise Exception("Nothing to install") from e
  763. if did_requirements:
  764. if message is not None:
  765. if "DYNO" in os.environ:
  766. await utils.answer(
  767. message,
  768. self.strings("heroku_install_failed"),
  769. )
  770. else:
  771. await utils.answer(
  772. message,
  773. self.strings("requirements_restart").format(e.name),
  774. )
  775. return
  776. if message is not None:
  777. await utils.answer(
  778. message,
  779. self.strings("requirements_installing").format(
  780. "\n".join(f"▫️ {req}" for req in requirements)
  781. ),
  782. )
  783. pip = await asyncio.create_subprocess_exec(
  784. sys.executable,
  785. "-m",
  786. "pip",
  787. "install",
  788. "--upgrade",
  789. "-q",
  790. "--disable-pip-version-check",
  791. "--no-warn-script-location",
  792. *["--user"] if loader.USER_INSTALL else [],
  793. *requirements,
  794. )
  795. rc = await pip.wait()
  796. if rc != 0:
  797. if message is not None:
  798. if "com.termux" in os.environ.get("PREFIX", ""):
  799. await utils.answer(
  800. message,
  801. self.strings("requirements_failed_termux"),
  802. )
  803. else:
  804. await utils.answer(
  805. message,
  806. self.strings("requirements_failed"),
  807. )
  808. return
  809. importlib.invalidate_caches()
  810. kwargs = utils.get_kwargs()
  811. kwargs["did_requirements"] = True
  812. return await self.load_module(**kwargs) # Try again
  813. except loader.LoadError as e:
  814. with contextlib.suppress(ValueError):
  815. self.allmodules.modules.remove(instance) # skipcq: PYL-E0601
  816. if message:
  817. await utils.answer(message, f"🚫 <b>{utils.escape_html(str(e))}</b>")
  818. return
  819. except CoreOverwriteError as e:
  820. await core_overwrite(e)
  821. return
  822. except BaseException as e:
  823. logger.exception(f"Loading external module failed due to {e}")
  824. if message is not None:
  825. await utils.answer(message, self.strings("load_failed"))
  826. return
  827. instance.inline = self.inline
  828. if hasattr(instance, "__version__") and isinstance(instance.__version__, tuple):
  829. version = (
  830. "<b><i>"
  831. f" (v{'.'.join(list(map(str, list(instance.__version__))))})</i></b>"
  832. )
  833. else:
  834. version = ""
  835. try:
  836. try:
  837. self.allmodules.send_config_one(instance)
  838. async def inner_proxy():
  839. nonlocal instance, message
  840. while True:
  841. if hasattr(instance, "hikka_wait_channel_approve"):
  842. if message:
  843. (
  844. module,
  845. channel,
  846. reason,
  847. ) = instance.hikka_wait_channel_approve
  848. message = await utils.answer(
  849. message,
  850. self.strings("wait_channel_approve").format(
  851. module,
  852. channel.username,
  853. utils.escape_html(channel.title),
  854. utils.escape_html(reason),
  855. self.inline.bot_username,
  856. ),
  857. )
  858. return
  859. await asyncio.sleep(0.1)
  860. task = asyncio.ensure_future(inner_proxy())
  861. await self.allmodules.send_ready_one(
  862. instance,
  863. no_self_unload=True,
  864. from_dlmod=bool(message),
  865. )
  866. task.cancel()
  867. except loader.LoadError as e:
  868. with contextlib.suppress(ValueError):
  869. self.allmodules.modules.remove(instance)
  870. if message:
  871. await utils.answer(message, f"🚫 <b>{utils.escape_html(str(e))}</b>")
  872. return
  873. except loader.SelfUnload as e:
  874. logging.debug(f"Unloading {instance}, because it raised `SelfUnload`")
  875. with contextlib.suppress(ValueError):
  876. self.allmodules.modules.remove(instance)
  877. if message:
  878. await utils.answer(message, f"🚫 <b>{utils.escape_html(str(e))}</b>")
  879. return
  880. except loader.SelfSuspend as e:
  881. logging.debug(f"Suspending {instance}, because it raised `SelfSuspend`")
  882. if message:
  883. await utils.answer(
  884. message,
  885. "🥶 <b>Module suspended itself\nReason:"
  886. f" {utils.escape_html(str(e))}</b>",
  887. )
  888. return
  889. except CoreOverwriteError as e:
  890. await core_overwrite(e)
  891. return
  892. except Exception as e:
  893. logger.exception(f"Module threw because {e}")
  894. if message is not None:
  895. await utils.answer(message, self.strings("load_failed"))
  896. return
  897. with contextlib.suppress(Exception):
  898. if (
  899. not any(
  900. line.replace(" ", "") == "#scope:no_stats"
  901. for line in doc.splitlines()
  902. )
  903. and self._db.get(main.__name__, "stats", True)
  904. and url is not None
  905. and utils.check_url(url)
  906. ):
  907. await self._send_stats(url)
  908. for alias, cmd in self.lookup("settings").get("aliases", {}).items():
  909. if cmd in instance.commands:
  910. self.allmodules.add_alias(alias, cmd)
  911. try:
  912. modname = instance.strings("name")
  913. except KeyError:
  914. modname = getattr(instance, "name", "ERROR")
  915. try:
  916. if developer in self._client._hikka_cache and getattr(
  917. await self._client.get_entity(developer), "left", True
  918. ):
  919. developer_entity = await self._client.force_get_entity(developer)
  920. else:
  921. developer_entity = await self._client.get_entity(developer)
  922. except Exception:
  923. developer_entity = None
  924. if not isinstance(developer_entity, Channel):
  925. developer_entity = None
  926. if (
  927. developer_entity is not None
  928. and f"{developer_entity.id}/{modname}" not in self.get("reacted", [])
  929. ):
  930. self._react_queue += [(developer_entity, modname)]
  931. if message is None:
  932. return
  933. modhelp = ""
  934. if instance.__doc__:
  935. modhelp += f"<i>\nℹ️ {utils.escape_html(inspect.getdoc(instance))}</i>\n"
  936. subscribe = ""
  937. subscribe_markup = None
  938. depends_from = []
  939. for key in dir(instance):
  940. value = getattr(instance, key)
  941. if isinstance(value, loader.Library):
  942. depends_from.append(
  943. f"▫️ <code>{value.__class__.__name__}</code><b>"
  944. f" {self.strings('by')} </b><code>{value.developer if isinstance(getattr(value, 'developer', None), str) else 'Unknown'}</code>"
  945. )
  946. depends_from = (
  947. self.strings("depends_from").format("\n".join(depends_from))
  948. if depends_from
  949. else ""
  950. )
  951. def loaded_msg(use_subscribe: bool = True):
  952. nonlocal modname, version, modhelp, developer, origin, subscribe, blob_link, depends_from
  953. return self.strings("loaded").format(
  954. modname.strip(),
  955. version,
  956. utils.ascii_face(),
  957. modhelp,
  958. developer if not subscribe or not use_subscribe else "",
  959. depends_from,
  960. self.strings("modlink").format(origin)
  961. if origin != "<string>" and self.config["share_link"]
  962. else "",
  963. blob_link,
  964. subscribe if use_subscribe else "",
  965. )
  966. if developer:
  967. if developer.startswith("@") and developer not in self.get(
  968. "do_not_subscribe", []
  969. ):
  970. if (
  971. developer_entity
  972. and getattr(developer_entity, "left", True)
  973. and self._db.get(main.__name__, "suggest_subscribe", True)
  974. ):
  975. subscribe = self.strings("suggest_subscribe").format(
  976. f"@{utils.escape_html(developer_entity.username)}"
  977. )
  978. subscribe_markup = [
  979. {
  980. "text": self.strings("subscribe"),
  981. "callback": self._inline__subscribe,
  982. "args": (
  983. developer_entity.id,
  984. functools.partial(loaded_msg, use_subscribe=False),
  985. True,
  986. ),
  987. },
  988. {
  989. "text": self.strings("no_subscribe"),
  990. "callback": self._inline__subscribe,
  991. "args": (
  992. developer,
  993. functools.partial(loaded_msg, use_subscribe=False),
  994. False,
  995. ),
  996. },
  997. ]
  998. developer = self.strings("developer").format(
  999. utils.escape_html(developer)
  1000. if isinstance(developer_entity, Channel)
  1001. else f"<code>{utils.escape_html(developer)}</code>"
  1002. )
  1003. else:
  1004. developer = ""
  1005. if any(
  1006. line.replace(" ", "") == "#scope:disable_onload_docs"
  1007. for line in doc.splitlines()
  1008. ):
  1009. await utils.answer(message, loaded_msg(), reply_markup=subscribe_markup)
  1010. return
  1011. for _name, fun in sorted(
  1012. instance.commands.items(),
  1013. key=lambda x: x[0],
  1014. ):
  1015. modhelp += self.strings("single_cmd").format(
  1016. self.get_prefix(),
  1017. _name,
  1018. (
  1019. utils.escape_html(inspect.getdoc(fun))
  1020. if fun.__doc__
  1021. else self.strings("undoc_cmd")
  1022. ),
  1023. )
  1024. if self.inline.init_complete:
  1025. if hasattr(instance, "inline_handlers"):
  1026. for _name, fun in sorted(
  1027. instance.inline_handlers.items(),
  1028. key=lambda x: x[0],
  1029. ):
  1030. modhelp += self.strings("ihandler").format(
  1031. f"@{self.inline.bot_username} {_name}",
  1032. (
  1033. utils.escape_html(inspect.getdoc(fun))
  1034. if fun.__doc__
  1035. else self.strings("undoc_ihandler")
  1036. ),
  1037. )
  1038. try:
  1039. await utils.answer(message, loaded_msg(), reply_markup=subscribe_markup)
  1040. except telethon.errors.rpcerrorlist.MediaCaptionTooLongError:
  1041. await message.reply(loaded_msg(False))
  1042. async def _inline__subscribe(
  1043. self,
  1044. call: InlineCall,
  1045. entity: int,
  1046. msg: callable,
  1047. subscribe: bool,
  1048. ):
  1049. if not subscribe:
  1050. self.set("do_not_subscribe", self.get("do_not_subscribe", []) + [entity])
  1051. await utils.answer(call, msg())
  1052. await call.answer(self.strings("not_subscribed"))
  1053. return
  1054. await self._client(JoinChannelRequest(entity))
  1055. await utils.answer(call, msg())
  1056. await call.answer(self.strings("subscribed"))
  1057. @loader.owner
  1058. async def unloadmodcmd(self, message: Message):
  1059. """Unload module by class name"""
  1060. args = utils.get_args_raw(message)
  1061. if not args:
  1062. await utils.answer(message, self.strings("no_class"))
  1063. return
  1064. instance = self.lookup(args)
  1065. if issubclass(instance.__class__, loader.Library):
  1066. await utils.answer(message, self.strings("cannot_unload_lib"))
  1067. return
  1068. try:
  1069. worked = self.allmodules.unload_module(args)
  1070. except CoreUnloadError as e:
  1071. await utils.answer(message, self.strings("unload_core").format(e.module))
  1072. return
  1073. if not self.allmodules.secure_boot:
  1074. self.set(
  1075. "loaded_modules",
  1076. {
  1077. mod: link
  1078. for mod, link in self.get("loaded_modules", {}).items()
  1079. if mod not in worked
  1080. },
  1081. )
  1082. msg = (
  1083. self.strings("unloaded").format(
  1084. ", ".join(
  1085. [(mod[:-3] if mod.endswith("Mod") else mod) for mod in worked]
  1086. )
  1087. )
  1088. if worked
  1089. else self.strings("not_unloaded")
  1090. )
  1091. await utils.answer(message, msg)
  1092. @loader.owner
  1093. async def clearmodulescmd(self, message: Message):
  1094. """Delete all installed modules"""
  1095. await self.inline.form(
  1096. self.strings("confirm_clearmodules"),
  1097. message,
  1098. reply_markup=[
  1099. {
  1100. "text": self.strings("clearmodules"),
  1101. "callback": self._inline__clearmodules,
  1102. },
  1103. {
  1104. "text": self.strings("cancel"),
  1105. "action": "close",
  1106. },
  1107. ],
  1108. )
  1109. async def _inline__clearmodules(self, call: InlineCall):
  1110. self.set("loaded_modules", {})
  1111. if "DYNO" not in os.environ:
  1112. for file in os.scandir(loader.LOADED_MODULES_DIR):
  1113. os.remove(file)
  1114. self.set("chosen_preset", "none")
  1115. await utils.answer(call, self.strings("all_modules_deleted"))
  1116. await self.lookup("Updater").restart_common(call)
  1117. async def _update_modules(self):
  1118. todo = await self._get_modules_to_load()
  1119. # ⚠️⚠️ WARNING! ⚠️⚠️
  1120. # If you are a module developer, and you'll try to bypass this protection to
  1121. # force user join your channel, you will be added to SCAM modules
  1122. # list and you will be banned from Hikka federation.
  1123. # Let USER decide, which channel he will follow. Do not be so petty
  1124. # I hope, you understood me.
  1125. # Thank you
  1126. if any(
  1127. arg in todo.values()
  1128. for arg in {
  1129. "https://mods.hikariatama.ru/forbid_joins.py",
  1130. "https://heta.hikariatama.ru/hikariatama/ftg/forbid_joins.py",
  1131. "https://github.com/hikariatama/ftg/raw/master/forbid_joins.py",
  1132. "https://raw.githubusercontent.com/hikariatama/ftg/master/forbid_joins.py",
  1133. }
  1134. ):
  1135. from ..forbid_joins import install_join_forbidder
  1136. install_join_forbidder(self._client)
  1137. secure_boot = False
  1138. if self._db.get(loader.__name__, "secure_boot", False):
  1139. self._db.set(loader.__name__, "secure_boot", False)
  1140. secure_boot = True
  1141. else:
  1142. for mod in todo.values():
  1143. await self.download_and_install(mod)
  1144. self._update_modules_in_db()
  1145. aliases = {
  1146. alias: cmd
  1147. for alias, cmd in self.lookup("settings").get("aliases", {}).items()
  1148. if self.allmodules.add_alias(alias, cmd)
  1149. }
  1150. self.lookup("settings").set("aliases", aliases)
  1151. self._fully_loaded = True
  1152. with contextlib.suppress(AttributeError):
  1153. await self.lookup("Updater").full_restart_complete(secure_boot)