user.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. info = {
  341. "challenge_context": (
  342. resp.challenge_context.serialize() if resp.challenge_context_str else None
  343. ),
  344. "step_name": resp.step_name,
  345. "step_data": resp.step_data.serialize() if resp.step_data else None,
  346. "user_id": resp.user_id,
  347. "action": resp.action,
  348. "status": resp.status,
  349. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  350. }
  351. self.log.debug(f"Challenge state: {resp.serialize()}")
  352. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  353. error_code = "ig-checkpoint-locked"
  354. except Exception:
  355. self.log.exception("Error resetting challenge state")
  356. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  357. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  358. # if on == "connect":
  359. # await self.connect()
  360. # else:
  361. # await self.sync()
  362. async def _sync_thread(self, thread: Thread, min_active_at: int) -> None:
  363. portal = await po.Portal.get_by_thread(thread, self.igpk)
  364. if portal.mxid:
  365. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  366. await portal.update_matrix_room(self, thread, backfill=True)
  367. elif thread.last_activity_at > min_active_at:
  368. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  369. await portal.create_matrix_room(self, thread)
  370. else:
  371. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  372. async def sync(self) -> None:
  373. resp = await self.client.get_inbox()
  374. if not self._listen_task:
  375. await self.start_listen(resp.seq_id, resp.snapshot_at_ms)
  376. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  377. limit = self.config["bridge.chat_sync_limit"]
  378. min_active_at = (time.time() * 1_000_000) - max_age
  379. i = 0
  380. await self.push_bridge_state(BridgeStateEvent.BACKFILLING)
  381. async for thread in self.client.iter_inbox(start_at=resp):
  382. try:
  383. await self._sync_thread(thread, min_active_at)
  384. except Exception:
  385. self.log.exception(f"Error syncing thread {thread.thread_id}")
  386. i += 1
  387. if i >= limit:
  388. break
  389. try:
  390. await self.update_direct_chats()
  391. except Exception:
  392. self.log.exception("Error updating direct chat list")
  393. async def start_listen(
  394. self, seq_id: int | None = None, snapshot_at_ms: int | None = None
  395. ) -> None:
  396. self.shutdown = False
  397. if not seq_id:
  398. resp = await self.client.get_inbox(limit=1)
  399. seq_id, snapshot_at_ms = resp.seq_id, resp.snapshot_at_ms
  400. task = self.listen(seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  401. self._listen_task = self.loop.create_task(task)
  402. async def listen(self, seq_id: int, snapshot_at_ms: int) -> None:
  403. try:
  404. await self.mqtt.listen(
  405. graphql_subs={
  406. GraphQLSubscription.app_presence(),
  407. GraphQLSubscription.direct_typing(self.state.user_id),
  408. GraphQLSubscription.direct_status(),
  409. },
  410. skywalker_subs={
  411. SkywalkerSubscription.direct_sub(self.state.user_id),
  412. SkywalkerSubscription.live_sub(self.state.user_id),
  413. },
  414. seq_id=seq_id,
  415. snapshot_at_ms=snapshot_at_ms,
  416. )
  417. except IrisSubscribeError as e:
  418. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  419. await self.refresh()
  420. except (MQTTNotConnected, MQTTNotLoggedIn) as e:
  421. await self.send_bridge_notice(
  422. f"Error in listener: {e}",
  423. important=True,
  424. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  425. error_code="ig-connection-error",
  426. )
  427. self.mqtt.disconnect()
  428. except Exception:
  429. self.log.exception("Fatal error in listener")
  430. await self.send_bridge_notice(
  431. "Fatal error in listener (see logs for more info)",
  432. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  433. important=True,
  434. error_code="ig-connection-error",
  435. )
  436. self.mqtt.disconnect()
  437. else:
  438. if not self.shutdown:
  439. await self.send_bridge_notice(
  440. "Instagram connection closed without error",
  441. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  442. error_code="ig-disconnected",
  443. )
  444. finally:
  445. self._listen_task = None
  446. self._is_connected = False
  447. self._track_metric(METRIC_CONNECTED, False)
  448. async def stop_listen(self) -> None:
  449. if self.mqtt:
  450. self.shutdown = True
  451. self.mqtt.disconnect()
  452. if self._listen_task:
  453. await self._listen_task
  454. self.shutdown = False
  455. self._track_metric(METRIC_CONNECTED, False)
  456. self._is_connected = False
  457. await self.update()
  458. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  459. if self.client and error is None:
  460. try:
  461. await self.client.logout(one_tap_app_login=False)
  462. except Exception:
  463. self.log.debug("Exception logging out", exc_info=True)
  464. if self.mqtt:
  465. self.mqtt.disconnect()
  466. self._track_metric(METRIC_CONNECTED, False)
  467. self._track_metric(METRIC_LOGGED_IN, False)
  468. if error is None:
  469. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  470. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  471. if puppet and puppet.is_real_user:
  472. await puppet.switch_mxid(None, None)
  473. try:
  474. del self.by_igpk[self.igpk]
  475. except KeyError:
  476. pass
  477. self.igpk = None
  478. else:
  479. self.log.debug("Auth error body: %s", error.body.serialize())
  480. await self.send_bridge_notice(
  481. f"You have been logged out of Instagram: {error.proper_message}",
  482. important=True,
  483. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  484. error_code="ig-auth-error",
  485. error_message=error.proper_message,
  486. )
  487. self.client = None
  488. self.mqtt = None
  489. self.state = None
  490. self._is_logged_in = False
  491. await self.update()
  492. # endregion
  493. # region Event handlers
  494. @async_time(METRIC_MESSAGE)
  495. async def handle_message(self, evt: MessageSyncEvent) -> None:
  496. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  497. if not portal or not portal.mxid:
  498. self.log.debug("Got message in thread with no portal, getting info...")
  499. resp = await self.client.get_thread(evt.message.thread_id)
  500. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  501. self.log.debug("Got info for unknown portal, creating room")
  502. await portal.create_matrix_room(self, resp.thread)
  503. if not portal.mxid:
  504. self.log.warning(
  505. "Room creation appears to have failed, "
  506. f"dropping message in {evt.message.thread_id}"
  507. )
  508. return
  509. self.log.trace(f"Received message sync event {evt.message}")
  510. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  511. if evt.message.op == Operation.ADD:
  512. if not sender:
  513. # I don't think we care about adds with no sender
  514. return
  515. await portal.handle_instagram_item(self, sender, evt.message)
  516. elif evt.message.op == Operation.REMOVE:
  517. # Removes don't have a sender, only the message sender can unsend messages anyway
  518. await portal.handle_instagram_remove(evt.message.item_id)
  519. elif evt.message.op == Operation.REPLACE:
  520. await portal.handle_instagram_update(evt.message)
  521. @async_time(METRIC_THREAD_SYNC)
  522. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  523. self.log.trace("Received thread sync event %s", evt)
  524. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  525. await portal.create_matrix_room(self, evt)
  526. @async_time(METRIC_RTD)
  527. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  528. if not isinstance(evt.value, ActivityIndicatorData):
  529. return
  530. now = int(time.time() * 1000)
  531. date = evt.value.timestamp_ms
  532. expiry = date + evt.value.ttl
  533. if expiry < now:
  534. return
  535. if evt.activity_indicator_id in self._activity_indicator_ids:
  536. return
  537. # TODO clear expired items from this dict
  538. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  539. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  540. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  541. if not puppet or not portal or not portal.mxid:
  542. return
  543. is_typing = evt.value.activity_status != TypingStatus.OFF
  544. if puppet.pk == self.igpk:
  545. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  546. await puppet.intent_for(portal).set_typing(
  547. portal.mxid, is_typing=is_typing, timeout=evt.value.ttl
  548. )
  549. # endregion
  550. # region Database getters
  551. def _add_to_cache(self) -> None:
  552. self.by_mxid[self.mxid] = self
  553. if self.igpk:
  554. self.by_igpk[self.igpk] = self
  555. @classmethod
  556. @async_getter_lock
  557. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  558. # Never allow ghosts to be users
  559. if pu.Puppet.get_id_from_mxid(mxid):
  560. return None
  561. try:
  562. return cls.by_mxid[mxid]
  563. except KeyError:
  564. pass
  565. user = cast(cls, await super().get_by_mxid(mxid))
  566. if user is not None:
  567. user._add_to_cache()
  568. return user
  569. if create:
  570. user = cls(mxid)
  571. await user.insert()
  572. user._add_to_cache()
  573. return user
  574. return None
  575. @classmethod
  576. @async_getter_lock
  577. async def get_by_igpk(cls, igpk: int) -> User | None:
  578. try:
  579. return cls.by_igpk[igpk]
  580. except KeyError:
  581. pass
  582. user = cast(cls, await super().get_by_igpk(igpk))
  583. if user is not None:
  584. user._add_to_cache()
  585. return user
  586. return None
  587. @classmethod
  588. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  589. users = await super().all_logged_in()
  590. user: cls
  591. for index, user in enumerate(users):
  592. try:
  593. yield cls.by_mxid[user.mxid]
  594. except KeyError:
  595. user._add_to_cache()
  596. yield user
  597. # endregion