okteto_waker.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. import asyncio
  9. import logging
  10. import os
  11. import time
  12. from telethon.errors.rpcerrorlist import YouBlockedUserError
  13. from telethon.tl.functions.contacts import UnblockRequest
  14. from telethon.tl.functions.messages import (
  15. GetScheduledHistoryRequest,
  16. DeleteScheduledMessagesRequest,
  17. )
  18. from telethon.tl.types import Message
  19. from .. import loader, main, utils
  20. logger = logging.getLogger(__name__)
  21. @loader.tds
  22. class OktetoMod(loader.Module):
  23. """Stuff related to Hikka Okteto cloud installation"""
  24. strings = {"name": "Okteto"}
  25. _env_wait_interval = 10
  26. _overall_polling_interval = 30 * 60
  27. _plan = 2 * 24 * 60 * 60
  28. _messages_interval = 30 * 60
  29. _exception_timeout = 10
  30. _send_interval = 5
  31. _bot = "@WebpageBot"
  32. async def client_ready(self):
  33. if "OKTETO" not in os.environ:
  34. messages = (
  35. await self._client(
  36. GetScheduledHistoryRequest(
  37. peer=self._bot,
  38. hash=0,
  39. ),
  40. )
  41. ).messages
  42. if messages:
  43. logger.info("Deleting previously scheduled Okteto pinger messages")
  44. await self._client(
  45. DeleteScheduledMessagesRequest(
  46. self._bot,
  47. [message.id for message in messages],
  48. )
  49. )
  50. raise loader.SelfUnload
  51. await utils.dnd(self._client, self._bot, True)
  52. self._task = asyncio.ensure_future(self._okteto_pinger())
  53. async def on_unload(self):
  54. self._task.cancel()
  55. async def _okteto_pinger(self):
  56. """Creates queue to Webpage bot to reset Okteto polling after app goes to sleep"""
  57. while True:
  58. try:
  59. if not main.get_config_key("okteto_uri"):
  60. await asyncio.sleep(self._env_wait_interval)
  61. continue
  62. uri = main.get_config_key("okteto_uri")
  63. current_queue = (
  64. await self._client(
  65. GetScheduledHistoryRequest(
  66. peer=self._bot,
  67. hash=0,
  68. ),
  69. )
  70. ).messages
  71. try:
  72. last_date = max(
  73. time.mktime(m.date.timetuple()) for m in current_queue
  74. )
  75. except ValueError:
  76. last_date = time.time()
  77. while last_date < time.time() + self._plan:
  78. last_date += self._messages_interval
  79. try:
  80. await self._client.send_message(
  81. self._bot,
  82. f"{uri}?hash={utils.rand(6)}",
  83. schedule=last_date,
  84. )
  85. except YouBlockedUserError:
  86. await self._client(UnblockRequest(id=self._bot))
  87. await self._client.send_message(
  88. self._bot,
  89. f"{uri}?hash={utils.rand(6)}",
  90. schedule=last_date,
  91. )
  92. logger.debug(f"Scheduled Okteto pinger to {last_date}")
  93. await asyncio.sleep(self._send_interval)
  94. await asyncio.sleep(self._overall_polling_interval)
  95. except Exception:
  96. logger.exception("Caught exception on Okteto poller")
  97. await asyncio.sleep(self._exception_timeout)
  98. async def watcher(self, message: Message):
  99. if (
  100. not getattr(message, "raw_text", False)
  101. or not main.get_config_key("okteto_uri")
  102. or main.get_config_key("okteto_uri") not in message.raw_text
  103. and "Link previews was updated successfully" not in message.raw_text
  104. or utils.get_chat_id(message) != 169642392
  105. ):
  106. return
  107. if message.out:
  108. await asyncio.sleep(1)
  109. await message.delete()