gallery.py 26 KB

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