updater.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. # Friendly Telegram (telegram userbot)
  2. # Copyright (C) 2018-2021 The Authors
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU Affero General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU Affero General Public License for more details.
  11. # You should have received a copy of the GNU Affero General Public License
  12. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  14. # █▀█ █ █ █ █▀█ █▀▄ █
  15. # © Copyright 2022
  16. # https://t.me/hikariatama
  17. #
  18. # 🔒 Licensed under the GNU AGPLv3
  19. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  20. import asyncio
  21. import atexit
  22. import contextlib
  23. import logging
  24. import os
  25. import subprocess
  26. import sys
  27. from typing import Union
  28. import time
  29. import git
  30. from git import GitCommandError, Repo
  31. from telethon.tl.functions.messages import (
  32. GetDialogFiltersRequest,
  33. UpdateDialogFilterRequest,
  34. )
  35. from telethon.tl.types import DialogFilter, Message
  36. from .. import loader, utils, heroku, main
  37. from ..inline.types import InlineCall
  38. logger = logging.getLogger(__name__)
  39. @loader.tds
  40. class UpdaterMod(loader.Module):
  41. """Updates itself"""
  42. strings = {
  43. "name": "Updater",
  44. "source": (
  45. "<emoji document_id='5456255401194429832'>📖</emoji> <b>Read the source code"
  46. " from</b> <a href='{}'>here</a>"
  47. ),
  48. "restarting_caption": (
  49. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Restarting...</b>"
  50. ),
  51. "downloading": (
  52. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Downloading"
  53. " updates...</b>"
  54. ),
  55. "installing": (
  56. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Installing"
  57. " updates...</b>"
  58. ),
  59. "success": (
  60. "<emoji document_id='6321050180095313397'>⏱</emoji> <b>Restart successful!"
  61. " {}</b>\n<i>But still loading modules...</i>\n<i>Restart took {}s</i>"
  62. ),
  63. "origin_cfg_doc": "Git origin URL, for where to update from",
  64. "btn_restart": "🔄 Restart",
  65. "btn_update": "🧭 Update",
  66. "restart_confirm": "❓ <b>Are you sure you want to restart?</b>",
  67. "secure_boot_confirm": (
  68. "❓ <b>Are you sure you want to restart in secure boot mode?</b>"
  69. ),
  70. "update_confirm": (
  71. "❓ <b>Are you sure you"
  72. " want to update?\n\n<a"
  73. ' href="https://github.com/hikariatama/Hikka/commit/{}">{}</a> ⤑ <a'
  74. ' href="https://github.com/hikariatama/Hikka/commit/{}">{}</a></b>'
  75. ),
  76. "no_update": "🚸 <b>You are on the latest version, pull updates anyway?</b>",
  77. "cancel": "🚫 Cancel",
  78. "lavhost_restart": (
  79. "<emoji document_id='6318862826265905418'>✌️</emoji> <b>Your lavHost is"
  80. " restarting...\n&gt;///&lt;</b>"
  81. ),
  82. "lavhost_update": (
  83. "<emoji document_id='6318862826265905418'>✌️</emoji> <b>Your lavHost is"
  84. " updating...\n&gt;///&lt;</b>"
  85. ),
  86. "heroku_update": (
  87. "♓️ <b>Deploying new version to Heroku...\nThis might take some time</b>"
  88. ),
  89. "heroku_update_done_nothing_to_push": (
  90. "😔 <b>Update complete. Nothing to push...</b>"
  91. ),
  92. "full_success": (
  93. "<emoji document_id='6323332130579416910'>👍</emoji> <b>Userbot is fully"
  94. " loaded! {}</b>\n<i>Full restart took {}s</i>"
  95. ),
  96. "secure_boot_complete": (
  97. "🔒 <b>Secure boot completed! {}</b>\n<i>Restart took {}s</i>"
  98. ),
  99. }
  100. strings_ru = {
  101. "source": (
  102. "<emoji document_id='5456255401194429832'>📖</emoji> <b>Исходный код можно"
  103. " прочитать</b> <a href='{}'>здесь</a>"
  104. ),
  105. "restarting_caption": (
  106. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Перезагрузка...</b>"
  107. ),
  108. "downloading": (
  109. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Скачивание"
  110. " обновлений...</b>"
  111. ),
  112. "installing": (
  113. "<emoji document_id='6318970114548958978'>🕗</emoji> <b>Установка"
  114. " обновлений...</b>"
  115. ),
  116. "success": (
  117. "<emoji document_id='6321050180095313397'>⏱</emoji> <b>Перезагрузка"
  118. " успешна! {}</b>\n<i>Но модули еще загружаются...</i>\n<i>Перезагрузка"
  119. " заняла {} сек</i>"
  120. ),
  121. "full_success": (
  122. "<emoji document_id='6323332130579416910'>👍</emoji> <b>Юзербот полностью"
  123. " загружен! {}</b>\n<i>Полная перезагрузка заняла {} сек</i>"
  124. ),
  125. "secure_boot_complete": (
  126. "🔒 <b>Безопасная загрузка завершена! {}</b>\n<i>Перезагрузка заняла {}"
  127. " сек</i>"
  128. ),
  129. "origin_cfg_doc": "Ссылка, из которой будут загружаться обновления",
  130. "btn_restart": "🔄 Перезагрузиться",
  131. "btn_update": "🧭 Обновиться",
  132. "restart_confirm": "❓ <b>Ты уверен, что хочешь перезагрузиться?</b>",
  133. "secure_boot_confirm": (
  134. "❓ <b>Ты уверен, что"
  135. " хочешь перезагрузиться в режиме безопасной загрузки?</b>"
  136. ),
  137. "update_confirm": (
  138. "❓ <b>Ты уверен, что"
  139. " хочешь обновиться??\n\n<a"
  140. ' href="https://github.com/hikariatama/Hikka/commit/{}">{}</a> ⤑ <a'
  141. ' href="https://github.com/hikariatama/Hikka/commit/{}">{}</a></b>'
  142. ),
  143. "no_update": "🚸 <b>У тебя последняя версия. Обновиться принудительно?</b>",
  144. "cancel": "🚫 Отмена",
  145. "_cls_doc": "Обновляет юзербот",
  146. "lavhost_restart": (
  147. "<emoji document_id='6318862826265905418'>✌️</emoji> <b>Твой lavHost"
  148. " перезагружается...\n&gt;///&lt;</b>"
  149. ),
  150. "lavhost_update": (
  151. "<emoji document_id='6318862826265905418'>✌️</emoji> <b>Твой lavHost"
  152. " обновляется...\n&gt;///&lt;</b>"
  153. ),
  154. "heroku_update": (
  155. "♓️ <b>Обновляю Heroku...\nЭто может занять некоторое время</b>"
  156. ),
  157. "heroku_update_done_nothing_to_push": (
  158. "😔 <b>Обновление завершено. Ничего не изменилось, нечего обновлять...</b>"
  159. ),
  160. }
  161. def __init__(self):
  162. self.config = loader.ModuleConfig(
  163. loader.ConfigValue(
  164. "GIT_ORIGIN_URL",
  165. "https://github.com/hikariatama/Hikka",
  166. lambda: self.strings("origin_cfg_doc"),
  167. validator=loader.validators.Link(),
  168. )
  169. )
  170. @loader.owner
  171. @loader.command(ru_doc="Перезагружает юзербот")
  172. async def restart(self, message: Message):
  173. """Restarts the userbot"""
  174. secure_boot = "--secure-boot" in utils.get_args_raw(message)
  175. try:
  176. if (
  177. "--force" in (utils.get_args_raw(message) or "")
  178. or not self.inline.init_complete
  179. or not await self.inline.form(
  180. message=message,
  181. text=self.strings(
  182. "secure_boot_confirm" if secure_boot else "restart_confirm"
  183. ),
  184. reply_markup=[
  185. {
  186. "text": self.strings("btn_restart"),
  187. "callback": self.inline_restart,
  188. "args": (secure_boot,),
  189. },
  190. {"text": self.strings("cancel"), "action": "close"},
  191. ],
  192. )
  193. ):
  194. raise
  195. except Exception:
  196. await self.restart_common(message, secure_boot)
  197. async def inline_restart(self, call: InlineCall, secure_boot: bool = False):
  198. await self.restart_common(call, secure_boot=secure_boot)
  199. async def process_restart_message(self, msg_obj: Union[InlineCall, Message]):
  200. self.set(
  201. "selfupdatemsg",
  202. msg_obj.inline_message_id
  203. if hasattr(msg_obj, "inline_message_id")
  204. else f"{utils.get_chat_id(msg_obj)}:{msg_obj.id}",
  205. )
  206. async def restart_common(
  207. self,
  208. msg_obj: Union[InlineCall, Message],
  209. secure_boot: bool = False,
  210. ):
  211. if (
  212. hasattr(msg_obj, "form")
  213. and isinstance(msg_obj.form, dict)
  214. and "uid" in msg_obj.form
  215. and msg_obj.form["uid"] in self.inline._units
  216. and "message" in self.inline._units[msg_obj.form["uid"]]
  217. ):
  218. message = self.inline._units[msg_obj.form["uid"]]["message"]
  219. else:
  220. message = msg_obj
  221. if secure_boot:
  222. self._db.set(loader.__name__, "secure_boot", True)
  223. msg_obj = await utils.answer(
  224. msg_obj,
  225. self.strings(
  226. "restarting_caption"
  227. if "LAVHOST" not in os.environ
  228. else "lavhost_restart"
  229. ),
  230. )
  231. await self.process_restart_message(msg_obj)
  232. self.set("restart_ts", time.time())
  233. await self._db.remote_force_save()
  234. if "LAVHOST" in os.environ:
  235. os.system("lavhost restart")
  236. return
  237. if "DYNO" in os.environ:
  238. app = heroku.get_app(api_token=main.hikka.api_token)[0]
  239. app.restart()
  240. return
  241. with contextlib.suppress(Exception):
  242. await main.hikka.web.stop()
  243. atexit.register(restart, *sys.argv[1:])
  244. handler = logging.getLogger().handlers[0]
  245. handler.setLevel(logging.CRITICAL)
  246. for client in self.allclients:
  247. # Terminate main loop of all running clients
  248. # Won't work if not all clients are ready
  249. if client is not message.client:
  250. await client.disconnect()
  251. await message.client.disconnect()
  252. sys.exit(0)
  253. async def download_common(self):
  254. try:
  255. repo = Repo(os.path.dirname(utils.get_base_dir()))
  256. origin = repo.remote("origin")
  257. r = origin.pull()
  258. new_commit = repo.head.commit
  259. for info in r:
  260. if info.old_commit:
  261. for d in new_commit.diff(info.old_commit):
  262. if d.b_path == "requirements.txt":
  263. return True
  264. return False
  265. except git.exc.InvalidGitRepositoryError:
  266. repo = Repo.init(os.path.dirname(utils.get_base_dir()))
  267. origin = repo.create_remote("origin", self.config["GIT_ORIGIN_URL"])
  268. origin.fetch()
  269. repo.create_head("master", origin.refs.master)
  270. repo.heads.master.set_tracking_branch(origin.refs.master)
  271. repo.heads.master.checkout(True)
  272. return False
  273. @staticmethod
  274. def req_common():
  275. # Now we have downloaded new code, install requirements
  276. logger.debug("Installing new requirements...")
  277. try:
  278. subprocess.run(
  279. [
  280. sys.executable,
  281. "-m",
  282. "pip",
  283. "install",
  284. "-r",
  285. os.path.join(
  286. os.path.dirname(utils.get_base_dir()),
  287. "requirements.txt",
  288. ),
  289. "--user",
  290. ],
  291. check=True,
  292. )
  293. except subprocess.CalledProcessError:
  294. logger.exception("Req install failed")
  295. @loader.owner
  296. @loader.command(ru_doc="Скачивает обновления юзербота")
  297. async def update(self, message: Message):
  298. """Downloads userbot updates"""
  299. try:
  300. current = utils.get_git_hash()
  301. upcoming = next(
  302. git.Repo().iter_commits("origin/master", max_count=1)
  303. ).hexsha
  304. if (
  305. "--force" in (utils.get_args_raw(message) or "")
  306. or not self.inline.init_complete
  307. or not await self.inline.form(
  308. message=message,
  309. text=self.strings("update_confirm").format(
  310. *(
  311. [current, current[:8], upcoming, upcoming[:8]]
  312. if "DYNO" not in os.environ
  313. else ["", "", "", ""]
  314. )
  315. )
  316. if upcoming != current or "DYNO" in os.environ
  317. else self.strings("no_update"),
  318. reply_markup=[
  319. {
  320. "text": self.strings("btn_update"),
  321. "callback": self.inline_update,
  322. },
  323. {"text": self.strings("cancel"), "action": "close"},
  324. ],
  325. )
  326. ):
  327. raise
  328. except Exception:
  329. await self.inline_update(message)
  330. async def inline_update(
  331. self,
  332. msg_obj: Union[InlineCall, Message],
  333. hard: bool = False,
  334. ):
  335. # We don't really care about asyncio at this point, as we are shutting down
  336. if hard:
  337. os.system(f"cd {utils.get_base_dir()} && cd .. && git reset --hard HEAD")
  338. try:
  339. if "LAVHOST" in os.environ:
  340. msg_obj = await utils.answer(msg_obj, self.strings("lavhost_update"))
  341. await self.process_restart_message(msg_obj)
  342. os.system("lavhost update")
  343. return
  344. if "DYNO" in os.environ:
  345. msg_obj = await utils.answer(msg_obj, self.strings("heroku_update"))
  346. await self.process_restart_message(msg_obj)
  347. try:
  348. nosave = "--no-save" in utils.get_args_raw(msg_obj)
  349. except Exception:
  350. nosave = False
  351. if not nosave:
  352. await self._db.remote_force_save()
  353. app, _ = heroku.get_app(
  354. api_token=main.hikka.api_token,
  355. create_new=False,
  356. )
  357. repo = heroku.get_repo()
  358. url = app.git_url.replace(
  359. "https://",
  360. f"https://api:{os.environ.get('heroku_api_token')}@",
  361. )
  362. if "heroku" in repo.remotes:
  363. remote = repo.remote("heroku")
  364. remote.set_url(url)
  365. else:
  366. remote = repo.create_remote("heroku", url)
  367. await utils.run_sync(remote.push, refspec="HEAD:refs/heads/master")
  368. await utils.answer(
  369. msg_obj,
  370. self.strings("heroku_update_done_nothing_to_push"),
  371. )
  372. return
  373. with contextlib.suppress(Exception):
  374. msg_obj = await utils.answer(msg_obj, self.strings("downloading"))
  375. req_update = await self.download_common()
  376. with contextlib.suppress(Exception):
  377. msg_obj = await utils.answer(msg_obj, self.strings("installing"))
  378. if req_update:
  379. self.req_common()
  380. await self.restart_common(msg_obj)
  381. except GitCommandError:
  382. if not hard:
  383. await self.inline_update(msg_obj, True)
  384. return
  385. logger.critical("Got update loop. Update manually via .terminal")
  386. return
  387. @loader.unrestricted
  388. @loader.command(ru_doc="Показать ссылку на исходный код проекта")
  389. async def source(self, message: Message):
  390. """Links the source code of this project"""
  391. await utils.answer(
  392. message,
  393. self.strings("source").format(self.config["GIT_ORIGIN_URL"]),
  394. )
  395. async def client_ready(self):
  396. if self.get("selfupdatemsg") is not None:
  397. try:
  398. await self.update_complete()
  399. except Exception:
  400. logger.exception("Failed to complete update!")
  401. if self.get("do_not_create", False):
  402. return
  403. try:
  404. await self._add_folder()
  405. except Exception:
  406. logger.exception("Failed to add folder!")
  407. finally:
  408. self.set("do_not_create", True)
  409. async def _add_folder(self):
  410. folders = await self._client(GetDialogFiltersRequest())
  411. if any(getattr(folder, "title", None) == "hikka" for folder in folders):
  412. return
  413. try:
  414. folder_id = (
  415. max(
  416. folders,
  417. key=lambda x: x.id,
  418. ).id
  419. + 1
  420. )
  421. except ValueError:
  422. folder_id = 2
  423. try:
  424. await self._client(
  425. UpdateDialogFilterRequest(
  426. folder_id,
  427. DialogFilter(
  428. folder_id,
  429. title="hikka",
  430. pinned_peers=(
  431. [
  432. await self._client.get_input_entity(
  433. self._client.loader.inline.bot_id
  434. )
  435. ]
  436. if self._client.loader.inline.init_complete
  437. else []
  438. ),
  439. include_peers=[
  440. await self._client.get_input_entity(dialog.entity)
  441. async for dialog in self._client.iter_dialogs(
  442. None,
  443. ignore_migrated=True,
  444. )
  445. if dialog.name
  446. in {
  447. "hikka-logs",
  448. "hikka-onload",
  449. "hikka-assets",
  450. "hikka-backups",
  451. "hikka-acc-switcher",
  452. "silent-tags",
  453. }
  454. and dialog.is_channel
  455. and (
  456. dialog.entity.participants_count == 1
  457. or dialog.entity.participants_count == 2
  458. and dialog.name in {"hikka-logs", "silent-tags"}
  459. )
  460. or (
  461. self._client.loader.inline.init_complete
  462. and dialog.entity.id
  463. == self._client.loader.inline.bot_id
  464. )
  465. or dialog.entity.id
  466. in [
  467. 1554874075,
  468. 1697279580,
  469. 1679998924,
  470. ] # official hikka chats
  471. ],
  472. emoticon="🐱",
  473. exclude_peers=[],
  474. contacts=False,
  475. non_contacts=False,
  476. groups=False,
  477. broadcasts=False,
  478. bots=False,
  479. exclude_muted=False,
  480. exclude_read=False,
  481. exclude_archived=False,
  482. ),
  483. )
  484. )
  485. except Exception:
  486. logger.critical(
  487. "Can't create Hikka folder. Possible reasons are:\n"
  488. "- User reached the limit of folders in Telegram\n"
  489. "- User got floodwait\n"
  490. "Ignoring error and adding folder addition to ignore list"
  491. )
  492. async def update_complete(self):
  493. logger.debug("Self update successful! Edit message")
  494. start = self.get("restart_ts")
  495. try:
  496. took = round(time.time() - start)
  497. except Exception:
  498. took = "n/a"
  499. msg = self.strings("success").format(utils.ascii_face(), took)
  500. ms = self.get("selfupdatemsg")
  501. if ":" in str(ms):
  502. chat_id, message_id = ms.split(":")
  503. chat_id, message_id = int(chat_id), int(message_id)
  504. await self._client.edit_message(chat_id, message_id, msg)
  505. return
  506. await self.inline.bot.edit_message_text(
  507. inline_message_id=ms,
  508. text=self.inline.sanitise_text(msg),
  509. )
  510. async def full_restart_complete(self, secure_boot: bool = False):
  511. start = self.get("restart_ts")
  512. try:
  513. took = round(time.time() - start)
  514. except Exception:
  515. took = "n/a"
  516. self.set("restart_ts", None)
  517. ms = self.get("selfupdatemsg")
  518. msg = self.strings(
  519. "secure_boot_complete" if secure_boot else "full_success"
  520. ).format(utils.ascii_face(), took)
  521. if ms is None:
  522. return
  523. self.set("selfupdatemsg", None)
  524. if ":" in str(ms):
  525. chat_id, message_id = ms.split(":")
  526. chat_id, message_id = int(chat_id), int(message_id)
  527. await self._client.edit_message(chat_id, message_id, msg)
  528. await asyncio.sleep(60)
  529. await self._client.delete_messages(chat_id, message_id)
  530. return
  531. await self.inline.bot.edit_message_text(
  532. inline_message_id=ms,
  533. text=self.inline.sanitise_text(msg),
  534. )
  535. def restart(*argv):
  536. os.execl(
  537. sys.executable,
  538. sys.executable,
  539. "-m",
  540. os.path.relpath(utils.get_base_dir()),
  541. *argv,
  542. )