user.py 25 KB

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