okteto_waker.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. """
  58. while True:
  59. try:
  60. if not main.get_config_key("okteto_uri"):
  61. await asyncio.sleep(self._env_wait_interval)
  62. continue
  63. uri = main.get_config_key("okteto_uri")
  64. current_queue = (
  65. await self._client(
  66. GetScheduledHistoryRequest(
  67. peer=self._bot,
  68. hash=0,
  69. ),
  70. )
  71. ).messages
  72. try:
  73. last_date = max(
  74. time.mktime(m.date.timetuple()) for m in current_queue
  75. )
  76. except ValueError:
  77. last_date = time.time()
  78. while last_date < time.time() + self._plan:
  79. last_date += self._messages_interval
  80. try:
  81. await self._client.send_message(
  82. self._bot,
  83. f"{uri}?hash={utils.rand(6)}",
  84. schedule=last_date,
  85. )
  86. except YouBlockedUserError:
  87. await self._client(UnblockRequest(id=self._bot))
  88. await self._client.send_message(
  89. self._bot,
  90. f"{uri}?hash={utils.rand(6)}",
  91. schedule=last_date,
  92. )
  93. logger.debug("Scheduled Okteto pinger to %s", last_date)
  94. await asyncio.sleep(self._send_interval)
  95. await asyncio.sleep(self._overall_polling_interval)
  96. except Exception:
  97. logger.exception("Caught exception on Okteto poller")
  98. await asyncio.sleep(self._exception_timeout)
  99. async def watcher(self, message: Message):
  100. if (
  101. not getattr(message, "raw_text", False)
  102. or not main.get_config_key("okteto_uri")
  103. or main.get_config_key("okteto_uri") not in message.raw_text
  104. and "Link previews was updated successfully" not in message.raw_text
  105. or utils.get_chat_id(message) != 169642392
  106. ):
  107. return
  108. if message.out:
  109. await asyncio.sleep(1)
  110. await message.delete()