gallery.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. # ©️ Dan Gazizullin, 2021-2023
  2. # This file is a part of Hikka Userbot
  3. # 🌐 https://github.com/hikariatama/Hikka
  4. # You can redistribute it and/or modify it under the terms of the GNU AGPLv3
  5. # 🔑 https://www.gnu.org/licenses/agpl-3.0.html
  6. import asyncio
  7. import contextlib
  8. import copy
  9. import functools
  10. import logging
  11. import os
  12. import time
  13. import traceback
  14. import typing
  15. from urllib.parse import urlparse
  16. from aiogram.types import (
  17. CallbackQuery,
  18. InlineKeyboardMarkup,
  19. InlineQuery,
  20. InlineQueryResultGif,
  21. InlineQueryResultPhoto,
  22. InputMediaAnimation,
  23. InputMediaPhoto,
  24. )
  25. from aiogram.utils.exceptions import BadRequest, RetryAfter
  26. from hikkatl.errors.rpcerrorlist import ChatSendInlineForbiddenError
  27. from hikkatl.extensions.html import CUSTOM_EMOJIS
  28. from hikkatl.tl.types import Message
  29. from .. import main, utils
  30. from ..types import HikkaReplyMarkup
  31. from .types import InlineMessage, InlineUnit
  32. logger = logging.getLogger(__name__)
  33. class ListGalleryHelper:
  34. def __init__(self, lst: typing.List[str]):
  35. self.lst = lst
  36. self._current_index = -1
  37. def __call__(self) -> str:
  38. self._current_index += 1
  39. return self.lst[self._current_index % len(self.lst)]
  40. def by_index(self, index: int) -> str:
  41. return self.lst[index % len(self.lst)]
  42. class Gallery(InlineUnit):
  43. async def gallery(
  44. self,
  45. message: typing.Union[Message, int],
  46. next_handler: typing.Union[callable, typing.List[str]],
  47. caption: typing.Union[typing.List[str], str, callable] = "",
  48. *,
  49. custom_buttons: typing.Optional[HikkaReplyMarkup] = None,
  50. force_me: bool = False,
  51. always_allow: typing.Optional[typing.List[int]] = None,
  52. manual_security: bool = False,
  53. disable_security: bool = False,
  54. ttl: typing.Union[int, bool] = False,
  55. on_unload: typing.Optional[callable] = None,
  56. preload: typing.Union[bool, int] = False,
  57. gif: bool = False,
  58. silent: bool = False,
  59. _reattempt: bool = False,
  60. ) -> typing.Union[bool, InlineMessage]:
  61. """
  62. Send inline gallery to chat
  63. :param caption: Caption for photo, or callable, returning caption
  64. :param message: Where to send inline. Can be either `Message` or `int`
  65. :param next_handler: Callback function, which must return url for next photo or list with photo urls
  66. :param custom_buttons: Custom buttons to add above native ones
  67. :param force_me: Either this gallery buttons must be pressed only by owner scope or no
  68. :param always_allow: Users, that are allowed to press buttons in addition to previous rules
  69. :param ttl: Time, when the gallery is going to be unloaded. Unload means, that the gallery
  70. will become unusable. Pay attention, that ttl can't
  71. be bigger, than default one (1 day) and must be either `int` or `False`
  72. :param on_unload: Callback, called when gallery is unloaded and/or closed. You can clean up trash
  73. or perform another needed action
  74. :param preload: Either to preload gallery photos beforehand or no. If yes - specify threshold to
  75. be loaded. Toggle this attribute, if your callback is too slow to load photos
  76. in real time
  77. :param gif: Whether the gallery will be filled with gifs. If you omit this argument and specify
  78. gifs in `next_handler`, Hikka will try to determine the filetype of these images
  79. :param manual_security: By default, Hikka will try to inherit inline buttons security from the caller (command)
  80. If you want to avoid this, pass `manual_security=True`
  81. :param disable_security: By default, Hikka will try to inherit inline buttons security from the caller (command)
  82. If you want to disable all security checks on this gallery in particular, pass `disable_security=True`
  83. :param silent: Whether the gallery must be sent silently (w/o "Opening gallery..." message)
  84. :return: If gallery is sent, returns :obj:`InlineMessage`, otherwise returns `False`
  85. """
  86. with contextlib.suppress(AttributeError):
  87. _hikka_client_id_logging_tag = copy.copy(self._client.tg_id) # noqa: F841
  88. custom_buttons = self._validate_markup(custom_buttons)
  89. if not (
  90. isinstance(caption, str)
  91. or isinstance(caption, list)
  92. and all(isinstance(item, str) for item in caption)
  93. ) and not callable(caption):
  94. logger.error(
  95. (
  96. "Invalid type for `caption`. Expected `str` or `list` or"
  97. " `callable`, got `%s`"
  98. ),
  99. type(caption),
  100. )
  101. return False
  102. if isinstance(caption, list):
  103. caption = ListGalleryHelper(caption)
  104. if not isinstance(manual_security, bool):
  105. logger.error(
  106. "Invalid type for `manual_security`. Expected `bool`, got `%s`",
  107. type(manual_security),
  108. )
  109. return False
  110. if not isinstance(silent, bool):
  111. logger.error(
  112. "Invalid type for `silent`. Expected `bool`, got `%s`", type(silent)
  113. )
  114. return False
  115. if not isinstance(disable_security, bool):
  116. logger.error(
  117. "Invalid type for `disable_security`. Expected `bool`, got `%s`",
  118. type(disable_security),
  119. )
  120. return False
  121. if not isinstance(message, (Message, int)):
  122. logger.error(
  123. "Invalid type for `message`. Expected `Message` or `int`, got `%s`",
  124. type(message),
  125. )
  126. return False
  127. if not isinstance(force_me, bool):
  128. logger.error(
  129. "Invalid type for `force_me`. Expected `bool`, got `%s`", type(force_me)
  130. )
  131. return False
  132. if not isinstance(gif, bool):
  133. logger.error("Invalid type for `gif`. Expected `bool`, got `%s`", type(gif))
  134. return False
  135. if (
  136. not isinstance(preload, (bool, int))
  137. or isinstance(preload, bool)
  138. and preload
  139. ):
  140. logger.error(
  141. "Invalid type for `preload`. Expected `int` or `False`, got `%s`",
  142. type(preload),
  143. )
  144. return False
  145. if always_allow and not isinstance(always_allow, list):
  146. logger.error(
  147. "Invalid type for `always_allow`. Expected `list`, got `%s`",
  148. type(always_allow),
  149. )
  150. return False
  151. if not always_allow:
  152. always_allow = []
  153. if not isinstance(ttl, int) and ttl:
  154. logger.error(
  155. "Invalid type for `ttl`. Expected `int` or `False`, got `%s`", type(ttl)
  156. )
  157. return False
  158. if isinstance(next_handler, list):
  159. if all(isinstance(i, str) for i in next_handler):
  160. next_handler = ListGalleryHelper(next_handler)
  161. else:
  162. logger.error(
  163. (
  164. "Invalid type for `next_handler`. Expected `callable` or `list`"
  165. " of `str`, got `%s`"
  166. ),
  167. type(next_handler),
  168. )
  169. return False
  170. unit_id = utils.rand(16)
  171. btn_call_data = utils.rand(10)
  172. try:
  173. if isinstance(next_handler, ListGalleryHelper):
  174. photo_url = next_handler.lst
  175. else:
  176. photo_url = await self._call_photo(next_handler)
  177. if not photo_url:
  178. return False
  179. except Exception:
  180. logger.exception("Error while parsing first photo in gallery")
  181. return False
  182. perms_map = None if manual_security else self._find_caller_sec_map()
  183. self._units[unit_id] = {
  184. "type": "gallery",
  185. "caption": caption,
  186. "caller": message,
  187. "chat": None,
  188. "message_id": None,
  189. "top_msg_id": utils.get_topic(message),
  190. "uid": unit_id,
  191. "photo_url": photo_url if isinstance(photo_url, str) else photo_url[0],
  192. "next_handler": next_handler,
  193. "btn_call_data": btn_call_data,
  194. "photos": [photo_url] if isinstance(photo_url, str) else photo_url,
  195. "current_index": 0,
  196. "future": asyncio.Event(),
  197. **({"ttl": round(time.time()) + ttl} if ttl else {}),
  198. **({"force_me": force_me} if force_me else {}),
  199. **({"disable_security": disable_security} if disable_security else {}),
  200. **({"on_unload": on_unload} if callable(on_unload) else {}),
  201. **({"preload": preload} if preload else {}),
  202. **({"gif": gif} if gif else {}),
  203. **({"always_allow": always_allow} if always_allow else {}),
  204. **({"perms_map": perms_map} if perms_map else {}),
  205. **({"message": message} if isinstance(message, Message) else {}),
  206. **({"custom_buttons": custom_buttons} if custom_buttons else {}),
  207. }
  208. self._custom_map[btn_call_data] = {
  209. "handler": asyncio.coroutine(
  210. functools.partial(
  211. self._gallery_page,
  212. unit_id=unit_id,
  213. )
  214. ),
  215. **(
  216. {"ttl": self._units[unit_id]["ttl"]}
  217. if "ttl" in self._units[unit_id]
  218. else {}
  219. ),
  220. **({"always_allow": always_allow} if always_allow else {}),
  221. **({"force_me": force_me} if force_me else {}),
  222. **({"disable_security": disable_security} if disable_security else {}),
  223. **({"perms_map": perms_map} if perms_map else {}),
  224. **({"message": message} if isinstance(message, Message) else {}),
  225. }
  226. if isinstance(message, Message) and not silent:
  227. try:
  228. status_message = await (
  229. message.edit if message.out else message.respond
  230. )(
  231. (
  232. utils.get_platform_emoji()
  233. if self._client.hikka_me.premium and CUSTOM_EMOJIS
  234. else "🌘"
  235. )
  236. + self.translator.getkey("inline.opening_gallery"),
  237. **({"reply_to": utils.get_topic(message)} if message.out else {}),
  238. )
  239. except Exception:
  240. status_message = None
  241. else:
  242. status_message = None
  243. async def answer(msg: str):
  244. nonlocal message
  245. if isinstance(message, Message):
  246. await (message.edit if message.out else message.respond)(
  247. msg,
  248. **({} if message.out else {"reply_to": utils.get_topic(message)}),
  249. )
  250. else:
  251. await self._client.send_message(message, msg)
  252. try:
  253. m = await self._invoke_unit(unit_id, message)
  254. except ChatSendInlineForbiddenError:
  255. await answer(self.translator.getkey("inline.inline403"))
  256. except Exception:
  257. logger.exception("Error sending inline gallery")
  258. del self._units[unit_id]
  259. if _reattempt:
  260. logger.exception("Can't send gallery")
  261. del self._units[unit_id]
  262. await answer(
  263. self.translator.getkey("inline.invoke_failed_logs").format(
  264. utils.escape_html(
  265. "\n".join(traceback.format_exc().splitlines()[1:])
  266. )
  267. )
  268. if self._db.get(main.__name__, "inlinelogs", True)
  269. else self.translator.getkey("inline.invoke_failed")
  270. )
  271. return False
  272. kwargs = utils.get_kwargs()
  273. kwargs["_reattempt"] = True
  274. return await self.gallery(**kwargs)
  275. await self._units[unit_id]["future"].wait()
  276. del self._units[unit_id]["future"]
  277. self._units[unit_id]["chat"] = utils.get_chat_id(m)
  278. self._units[unit_id]["message_id"] = m.id
  279. if isinstance(message, Message) and message.out:
  280. await message.delete()
  281. if status_message and not message.out:
  282. await status_message.delete()
  283. if not isinstance(next_handler, ListGalleryHelper):
  284. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  285. return InlineMessage(self, unit_id, self._units[unit_id]["inline_message_id"])
  286. async def _call_photo(
  287. self,
  288. callback: typing.Union[
  289. typing.Callable[[], typing.Awaitable[str]],
  290. typing.Callable[[], str],
  291. typing.List[str],
  292. ],
  293. ) -> typing.Union[str, bool]:
  294. """Parses photo url from `callback`. Returns url on success, otherwise `False`"""
  295. if isinstance(callback, str):
  296. photo_url = callback
  297. elif isinstance(callback, list):
  298. photo_url = callback[0]
  299. elif asyncio.iscoroutinefunction(callback):
  300. photo_url = await callback()
  301. elif callable(callback):
  302. photo_url = callback()
  303. else:
  304. logger.error(
  305. (
  306. "Invalid type for `next_handler`. Expected `str`, `list` or"
  307. " `callable`, got %s"
  308. ),
  309. type(callback),
  310. )
  311. return False
  312. if not isinstance(photo_url, (str, list)):
  313. logger.error(
  314. (
  315. "Got invalid result from `next_handler`. Expected `str` or `list`,"
  316. " got %s"
  317. ),
  318. type(photo_url),
  319. )
  320. return False
  321. return photo_url
  322. async def _load_gallery_photos(self, unit_id: str):
  323. """Preloads photo. Should be called via ensure_future"""
  324. unit = self._units[unit_id]
  325. photo_url = await self._call_photo(unit["next_handler"])
  326. self._units[unit_id]["photos"] += (
  327. [photo_url] if isinstance(photo_url, str) else photo_url
  328. )
  329. unit = self._units[unit_id]
  330. if unit.get("preload", False) and len(unit["photos"]) - unit[
  331. "current_index"
  332. ] < unit.get("preload", False):
  333. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  334. async def _gallery_slideshow_loop(
  335. self,
  336. call: CallbackQuery,
  337. unit_id: typing.Optional[str] = None,
  338. ):
  339. while True:
  340. await asyncio.sleep(7)
  341. unit = self._units[unit_id]
  342. if unit_id not in self._units or not unit.get("slideshow", False):
  343. return
  344. if unit["current_index"] + 1 >= len(unit["photos"]) and isinstance(
  345. unit["next_handler"],
  346. ListGalleryHelper,
  347. ):
  348. del self._units[unit_id]["slideshow"]
  349. self._units[unit_id]["current_index"] -= 1
  350. await self._gallery_page(
  351. call,
  352. self._units[unit_id]["current_index"] + 1,
  353. unit_id=unit_id,
  354. )
  355. async def _gallery_slideshow(
  356. self,
  357. call: CallbackQuery,
  358. unit_id: typing.Optional[str] = None,
  359. ):
  360. if not self._units[unit_id].get("slideshow", False):
  361. self._units[unit_id]["slideshow"] = True
  362. await self.bot.edit_message_reply_markup(
  363. inline_message_id=call.inline_message_id,
  364. reply_markup=self._gallery_markup(unit_id),
  365. )
  366. await call.answer("✅ Slideshow on")
  367. else:
  368. del self._units[unit_id]["slideshow"]
  369. await self.bot.edit_message_reply_markup(
  370. inline_message_id=call.inline_message_id,
  371. reply_markup=self._gallery_markup(unit_id),
  372. )
  373. await call.answer("🚫 Slideshow off")
  374. return
  375. asyncio.ensure_future(
  376. self._gallery_slideshow_loop(
  377. call,
  378. unit_id,
  379. )
  380. )
  381. async def _gallery_back(
  382. self,
  383. call: CallbackQuery,
  384. unit_id: typing.Optional[str] = None,
  385. ):
  386. queue = self._units[unit_id]["photos"]
  387. if not queue:
  388. await call.answer("No way back", show_alert=True)
  389. return
  390. self._units[unit_id]["current_index"] -= 1
  391. if self._units[unit_id]["current_index"] < 0:
  392. self._units[unit_id]["current_index"] = 0
  393. await call.answer("No way back")
  394. return
  395. try:
  396. await self.bot.edit_message_media(
  397. inline_message_id=call.inline_message_id,
  398. media=self._get_current_media(unit_id),
  399. reply_markup=self._gallery_markup(unit_id),
  400. )
  401. except RetryAfter as e:
  402. await call.answer(
  403. f"Got FloodWait. Wait for {e.timeout} seconds",
  404. show_alert=True,
  405. )
  406. except Exception:
  407. logger.exception("Exception while trying to edit media")
  408. await call.answer("Error occurred", show_alert=True)
  409. return
  410. def _get_current_media(
  411. self,
  412. unit_id: str,
  413. ) -> typing.Union[InputMediaPhoto, InputMediaAnimation]:
  414. """Return current media, which should be updated in gallery"""
  415. media = self._get_next_photo(unit_id)
  416. try:
  417. path = urlparse(media).path
  418. ext = os.path.splitext(path)[1]
  419. except Exception:
  420. ext = None
  421. if self._units[unit_id].get("gif", False) or ext in {".gif", ".mp4"}:
  422. return InputMediaAnimation(
  423. media=media,
  424. caption=self._get_caption(
  425. unit_id,
  426. index=self._units[unit_id]["current_index"],
  427. ),
  428. parse_mode="HTML",
  429. )
  430. return InputMediaPhoto(
  431. media=media,
  432. caption=self._get_caption(
  433. unit_id,
  434. index=self._units[unit_id]["current_index"],
  435. ),
  436. parse_mode="HTML",
  437. )
  438. async def _gallery_page(
  439. self,
  440. call: CallbackQuery,
  441. page: typing.Union[int, str],
  442. unit_id: typing.Optional[str] = None,
  443. ):
  444. if page == "slideshow":
  445. await self._gallery_slideshow(call, unit_id)
  446. return
  447. if page == "close":
  448. await self._delete_unit_message(call, unit_id=unit_id)
  449. return
  450. if page < 0:
  451. await call.answer("No way back")
  452. return
  453. if page > len(self._units[unit_id]["photos"]) - 1 and isinstance(
  454. self._units[unit_id]["next_handler"], ListGalleryHelper
  455. ):
  456. await call.answer("No way forward")
  457. return
  458. self._units[unit_id]["current_index"] = page
  459. if not isinstance(self._units[unit_id]["next_handler"], ListGalleryHelper):
  460. if self._units[unit_id]["current_index"] >= len(
  461. self._units[unit_id]["photos"]
  462. ):
  463. await self._load_gallery_photos(unit_id)
  464. if self._units[unit_id]["current_index"] >= len(
  465. self._units[unit_id]["photos"]
  466. ):
  467. await call.answer("Can't load next photo")
  468. return
  469. if (
  470. len(self._units[unit_id]["photos"])
  471. - self._units[unit_id]["current_index"]
  472. < self._units[unit_id].get("preload", 0) // 2
  473. ):
  474. logger.debug("Started preload for gallery %s", unit_id)
  475. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  476. try:
  477. await self.bot.edit_message_media(
  478. inline_message_id=call.inline_message_id,
  479. media=self._get_current_media(unit_id),
  480. reply_markup=self._gallery_markup(unit_id),
  481. )
  482. except BadRequest:
  483. logger.debug("Error fetching photo content, attempting load next one")
  484. del self._units[unit_id]["photos"][self._units[unit_id]["current_index"]]
  485. self._units[unit_id]["current_index"] -= 1
  486. return await self._gallery_page(call, page, unit_id)
  487. except RetryAfter as e:
  488. await call.answer(
  489. f"Got FloodWait. Wait for {e.timeout} seconds",
  490. show_alert=True,
  491. )
  492. return
  493. except Exception:
  494. logger.exception("Exception while trying to edit media")
  495. await call.answer("Error occurred", show_alert=True)
  496. return
  497. def _get_next_photo(self, unit_id: str) -> str:
  498. """Returns next photo"""
  499. try:
  500. return self._units[unit_id]["photos"][self._units[unit_id]["current_index"]]
  501. except IndexError:
  502. logger.error(
  503. "Got IndexError in `_get_next_photo`. %s / %s",
  504. self._units[unit_id]["current_index"],
  505. len(self._units[unit_id]["photos"]),
  506. )
  507. return self._units[unit_id]["photos"][0]
  508. def _get_caption(self, unit_id: str, index: int = 0) -> str:
  509. """Calls and returnes caption for gallery"""
  510. caption = self._units[unit_id].get("caption", "")
  511. if isinstance(caption, ListGalleryHelper):
  512. return caption.by_index(index)
  513. return (
  514. caption
  515. if isinstance(caption, str)
  516. else caption() if callable(caption) else ""
  517. )
  518. def _gallery_markup(self, unit_id: str) -> InlineKeyboardMarkup:
  519. """Generates aiogram markup for `gallery`"""
  520. callback = functools.partial(self._gallery_page, unit_id=unit_id)
  521. unit = self._units[unit_id]
  522. return self.generate_markup(
  523. (
  524. (
  525. unit.get("custom_buttons", [])
  526. + self.build_pagination(
  527. unit_id=unit_id,
  528. callback=callback,
  529. total_pages=len(unit["photos"]),
  530. )
  531. + [
  532. [
  533. *(
  534. [
  535. {
  536. "text": "⏪",
  537. "callback": callback,
  538. "args": (unit["current_index"] - 1,),
  539. }
  540. ]
  541. if unit["current_index"] > 0
  542. else []
  543. ),
  544. *(
  545. [
  546. {
  547. "text": (
  548. "🛑"
  549. if unit.get("slideshow", False)
  550. else "⏱"
  551. ),
  552. "callback": callback,
  553. "args": ("slideshow",),
  554. }
  555. ]
  556. if unit["current_index"] < len(unit["photos"]) - 1
  557. or not isinstance(
  558. unit["next_handler"], ListGalleryHelper
  559. )
  560. else []
  561. ),
  562. *(
  563. [
  564. {
  565. "text": "⏩",
  566. "callback": callback,
  567. "args": (unit["current_index"] + 1,),
  568. }
  569. ]
  570. if unit["current_index"] < len(unit["photos"]) - 1
  571. or not isinstance(
  572. unit["next_handler"], ListGalleryHelper
  573. )
  574. else []
  575. ),
  576. ]
  577. ]
  578. )
  579. + [[{"text": "🔻 Close", "callback": callback, "args": ("close",)}]]
  580. )
  581. )
  582. async def _gallery_inline_handler(self, inline_query: InlineQuery):
  583. for unit in self._units.copy().values():
  584. if (
  585. inline_query.from_user.id == self._me
  586. and inline_query.query == unit["uid"]
  587. and unit["type"] == "gallery"
  588. ):
  589. try:
  590. try:
  591. path = urlparse(unit["photo_url"]).path
  592. ext = os.path.splitext(path)[1]
  593. except Exception:
  594. ext = None
  595. args = {
  596. "thumb_url": "https://img.icons8.com/fluency/344/loading.png",
  597. "caption": self._get_caption(unit["uid"], index=0),
  598. "parse_mode": "HTML",
  599. "reply_markup": self._gallery_markup(unit["uid"]),
  600. "id": utils.rand(20),
  601. "title": "Processing inline gallery",
  602. }
  603. if unit.get("gif", False) or ext in {".gif", ".mp4"}:
  604. await inline_query.answer(
  605. [InlineQueryResultGif(gif_url=unit["photo_url"], **args)]
  606. )
  607. return
  608. await inline_query.answer(
  609. [InlineQueryResultPhoto(photo_url=unit["photo_url"], **args)],
  610. cache_time=0,
  611. )
  612. except Exception as e:
  613. if unit["uid"] in self._error_events:
  614. self._error_events[unit["uid"]].set()
  615. self._error_events[unit["uid"]] = e