gallery.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. from typing import List, Optional, Union
  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, InvalidHTTPUrlContent, RetryAfter
  26. from telethon.tl.types import Message
  27. from telethon.errors.rpcerrorlist import ChatSendInlineForbiddenError
  28. from urllib.parse import urlparse
  29. import os
  30. from .. import utils, main
  31. from .types import InlineUnit, InlineMessage
  32. logger = logging.getLogger(__name__)
  33. class ListGalleryHelper:
  34. def __init__(self, lst: List[str]):
  35. self.lst = lst
  36. self._current_index = -1
  37. def __call__(self):
  38. self._current_index += 1
  39. return self.lst[self._current_index % len(self.lst)]
  40. def by_index(self, index: int):
  41. return self.lst[index % len(self.lst)]
  42. class Gallery(InlineUnit):
  43. async def gallery(
  44. self,
  45. message: Union[Message, int],
  46. next_handler: Union[callable, List[str]],
  47. caption: Optional[Union[List[str], str, callable]] = "",
  48. *,
  49. custom_buttons: Optional[Union[List[List[dict]], List[dict], dict]] = None,
  50. force_me: Optional[bool] = False,
  51. always_allow: Optional[list] = None,
  52. manual_security: Optional[bool] = False,
  53. disable_security: Optional[bool] = False,
  54. ttl: Optional[Union[int, bool]] = False,
  55. on_unload: Optional[callable] = None,
  56. preload: Optional[Union[bool, int]] = False,
  57. gif: Optional[bool] = False,
  58. silent: Optional[bool] = False,
  59. _reattempt: bool = False,
  60. ) -> 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 "Loading inline 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)
  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("Invalid type for `caption`")
  95. return False
  96. if isinstance(caption, list):
  97. caption = ListGalleryHelper(caption)
  98. if not isinstance(manual_security, bool):
  99. logger.error("Invalid type for `manual_security`")
  100. return False
  101. if not isinstance(silent, bool):
  102. logger.error("Invalid type for `silent`")
  103. return False
  104. if not isinstance(disable_security, bool):
  105. logger.error("Invalid type for `disable_security`")
  106. return False
  107. if not isinstance(message, (Message, int)):
  108. logger.error("Invalid type for `message`")
  109. return False
  110. if not isinstance(force_me, bool):
  111. logger.error("Invalid type for `force_me`")
  112. return False
  113. if not isinstance(gif, bool):
  114. logger.error("Invalid type for `gif`")
  115. return False
  116. if (
  117. not isinstance(preload, (bool, int))
  118. or isinstance(preload, bool)
  119. and preload
  120. ):
  121. logger.error("Invalid type for `preload`")
  122. return False
  123. if always_allow and not isinstance(always_allow, list):
  124. logger.error("Invalid type for `always_allow`")
  125. return False
  126. if not always_allow:
  127. always_allow = []
  128. if not isinstance(ttl, int) and ttl:
  129. logger.error("Invalid type for `ttl`")
  130. return False
  131. if isinstance(next_handler, list):
  132. if all(isinstance(i, str) for i in next_handler):
  133. next_handler = ListGalleryHelper(next_handler)
  134. else:
  135. logger.error("Invalid type for `next_handler`")
  136. return False
  137. unit_id = utils.rand(16)
  138. btn_call_data = utils.rand(10)
  139. try:
  140. if isinstance(next_handler, ListGalleryHelper):
  141. photo_url = next_handler.lst
  142. else:
  143. photo_url = await self._call_photo(next_handler)
  144. if not photo_url:
  145. return False
  146. except Exception:
  147. logger.exception("Error while parsing first photo in gallery")
  148. return False
  149. perms_map = None if manual_security else self._find_caller_sec_map()
  150. self._units[unit_id] = {
  151. "type": "gallery",
  152. "caption": caption,
  153. "chat": None,
  154. "message_id": None,
  155. "uid": unit_id,
  156. "photo_url": (photo_url if isinstance(photo_url, str) else photo_url[0]),
  157. "next_handler": next_handler,
  158. "btn_call_data": btn_call_data,
  159. "photos": [photo_url] if isinstance(photo_url, str) else photo_url,
  160. "current_index": 0,
  161. "future": asyncio.Event(),
  162. **({"ttl": round(time.time()) + ttl} if ttl else {}),
  163. **({"force_me": force_me} if force_me else {}),
  164. **({"disable_security": disable_security} if disable_security else {}),
  165. **({"on_unload": on_unload} if callable(on_unload) else {}),
  166. **({"preload": preload} if preload else {}),
  167. **({"gif": gif} if gif else {}),
  168. **({"always_allow": always_allow} if always_allow else {}),
  169. **({"perms_map": perms_map} if perms_map else {}),
  170. **({"message": message} if isinstance(message, Message) else {}),
  171. **({"custom_buttons": custom_buttons} if custom_buttons else {}),
  172. }
  173. self._custom_map[btn_call_data] = {
  174. "handler": asyncio.coroutine(
  175. functools.partial(
  176. self._gallery_page,
  177. unit_id=unit_id,
  178. )
  179. ),
  180. **(
  181. {"ttl": self._units[unit_id]["ttl"]}
  182. if "ttl" in self._units[unit_id]
  183. else {}
  184. ),
  185. **({"always_allow": always_allow} if always_allow else {}),
  186. **({"force_me": force_me} if force_me else {}),
  187. **({"disable_security": disable_security} if disable_security else {}),
  188. **({"perms_map": perms_map} if perms_map else {}),
  189. **({"message": message} if isinstance(message, Message) else {}),
  190. }
  191. if isinstance(message, Message) and not silent:
  192. try:
  193. status_message = await (
  194. message.edit if message.out else message.respond
  195. )("🌘 <b>Loading inline gallery...</b>")
  196. except Exception:
  197. status_message = None
  198. else:
  199. status_message = None
  200. async def answer(msg: str):
  201. nonlocal message
  202. if isinstance(message, Message):
  203. await (message.edit if message.out else message.respond)(msg)
  204. else:
  205. await self._client.send_message(message, msg)
  206. try:
  207. q = await self._client.inline_query(self.bot_username, unit_id)
  208. m = await q[0].click(
  209. utils.get_chat_id(message) if isinstance(message, Message) else message,
  210. reply_to=message.reply_to_msg_id
  211. if isinstance(message, Message)
  212. else None,
  213. )
  214. except ChatSendInlineForbiddenError:
  215. await answer("🚫 <b>You can't send inline units in this chat</b>")
  216. except Exception:
  217. logger.exception("Error sending inline gallery")
  218. del self._units[unit_id]
  219. if _reattempt:
  220. logger.exception("Can't send gallery")
  221. if not self._db.get(main.__name__, "inlinelogs", True):
  222. msg = "<b>🚫 Gallery invoke failed! More info in logs</b>"
  223. else:
  224. exc = traceback.format_exc()
  225. # Remove `Traceback (most recent call last):`
  226. exc = "\n".join(exc.splitlines()[1:])
  227. msg = (
  228. "<b>🚫 Gallery invoke failed!</b>\n\n"
  229. f"<b>🧾 Logs:</b>\n<code>{exc}</code>"
  230. )
  231. del self._units[unit_id]
  232. await answer(msg)
  233. return False
  234. kwargs = utils.get_kwargs()
  235. kwargs["_reattempt"] = True
  236. return await self.gallery(**kwargs)
  237. await self._units[unit_id]["future"].wait()
  238. del self._units[unit_id]["future"]
  239. self._units[unit_id]["chat"] = utils.get_chat_id(m)
  240. self._units[unit_id]["message_id"] = m.id
  241. if isinstance(message, Message) and message.out:
  242. await message.delete()
  243. if status_message and not message.out:
  244. await status_message.delete()
  245. if not isinstance(next_handler, ListGalleryHelper):
  246. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  247. return InlineMessage(self, unit_id, self._units[unit_id]["inline_message_id"])
  248. async def _call_photo(self, callback: callable) -> Union[str, bool]:
  249. """Parses photo url from `callback`. Returns url on success, otherwise `False`"""
  250. if isinstance(callback, str):
  251. photo_url = callback
  252. elif isinstance(callback, list):
  253. photo_url = callback[0]
  254. elif asyncio.iscoroutinefunction(callback):
  255. photo_url = await callback()
  256. elif callable(callback):
  257. photo_url = callback()
  258. else:
  259. logger.error("Invalid type for `next_handler`")
  260. return False
  261. if not isinstance(photo_url, (str, list)):
  262. logger.error("Got invalid result from `next_handler`")
  263. return False
  264. return photo_url
  265. async def _load_gallery_photos(self, unit_id: str):
  266. """Preloads photo. Should be called via ensure_future"""
  267. unit = self._units[unit_id]
  268. photo_url = await self._call_photo(unit["next_handler"])
  269. self._units[unit_id]["photos"] += (
  270. [photo_url] if isinstance(photo_url, str) else photo_url
  271. )
  272. unit = self._units[unit_id]
  273. # If only one preload was insufficient to load needed amount of photos
  274. if unit.get("preload", False) and len(unit["photos"]) - unit[
  275. "current_index"
  276. ] < unit.get("preload", False):
  277. # Start load again
  278. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  279. async def _gallery_slideshow_loop(
  280. self,
  281. call: CallbackQuery,
  282. unit_id: str = None,
  283. ):
  284. while True:
  285. await asyncio.sleep(7)
  286. unit = self._units[unit_id]
  287. if unit_id not in self._units or not unit.get("slideshow", False):
  288. return
  289. if unit["current_index"] + 1 >= len(unit["photos"]) and isinstance(
  290. unit["next_handler"],
  291. ListGalleryHelper,
  292. ):
  293. del self._units[unit_id]["slideshow"]
  294. self._units[unit_id]["current_index"] -= 1
  295. await self._gallery_page(
  296. call,
  297. self._units[unit_id]["current_index"] + 1,
  298. unit_id=unit_id,
  299. )
  300. async def _gallery_slideshow(
  301. self,
  302. call: CallbackQuery,
  303. unit_id: str = None,
  304. ):
  305. if not self._units[unit_id].get("slideshow", False):
  306. self._units[unit_id]["slideshow"] = True
  307. await self.bot.edit_message_reply_markup(
  308. inline_message_id=call.inline_message_id,
  309. reply_markup=self._gallery_markup(unit_id),
  310. )
  311. await call.answer("✅ Slideshow on")
  312. else:
  313. del self._units[unit_id]["slideshow"]
  314. await self.bot.edit_message_reply_markup(
  315. inline_message_id=call.inline_message_id,
  316. reply_markup=self._gallery_markup(unit_id),
  317. )
  318. await call.answer("🚫 Slideshow off")
  319. return
  320. asyncio.ensure_future(
  321. self._gallery_slideshow_loop(
  322. call,
  323. unit_id,
  324. )
  325. )
  326. async def _gallery_back(
  327. self,
  328. call: CallbackQuery,
  329. unit_id: str = None,
  330. ):
  331. queue = self._units[unit_id]["photos"]
  332. if not queue:
  333. await call.answer("No way back", show_alert=True)
  334. return
  335. self._units[unit_id]["current_index"] -= 1
  336. if self._units[unit_id]["current_index"] < 0:
  337. self._units[unit_id]["current_index"] = 0
  338. await call.answer("No way back")
  339. return
  340. try:
  341. await self.bot.edit_message_media(
  342. inline_message_id=call.inline_message_id,
  343. media=self._get_current_media(unit_id),
  344. reply_markup=self._gallery_markup(unit_id),
  345. )
  346. except RetryAfter as e:
  347. await call.answer(
  348. f"Got FloodWait. Wait for {e.timeout} seconds",
  349. show_alert=True,
  350. )
  351. except Exception:
  352. logger.exception("Exception while trying to edit media")
  353. await call.answer("Error occurred", show_alert=True)
  354. return
  355. def _get_current_media(
  356. self,
  357. unit_id: str,
  358. ) -> Union[InputMediaPhoto, InputMediaAnimation]:
  359. """Return current media, which should be updated in gallery"""
  360. media = self._get_next_photo(unit_id)
  361. try:
  362. path = urlparse(media).path
  363. ext = os.path.splitext(path)[1]
  364. except Exception:
  365. ext = None
  366. if self._units[unit_id].get("gif", False) or ext in {".gif", ".mp4"}:
  367. return InputMediaAnimation(
  368. media=media,
  369. caption=self._get_caption(
  370. unit_id,
  371. index=self._units[unit_id]["current_index"],
  372. ),
  373. parse_mode="HTML",
  374. )
  375. return InputMediaPhoto(
  376. media=media,
  377. caption=self._get_caption(
  378. unit_id,
  379. index=self._units[unit_id]["current_index"],
  380. ),
  381. parse_mode="HTML",
  382. )
  383. async def _gallery_page(
  384. self,
  385. call: CallbackQuery,
  386. page: Union[int, str],
  387. unit_id: str = None,
  388. ):
  389. if page == "slideshow":
  390. await self._gallery_slideshow(call, unit_id)
  391. return
  392. if page == "close":
  393. await self._delete_unit_message(call, unit_id=unit_id)
  394. return
  395. if page < 0:
  396. await call.answer("No way back")
  397. return
  398. if page > len(self._units[unit_id]["photos"]) - 1 and isinstance(
  399. self._units[unit_id]["next_handler"], ListGalleryHelper
  400. ):
  401. await call.answer("No way forward")
  402. return
  403. self._units[unit_id]["current_index"] = page
  404. if not isinstance(self._units[unit_id]["next_handler"], ListGalleryHelper):
  405. # If we exceeded photos limit in gallery and need to preload more
  406. if self._units[unit_id]["current_index"] >= len(
  407. self._units[unit_id]["photos"]
  408. ):
  409. await self._load_gallery_photos(unit_id)
  410. # If we still didn't get needed photo index
  411. if self._units[unit_id]["current_index"] >= len(
  412. self._units[unit_id]["photos"]
  413. ):
  414. await call.answer("Can't load next photo")
  415. return
  416. if (
  417. len(self._units[unit_id]["photos"])
  418. - self._units[unit_id]["current_index"]
  419. < self._units[unit_id].get("preload", 0) // 2
  420. ):
  421. logger.debug(f"Started preload for gallery {unit_id}")
  422. asyncio.ensure_future(self._load_gallery_photos(unit_id))
  423. try:
  424. await self.bot.edit_message_media(
  425. inline_message_id=call.inline_message_id,
  426. media=self._get_current_media(unit_id),
  427. reply_markup=self._gallery_markup(unit_id),
  428. )
  429. except (InvalidHTTPUrlContent, BadRequest):
  430. logger.debug("Error fetching photo content, attempting load next one")
  431. del self._units[unit_id]["photos"][self._units[unit_id]["current_index"]]
  432. self._units[unit_id]["current_index"] -= 1
  433. return await self._gallery_page(call, page, unit_id)
  434. except RetryAfter as e:
  435. await call.answer(
  436. f"Got FloodWait. Wait for {e.timeout} seconds",
  437. show_alert=True,
  438. )
  439. return
  440. except Exception:
  441. logger.exception("Exception while trying to edit media")
  442. await call.answer("Error occurred", show_alert=True)
  443. return
  444. def _get_next_photo(self, unit_id: str) -> str:
  445. """Returns next photo"""
  446. try:
  447. return self._units[unit_id]["photos"][self._units[unit_id]["current_index"]]
  448. except IndexError:
  449. logger.error(
  450. "Got IndexError in `_get_next_photo`. "
  451. f"{self._units[unit_id]['current_index']=} / "
  452. f"{len(self._units[unit_id]['photos'])=}"
  453. )
  454. return self._units[unit_id]["photos"][0]
  455. def _get_caption(self, unit_id: str, index: int = 0) -> str:
  456. """Calls and returnes caption for gallery"""
  457. caption = self._units[unit_id].get("caption", "")
  458. if isinstance(caption, ListGalleryHelper):
  459. return caption.by_index(index)
  460. return (
  461. caption
  462. if isinstance(caption, str)
  463. else caption()
  464. if callable(caption)
  465. else ""
  466. )
  467. def _gallery_markup(self, unit_id: str) -> InlineKeyboardMarkup:
  468. """Generates aiogram markup for `gallery`"""
  469. callback = functools.partial(self._gallery_page, unit_id=unit_id)
  470. unit = self._units[unit_id]
  471. return self.generate_markup(
  472. (
  473. (
  474. unit.get("custom_buttons", [])
  475. + self.build_pagination(
  476. unit_id=unit_id,
  477. callback=callback,
  478. total_pages=len(unit["photos"]),
  479. )
  480. + [
  481. [
  482. *(
  483. [
  484. {
  485. "text": "⏪",
  486. "callback": callback,
  487. "args": (unit["current_index"] - 1,),
  488. }
  489. ]
  490. if unit["current_index"] > 0
  491. else []
  492. ),
  493. *(
  494. [
  495. {
  496. "text": "🛑"
  497. if unit.get("slideshow", False)
  498. else "⏱",
  499. "callback": callback,
  500. "args": ("slideshow",),
  501. }
  502. ]
  503. if unit["current_index"] < len(unit["photos"]) - 1
  504. or not isinstance(
  505. unit["next_handler"], ListGalleryHelper
  506. )
  507. else []
  508. ),
  509. *(
  510. [
  511. {
  512. "text": "⏩",
  513. "callback": callback,
  514. "args": (unit["current_index"] + 1,),
  515. }
  516. ]
  517. if unit["current_index"] < len(unit["photos"]) - 1
  518. or not isinstance(
  519. unit["next_handler"], ListGalleryHelper
  520. )
  521. else []
  522. ),
  523. ]
  524. ]
  525. )
  526. + [[{"text": "🔻 Close", "callback": callback, "args": ("close",)}]]
  527. )
  528. )
  529. async def _gallery_inline_handler(self, inline_query: InlineQuery):
  530. for unit in self._units.copy().values():
  531. if (
  532. inline_query.from_user.id == self._me
  533. and inline_query.query == unit["uid"]
  534. and unit["type"] == "gallery"
  535. ):
  536. try:
  537. path = urlparse(unit["photo_url"]).path
  538. ext = os.path.splitext(path)[1]
  539. except Exception:
  540. ext = None
  541. args = {
  542. "thumb_url": "https://img.icons8.com/fluency/344/loading.png",
  543. "caption": self._get_caption(unit["uid"], index=0),
  544. "parse_mode": "HTML",
  545. "reply_markup": self._gallery_markup(unit["uid"]),
  546. "id": utils.rand(20),
  547. "title": "Processing inline gallery",
  548. }
  549. if unit.get("gif", False) or ext in {".gif", ".mp4"}:
  550. await inline_query.answer(
  551. [InlineQueryResultGif(gif_url=unit["photo_url"], **args)]
  552. )
  553. return
  554. await inline_query.answer(
  555. [InlineQueryResultPhoto(photo_url=unit["photo_url"], **args)],
  556. cache_time=0,
  557. )