user.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from __future__ import annotations
  17. from typing import TYPE_CHECKING, AsyncGenerator, AsyncIterable, Awaitable, cast
  18. import asyncio
  19. import logging
  20. import time
  21. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState
  22. from mauigpapi.errors import (
  23. IGCheckpointError,
  24. IGNotLoggedInError,
  25. IGUserIDNotFoundError,
  26. IrisSubscribeError,
  27. MQTTNotConnected,
  28. MQTTNotLoggedIn,
  29. )
  30. from mauigpapi.mqtt import Connect, Disconnect, GraphQLSubscription, SkywalkerSubscription
  31. from mauigpapi.types import (
  32. ActivityIndicatorData,
  33. CurrentUser,
  34. MessageSyncEvent,
  35. Operation,
  36. RealtimeDirectEvent,
  37. Thread,
  38. ThreadSyncEvent,
  39. TypingStatus,
  40. )
  41. from mautrix.appservice import AppService
  42. from mautrix.bridge import BaseUser, async_getter_lock
  43. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  44. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  45. from mautrix.util.logging import TraceLogger
  46. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  47. from . import portal as po, puppet as pu
  48. from .config import Config
  49. from .db import Portal as DBPortal, User as DBUser
  50. if TYPE_CHECKING:
  51. from .__main__ import InstagramBridge
  52. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  53. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  54. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  55. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  56. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  57. BridgeState.human_readable_errors.update(
  58. {
  59. "ig-connection-error": "Instagram disconnected unexpectedly",
  60. "ig-auth-error": "Authentication error from Instagram: {message}",
  61. "ig-checkpoint": "Instagram checkpoint error. Please check Instagram website.",
  62. "ig-checkpoint-locked": "Instagram checkpoint error. Please check Instagram website.",
  63. "ig-disconnected": None,
  64. "ig-no-mqtt": "You're not connected to Instagram",
  65. "logged-out": "You're not logged into Instagram",
  66. }
  67. )
  68. class User(DBUser, BaseUser):
  69. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  70. _activity_indicator_ids: dict[str, int] = {}
  71. by_mxid: dict[UserID, User] = {}
  72. by_igpk: dict[int, User] = {}
  73. config: Config
  74. az: AppService
  75. loop: asyncio.AbstractEventLoop
  76. client: AndroidAPI | None
  77. mqtt: AndroidMQTT | None
  78. _listen_task: asyncio.Task | None = None
  79. permission_level: str
  80. username: str | None
  81. _notice_room_lock: asyncio.Lock
  82. _notice_send_lock: asyncio.Lock
  83. _is_logged_in: bool
  84. _is_connected: bool
  85. shutdown: bool
  86. remote_typing_status: TypingStatus | None
  87. def __init__(
  88. self,
  89. mxid: UserID,
  90. igpk: int | None = None,
  91. state: AndroidState | None = None,
  92. notice_room: RoomID | None = None,
  93. ) -> None:
  94. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  95. BaseUser.__init__(self)
  96. self._notice_room_lock = asyncio.Lock()
  97. self._notice_send_lock = asyncio.Lock()
  98. perms = self.config.get_permissions(mxid)
  99. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  100. self.client = None
  101. self.mqtt = None
  102. self.username = None
  103. self._is_logged_in = False
  104. self._is_connected = False
  105. self._is_refreshing = False
  106. self.shutdown = False
  107. self._listen_task = None
  108. self.remote_typing_status = None
  109. @classmethod
  110. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  111. cls.bridge = bridge
  112. cls.config = bridge.config
  113. cls.az = bridge.az
  114. cls.loop = bridge.loop
  115. return (user.try_connect() async for user in cls.all_logged_in())
  116. # region Connection management
  117. async def is_logged_in(self) -> bool:
  118. return bool(self.client) and self._is_logged_in
  119. async def get_puppet(self) -> pu.Puppet | None:
  120. if not self.igpk:
  121. return None
  122. return await pu.Puppet.get_by_pk(self.igpk)
  123. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  124. if not self.igpk:
  125. return None
  126. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  127. if portal:
  128. return portal
  129. if create:
  130. # TODO add error handling somewhere
  131. thread = await self.client.create_group_thread([puppet.pk])
  132. portal = await po.Portal.get_by_thread(thread, self.igpk)
  133. await portal.update_info(thread, self)
  134. return portal
  135. return None
  136. async def try_connect(self) -> None:
  137. try:
  138. await self.connect()
  139. except Exception:
  140. self.log.exception("Error while connecting to Instagram")
  141. @property
  142. def api_log(self) -> TraceLogger:
  143. return self.ig_base_log.getChild("http").getChild(self.mxid)
  144. @property
  145. def is_connected(self) -> bool:
  146. return bool(self.client) and bool(self.mqtt) and self._is_connected
  147. async def connect(self, user: CurrentUser | None = None) -> None:
  148. if not self.state:
  149. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error="logged-out")
  150. return
  151. client = AndroidAPI(self.state, log=self.api_log)
  152. if not user:
  153. try:
  154. resp = await client.current_user()
  155. user = resp.user
  156. except IGNotLoggedInError as e:
  157. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  158. await self.logout(error=e)
  159. return
  160. except IGCheckpointError as e:
  161. await self._handle_checkpoint(e, on="connect", client=client)
  162. return
  163. self.client = client
  164. self._is_logged_in = True
  165. self.igpk = user.pk
  166. self.username = user.username
  167. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  168. self._track_metric(METRIC_LOGGED_IN, True)
  169. self.by_igpk[self.igpk] = self
  170. self.mqtt = AndroidMQTT(
  171. self.state, loop=self.loop, log=self.ig_base_log.getChild("mqtt").getChild(self.mxid)
  172. )
  173. self.mqtt.add_event_handler(Connect, self.on_connect)
  174. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  175. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  176. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  177. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  178. await self.update()
  179. self.loop.create_task(self._try_sync_puppet(user))
  180. self.loop.create_task(self._try_sync())
  181. async def on_connect(self, evt: Connect) -> None:
  182. self.log.debug("Connected to Instagram")
  183. self._track_metric(METRIC_CONNECTED, True)
  184. self._is_connected = True
  185. await self.send_bridge_notice("Connected to Instagram")
  186. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  187. async def on_disconnect(self, evt: Disconnect) -> None:
  188. self.log.debug("Disconnected from Instagram")
  189. self._track_metric(METRIC_CONNECTED, False)
  190. self._is_connected = False
  191. # TODO this stuff could probably be moved to mautrix-python
  192. async def get_notice_room(self) -> RoomID:
  193. if not self.notice_room:
  194. async with self._notice_room_lock:
  195. # If someone already created the room while this call was waiting,
  196. # don't make a new room
  197. if self.notice_room:
  198. return self.notice_room
  199. creation_content = {}
  200. if not self.config["bridge.federate_rooms"]:
  201. creation_content["m.federate"] = False
  202. self.notice_room = await self.az.intent.create_room(
  203. is_direct=True,
  204. invitees=[self.mxid],
  205. topic="Instagram bridge notices",
  206. creation_content=creation_content,
  207. )
  208. await self.update()
  209. return self.notice_room
  210. async def fill_bridge_state(self, state: BridgeState) -> None:
  211. await super().fill_bridge_state(state)
  212. if not state.remote_id:
  213. if self.igpk:
  214. state.remote_id = str(self.igpk)
  215. else:
  216. try:
  217. state.remote_id = self.state.user_id
  218. except IGUserIDNotFoundError:
  219. state.remote_id = None
  220. if self.username:
  221. state.remote_name = f"@{self.username}"
  222. async def get_bridge_states(self) -> list[BridgeState]:
  223. if not self.state:
  224. return []
  225. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  226. if self.is_connected:
  227. state.state_event = BridgeStateEvent.CONNECTED
  228. elif self._is_refreshing or self.mqtt:
  229. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  230. return [state]
  231. async def send_bridge_notice(
  232. self,
  233. text: str,
  234. edit: EventID | None = None,
  235. state_event: BridgeStateEvent | None = None,
  236. important: bool = False,
  237. error_code: str | None = None,
  238. error_message: str | None = None,
  239. ) -> EventID | None:
  240. if state_event:
  241. await self.push_bridge_state(
  242. state_event, error=error_code, message=error_message if error_code else text
  243. )
  244. if self.config["bridge.disable_bridge_notices"]:
  245. return None
  246. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  247. self.log.debug("Not sending unimportant bridge notice: %s", text)
  248. return None
  249. event_id = None
  250. try:
  251. self.log.debug("Sending bridge notice: %s", text)
  252. content = TextMessageEventContent(
  253. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  254. )
  255. if edit:
  256. content.set_edit(edit)
  257. # This is locked to prevent notices going out in the wrong order
  258. async with self._notice_send_lock:
  259. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  260. except Exception:
  261. self.log.warning("Failed to send bridge notice", exc_info=True)
  262. return edit or event_id
  263. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  264. puppet = await pu.Puppet.get_by_pk(self.igpk)
  265. try:
  266. await puppet.update_info(user_info, self)
  267. except Exception:
  268. self.log.exception("Failed to update own puppet info")
  269. try:
  270. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  271. self.log.info(f"Automatically enabling custom puppet")
  272. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  273. except Exception:
  274. self.log.exception("Failed to automatically enable custom puppet")
  275. async def _try_sync(self) -> None:
  276. try:
  277. await self.sync()
  278. except Exception:
  279. self.log.exception("Exception while syncing")
  280. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  281. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  282. return {
  283. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  284. for portal in await DBPortal.find_private_chats_of(self.igpk)
  285. if portal.mxid
  286. }
  287. async def refresh(self, resync: bool = True) -> None:
  288. self._is_refreshing = True
  289. try:
  290. await self.stop_listen()
  291. if resync:
  292. retry_count = 0
  293. minutes = 1
  294. while True:
  295. try:
  296. await self.sync()
  297. return
  298. except IGNotLoggedInError as e:
  299. self.log.exception("Got not logged in error while syncing for refresh")
  300. await self.logout(error=e)
  301. except IGCheckpointError as e:
  302. await self._handle_checkpoint(e, on="refresh")
  303. return
  304. except Exception:
  305. if retry_count >= 4 and minutes < 5:
  306. minutes += 1
  307. retry_count += 1
  308. s = "s" if minutes != 1 else ""
  309. self.log.exception(
  310. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  311. )
  312. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  313. await asyncio.sleep(minutes * 60)
  314. else:
  315. await self.start_listen()
  316. finally:
  317. self._is_refreshing = False
  318. async def _handle_checkpoint(
  319. self, e: IGCheckpointError, on: str, client: AndroidAPI | None = None
  320. ) -> None:
  321. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  322. client = client or self.client
  323. error_code = "ig-checkpoint"
  324. try:
  325. resp = await client.challenge_reset()
  326. self.log.debug(f"Challenge state: {resp.serialize()}")
  327. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  328. error_code = "ig-checkpoint-locked"
  329. except Exception:
  330. self.log.exception("Error resetting challenge state")
  331. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code)
  332. self.client = None
  333. self.mqtt = None
  334. # if on == "connect":
  335. # await self.connect()
  336. # else:
  337. # await self.sync()
  338. async def _sync_thread(self, thread: Thread, min_active_at: int) -> None:
  339. portal = await po.Portal.get_by_thread(thread, self.igpk)
  340. if portal.mxid:
  341. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  342. await portal.update_matrix_room(self, thread, backfill=True)
  343. elif thread.last_activity_at > min_active_at:
  344. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  345. await portal.create_matrix_room(self, thread)
  346. else:
  347. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  348. async def sync(self) -> None:
  349. resp = await self.client.get_inbox()
  350. if not self._listen_task:
  351. await self.start_listen(resp.seq_id, resp.snapshot_at_ms)
  352. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  353. limit = self.config["bridge.chat_sync_limit"]
  354. min_active_at = (time.time() * 1_000_000) - max_age
  355. i = 0
  356. await self.push_bridge_state(BridgeStateEvent.BACKFILLING)
  357. async for thread in self.client.iter_inbox(start_at=resp):
  358. try:
  359. await self._sync_thread(thread, min_active_at)
  360. except Exception:
  361. self.log.exception(f"Error syncing thread {thread.thread_id}")
  362. i += 1
  363. if i >= limit:
  364. break
  365. try:
  366. await self.update_direct_chats()
  367. except Exception:
  368. self.log.exception("Error updating direct chat list")
  369. async def start_listen(
  370. self, seq_id: int | None = None, snapshot_at_ms: int | None = None
  371. ) -> None:
  372. self.shutdown = False
  373. if not seq_id:
  374. resp = await self.client.get_inbox(limit=1)
  375. seq_id, snapshot_at_ms = resp.seq_id, resp.snapshot_at_ms
  376. task = self.listen(seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  377. self._listen_task = self.loop.create_task(task)
  378. async def listen(self, seq_id: int, snapshot_at_ms: int) -> None:
  379. try:
  380. await self.mqtt.listen(
  381. graphql_subs={
  382. GraphQLSubscription.app_presence(),
  383. GraphQLSubscription.direct_typing(self.state.user_id),
  384. GraphQLSubscription.direct_status(),
  385. },
  386. skywalker_subs={
  387. SkywalkerSubscription.direct_sub(self.state.user_id),
  388. SkywalkerSubscription.live_sub(self.state.user_id),
  389. },
  390. seq_id=seq_id,
  391. snapshot_at_ms=snapshot_at_ms,
  392. )
  393. except IrisSubscribeError as e:
  394. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  395. await self.refresh()
  396. except (MQTTNotConnected, MQTTNotLoggedIn) as e:
  397. await self.send_bridge_notice(
  398. f"Error in listener: {e}",
  399. important=True,
  400. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  401. error_code="ig-connection-error",
  402. )
  403. self.mqtt.disconnect()
  404. except Exception:
  405. self.log.exception("Fatal error in listener")
  406. await self.send_bridge_notice(
  407. "Fatal error in listener (see logs for more info)",
  408. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  409. important=True,
  410. error_code="ig-connection-error",
  411. )
  412. self.mqtt.disconnect()
  413. else:
  414. if not self.shutdown:
  415. await self.send_bridge_notice(
  416. "Instagram connection closed without error",
  417. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  418. error_code="ig-disconnected",
  419. )
  420. finally:
  421. self._listen_task = None
  422. self._is_connected = False
  423. self._track_metric(METRIC_CONNECTED, False)
  424. async def stop_listen(self) -> None:
  425. if self.mqtt:
  426. self.shutdown = True
  427. self.mqtt.disconnect()
  428. if self._listen_task:
  429. await self._listen_task
  430. self.shutdown = False
  431. self._track_metric(METRIC_CONNECTED, False)
  432. self._is_connected = False
  433. await self.update()
  434. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  435. if self.client and error is None:
  436. try:
  437. await self.client.logout(one_tap_app_login=False)
  438. except Exception:
  439. self.log.debug("Exception logging out", exc_info=True)
  440. if self.mqtt:
  441. self.mqtt.disconnect()
  442. self._track_metric(METRIC_CONNECTED, False)
  443. self._track_metric(METRIC_LOGGED_IN, False)
  444. if error is None:
  445. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  446. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  447. if puppet and puppet.is_real_user:
  448. await puppet.switch_mxid(None, None)
  449. try:
  450. del self.by_igpk[self.igpk]
  451. except KeyError:
  452. pass
  453. self.igpk = None
  454. else:
  455. self.log.debug("Auth error body: %s", error.body.serialize())
  456. await self.send_bridge_notice(
  457. f"You have been logged out of Instagram: {error.proper_message}",
  458. important=True,
  459. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  460. error_code="ig-auth-error",
  461. error_message=error.proper_message,
  462. )
  463. self.client = None
  464. self.mqtt = None
  465. self.state = None
  466. self._is_logged_in = False
  467. await self.update()
  468. # endregion
  469. # region Event handlers
  470. @async_time(METRIC_MESSAGE)
  471. async def handle_message(self, evt: MessageSyncEvent) -> None:
  472. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  473. if not portal or not portal.mxid:
  474. self.log.debug("Got message in thread with no portal, getting info...")
  475. resp = await self.client.get_thread(evt.message.thread_id)
  476. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  477. self.log.debug("Got info for unknown portal, creating room")
  478. await portal.create_matrix_room(self, resp.thread)
  479. if not portal.mxid:
  480. self.log.warning(
  481. "Room creation appears to have failed, "
  482. f"dropping message in {evt.message.thread_id}"
  483. )
  484. return
  485. self.log.trace(f"Received message sync event {evt.message}")
  486. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  487. if evt.message.op == Operation.ADD:
  488. if not sender:
  489. # I don't think we care about adds with no sender
  490. return
  491. await portal.handle_instagram_item(self, sender, evt.message)
  492. elif evt.message.op == Operation.REMOVE:
  493. # Removes don't have a sender, only the message sender can unsend messages anyway
  494. await portal.handle_instagram_remove(evt.message.item_id)
  495. elif evt.message.op == Operation.REPLACE:
  496. await portal.handle_instagram_update(evt.message)
  497. @async_time(METRIC_THREAD_SYNC)
  498. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  499. self.log.trace("Received thread sync event %s", evt)
  500. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  501. await portal.create_matrix_room(self, evt)
  502. @async_time(METRIC_RTD)
  503. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  504. if not isinstance(evt.value, ActivityIndicatorData):
  505. return
  506. now = int(time.time() * 1000)
  507. date = evt.value.timestamp_ms
  508. expiry = date + evt.value.ttl
  509. if expiry < now:
  510. return
  511. if evt.activity_indicator_id in self._activity_indicator_ids:
  512. return
  513. # TODO clear expired items from this dict
  514. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  515. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  516. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  517. if not puppet or not portal or not portal.mxid:
  518. return
  519. is_typing = evt.value.activity_status != TypingStatus.OFF
  520. if puppet.pk == self.igpk:
  521. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  522. await puppet.intent_for(portal).set_typing(
  523. portal.mxid, is_typing=is_typing, timeout=evt.value.ttl
  524. )
  525. # endregion
  526. # region Database getters
  527. def _add_to_cache(self) -> None:
  528. self.by_mxid[self.mxid] = self
  529. if self.igpk:
  530. self.by_igpk[self.igpk] = self
  531. @classmethod
  532. @async_getter_lock
  533. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  534. # Never allow ghosts to be users
  535. if pu.Puppet.get_id_from_mxid(mxid):
  536. return None
  537. try:
  538. return cls.by_mxid[mxid]
  539. except KeyError:
  540. pass
  541. user = cast(cls, await super().get_by_mxid(mxid))
  542. if user is not None:
  543. user._add_to_cache()
  544. return user
  545. if create:
  546. user = cls(mxid)
  547. await user.insert()
  548. user._add_to_cache()
  549. return user
  550. return None
  551. @classmethod
  552. @async_getter_lock
  553. async def get_by_igpk(cls, igpk: int) -> User | None:
  554. try:
  555. return cls.by_igpk[igpk]
  556. except KeyError:
  557. pass
  558. user = cast(cls, await super().get_by_igpk(igpk))
  559. if user is not None:
  560. user._add_to_cache()
  561. return user
  562. return None
  563. @classmethod
  564. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  565. users = await super().all_logged_in()
  566. user: cls
  567. for index, user in enumerate(users):
  568. try:
  569. yield cls.by_mxid[user.mxid]
  570. except KeyError:
  571. user._add_to_cache()
  572. yield user
  573. # endregion