user.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 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, Callable, cast
  18. from datetime import datetime, timedelta
  19. from functools import partial
  20. import asyncio
  21. import logging
  22. import time
  23. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState
  24. from mauigpapi.errors import (
  25. IGChallengeError,
  26. IGCheckpointError,
  27. IGConsentRequiredError,
  28. IGNotLoggedInError,
  29. IGRateLimitError,
  30. IGUnknownError,
  31. IGUserIDNotFoundError,
  32. IrisSubscribeError,
  33. MQTTConnectionUnauthorized,
  34. MQTTNotConnected,
  35. MQTTNotLoggedIn,
  36. MQTTReconnectionError,
  37. )
  38. from mauigpapi.mqtt import (
  39. Connect,
  40. Disconnect,
  41. GraphQLSubscription,
  42. NewSequenceID,
  43. ProxyUpdate,
  44. SkywalkerSubscription,
  45. )
  46. from mauigpapi.types import (
  47. ActivityIndicatorData,
  48. CurrentUser,
  49. MessageSyncEvent,
  50. Operation,
  51. RealtimeDirectEvent,
  52. Thread,
  53. ThreadRemoveEvent,
  54. ThreadSyncEvent,
  55. TypingStatus,
  56. )
  57. from mauigpapi.types.direct_inbox import DMInbox, DMInboxResponse
  58. from mautrix.appservice import AppService
  59. from mautrix.bridge import BaseUser, async_getter_lock
  60. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  61. from mautrix.util import background_task
  62. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  63. from mautrix.util.logging import TraceLogger
  64. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  65. from mautrix.util.proxy import RETRYABLE_PROXY_EXCEPTIONS, ProxyHandler
  66. from mautrix.util.simple_lock import SimpleLock
  67. from . import portal as po, puppet as pu
  68. from .config import Config
  69. from .db import Backfill, Message as DBMessage, Portal as DBPortal, User as DBUser
  70. if TYPE_CHECKING:
  71. from .__main__ import InstagramBridge
  72. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  73. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  74. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  75. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  76. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  77. BridgeState.human_readable_errors.update(
  78. {
  79. "ig-connection-error": "Instagram disconnected unexpectedly",
  80. "ig-refresh-connection-error": "Reconnecting failed again after refresh: {message}",
  81. "ig-connection-fatal-error": "Instagram disconnected unexpectedly",
  82. "ig-auth-error": "Authentication error from Instagram: {message}, please login again to continue",
  83. "ig-checkpoint": "Instagram checkpoint error. Please check the Instagram website.",
  84. "ig-consent-required": "Instagram requires a consent update. Please check the Instagram website.",
  85. "ig-checkpoint-locked": "Instagram checkpoint error. Please check the Instagram website.",
  86. "ig-rate-limit": "Got Instagram ratelimit error, waiting a few minutes before retrying...",
  87. "ig-disconnected": None,
  88. "logged-out": "You've been logged out of instagram, please login again to continue",
  89. }
  90. )
  91. class User(DBUser, BaseUser):
  92. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  93. _activity_indicator_ids: dict[str, int] = {}
  94. by_mxid: dict[UserID, User] = {}
  95. by_igpk: dict[int, User] = {}
  96. config: Config
  97. az: AppService
  98. loop: asyncio.AbstractEventLoop
  99. client: AndroidAPI | None
  100. mqtt: AndroidMQTT | None
  101. _listen_task: asyncio.Task | None = None
  102. _sync_lock: SimpleLock
  103. _backfill_loop_task: asyncio.Task | None
  104. _thread_sync_task: asyncio.Task | None
  105. _seq_id_save_task: asyncio.Task | None
  106. permission_level: str
  107. username: str | None
  108. _notice_room_lock: asyncio.Lock
  109. _notice_send_lock: asyncio.Lock
  110. _is_logged_in: bool
  111. _is_connected: bool
  112. shutdown: bool
  113. remote_typing_status: TypingStatus | None
  114. def __init__(
  115. self,
  116. mxid: UserID,
  117. igpk: int | None = None,
  118. state: AndroidState | None = None,
  119. notice_room: RoomID | None = None,
  120. seq_id: int | None = None,
  121. snapshot_at_ms: int | None = None,
  122. oldest_cursor: str | None = None,
  123. total_backfilled_portals: int | None = None,
  124. thread_sync_completed: bool = False,
  125. ) -> None:
  126. super().__init__(
  127. mxid=mxid,
  128. igpk=igpk,
  129. state=state,
  130. notice_room=notice_room,
  131. seq_id=seq_id,
  132. snapshot_at_ms=snapshot_at_ms,
  133. oldest_cursor=oldest_cursor,
  134. total_backfilled_portals=total_backfilled_portals,
  135. thread_sync_completed=thread_sync_completed,
  136. )
  137. BaseUser.__init__(self)
  138. self._notice_room_lock = asyncio.Lock()
  139. self._notice_send_lock = asyncio.Lock()
  140. perms = self.config.get_permissions(mxid)
  141. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  142. self.client = None
  143. self.mqtt = None
  144. self.username = None
  145. self._is_logged_in = False
  146. self._is_connected = False
  147. self._is_refreshing = False
  148. self.shutdown = False
  149. self._sync_lock = SimpleLock(
  150. "Waiting for thread sync to finish before handling %s", log=self.log
  151. )
  152. self._listen_task = None
  153. self._thread_sync_task = None
  154. self._backfill_loop_task = None
  155. self.remote_typing_status = None
  156. self._seq_id_save_task = None
  157. self.proxy_handler = ProxyHandler(
  158. api_url=self.config["bridge.get_proxy_api_url"],
  159. )
  160. @classmethod
  161. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  162. cls.bridge = bridge
  163. cls.config = bridge.config
  164. cls.az = bridge.az
  165. cls.loop = bridge.loop
  166. return (user.try_connect() async for user in cls.all_logged_in())
  167. # region Connection management
  168. async def is_logged_in(self) -> bool:
  169. return bool(self.client) and self._is_logged_in
  170. async def get_puppet(self) -> pu.Puppet | None:
  171. if not self.igpk:
  172. return None
  173. return await pu.Puppet.get_by_pk(self.igpk)
  174. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  175. if not self.igpk:
  176. return None
  177. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  178. if portal:
  179. return portal
  180. if create:
  181. # TODO add error handling somewhere
  182. thread = await self.client.create_group_thread([puppet.pk])
  183. portal = await po.Portal.get_by_thread(thread, self.igpk)
  184. await portal.update_info(thread, self)
  185. return portal
  186. return None
  187. async def try_connect(self) -> None:
  188. try:
  189. await self.connect()
  190. except Exception as e:
  191. self.log.exception("Error while connecting to Instagram")
  192. await self.push_bridge_state(
  193. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  194. )
  195. @property
  196. def api_log(self) -> TraceLogger:
  197. return self.ig_base_log.getChild("http").getChild(self.mxid)
  198. @property
  199. def is_connected(self) -> bool:
  200. return bool(self.client) and bool(self.mqtt) and self._is_connected
  201. async def ensure_connected(self, max_wait_seconds: int = 5) -> None:
  202. sleep_interval = 0.1
  203. max_attempts = max_wait_seconds / sleep_interval
  204. attempts = 0
  205. while True:
  206. if self.is_connected:
  207. return
  208. attempts += 1
  209. if attempts > max_attempts:
  210. raise Exception("You're not connected to instagram")
  211. await asyncio.sleep(sleep_interval)
  212. async def connect(self, user: CurrentUser | None = None) -> None:
  213. if not self.state:
  214. await self.push_bridge_state(
  215. BridgeStateEvent.BAD_CREDENTIALS,
  216. error="logged-out",
  217. info={"cnd_action": "reauth"},
  218. )
  219. return
  220. client = AndroidAPI(
  221. self.state,
  222. log=self.api_log,
  223. proxy_handler=self.proxy_handler,
  224. on_proxy_update=self.on_proxy_update,
  225. )
  226. if not user:
  227. try:
  228. resp = await client.current_user()
  229. user = resp.user
  230. except IGNotLoggedInError as e:
  231. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  232. await self.logout(error=e)
  233. return
  234. except IGCheckpointError as e:
  235. self.log.debug("Checkpoint error content: %s", e.body)
  236. raise
  237. except (IGChallengeError, IGConsentRequiredError) as e:
  238. await self._handle_checkpoint(e, on="connect", client=client)
  239. return
  240. self.client = client
  241. self._is_logged_in = True
  242. self.igpk = user.pk
  243. self.username = user.username
  244. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  245. self._track_metric(METRIC_LOGGED_IN, True)
  246. self.by_igpk[self.igpk] = self
  247. self.mqtt = AndroidMQTT(
  248. self.state,
  249. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid),
  250. proxy_handler=self.proxy_handler,
  251. )
  252. self.mqtt.add_event_handler(Connect, self.on_connect)
  253. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  254. self.mqtt.add_event_handler(NewSequenceID, self.update_seq_id)
  255. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  256. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  257. self.mqtt.add_event_handler(ThreadRemoveEvent, self.handle_thread_remove)
  258. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  259. self.mqtt.add_event_handler(ProxyUpdate, self.on_proxy_update)
  260. await self.update()
  261. self.loop.create_task(self._try_sync_puppet(user))
  262. self.loop.create_task(self._post_connect())
  263. async def _post_connect(self):
  264. # Backfill requests are handled synchronously so as not to overload the homeserver.
  265. # Users can configure their backfill stages to be more or less aggressive with backfilling
  266. # to try and avoid getting banned.
  267. if not self._backfill_loop_task or self._backfill_loop_task.done():
  268. self._backfill_loop_task = asyncio.create_task(self._handle_backfill_requests_loop())
  269. if not self.seq_id:
  270. await self._try_sync()
  271. else:
  272. self.log.debug("Connecting to MQTT directly as resync_on_startup is false")
  273. self.start_listen()
  274. if self.config["bridge.backfill.enable"]:
  275. if self._thread_sync_task and not self._thread_sync_task.done():
  276. self.log.warning("Cancelling existing background thread sync task")
  277. self._thread_sync_task.cancel()
  278. self._thread_sync_task = asyncio.create_task(self.backfill_threads())
  279. async def _handle_backfill_requests_loop(self) -> None:
  280. if not self.config["bridge.backfill.enable"] or not self.config["bridge.backfill.msc2716"]:
  281. return
  282. while True:
  283. await self._sync_lock.wait("backfill request")
  284. req = await Backfill.get_next(self.mxid)
  285. if not req:
  286. await asyncio.sleep(30)
  287. continue
  288. self.log.info("Backfill request %s", req)
  289. try:
  290. portal = await po.Portal.get_by_thread_id(
  291. req.portal_thread_id, receiver=req.portal_receiver
  292. )
  293. await req.mark_dispatched()
  294. await portal.backfill(self, req)
  295. await req.mark_done()
  296. except IGNotLoggedInError as e:
  297. self.log.exception("User got logged out during backfill loop")
  298. await self.logout(error=e)
  299. break
  300. except (IGChallengeError, IGConsentRequiredError) as e:
  301. self.log.exception("User got a challenge during backfill loop")
  302. await self._handle_checkpoint(e, on="backfill")
  303. break
  304. except Exception as e:
  305. self.log.exception("Failed to backfill portal %s: %s", req.portal_thread_id, e)
  306. # Don't try again to backfill this portal for a minute.
  307. await req.set_cooldown_timeout(60)
  308. self._backfill_loop_task = None
  309. async def on_connect(self, evt: Connect) -> None:
  310. self.log.debug("Connected to Instagram")
  311. self._track_metric(METRIC_CONNECTED, True)
  312. self._is_connected = True
  313. await self.send_bridge_notice("Connected to Instagram")
  314. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  315. async def on_disconnect(self, evt: Disconnect) -> None:
  316. self.log.debug("Disconnected from Instagram")
  317. self._track_metric(METRIC_CONNECTED, False)
  318. self._is_connected = False
  319. async def on_proxy_update(self, evt: ProxyUpdate | None = None) -> None:
  320. if self.client:
  321. self.client.setup_http(self.state.cookies.jar)
  322. if self.mqtt:
  323. self.mqtt.setup_proxy()
  324. # TODO this stuff could probably be moved to mautrix-python
  325. async def get_notice_room(self) -> RoomID:
  326. if not self.notice_room:
  327. async with self._notice_room_lock:
  328. # If someone already created the room while this call was waiting,
  329. # don't make a new room
  330. if self.notice_room:
  331. return self.notice_room
  332. creation_content = {}
  333. if not self.config["bridge.federate_rooms"]:
  334. creation_content["m.federate"] = False
  335. self.notice_room = await self.az.intent.create_room(
  336. is_direct=True,
  337. invitees=[self.mxid],
  338. topic="Instagram bridge notices",
  339. creation_content=creation_content,
  340. )
  341. await self.update()
  342. return self.notice_room
  343. async def fill_bridge_state(self, state: BridgeState) -> None:
  344. await super().fill_bridge_state(state)
  345. if not state.remote_id:
  346. if self.igpk:
  347. state.remote_id = str(self.igpk)
  348. else:
  349. try:
  350. state.remote_id = self.state.user_id
  351. except IGUserIDNotFoundError:
  352. state.remote_id = None
  353. if self.username:
  354. state.remote_name = f"@{self.username}"
  355. async def get_bridge_states(self) -> list[BridgeState]:
  356. if not self.state:
  357. return []
  358. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  359. if self.is_connected:
  360. state.state_event = BridgeStateEvent.CONNECTED
  361. elif self._is_refreshing or self.mqtt:
  362. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  363. return [state]
  364. async def send_bridge_notice(
  365. self,
  366. text: str,
  367. edit: EventID | None = None,
  368. state_event: BridgeStateEvent | None = None,
  369. important: bool = False,
  370. error_code: str | None = None,
  371. error_message: str | None = None,
  372. info: dict | None = None,
  373. ) -> EventID | None:
  374. if state_event:
  375. await self.push_bridge_state(
  376. state_event,
  377. error=error_code,
  378. message=error_message if error_code else text,
  379. info=info,
  380. )
  381. if self.config["bridge.disable_bridge_notices"]:
  382. return None
  383. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  384. self.log.debug("Not sending unimportant bridge notice: %s", text)
  385. return None
  386. event_id = None
  387. try:
  388. self.log.debug("Sending bridge notice: %s", text)
  389. content = TextMessageEventContent(
  390. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  391. )
  392. if edit:
  393. content.set_edit(edit)
  394. # This is locked to prevent notices going out in the wrong order
  395. async with self._notice_send_lock:
  396. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  397. except Exception:
  398. self.log.warning("Failed to send bridge notice", exc_info=True)
  399. return edit or event_id
  400. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  401. puppet = await pu.Puppet.get_by_pk(self.igpk)
  402. try:
  403. await puppet.update_info(user_info, self)
  404. except Exception:
  405. self.log.exception("Failed to update own puppet info")
  406. try:
  407. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  408. self.log.info("Automatically enabling custom puppet")
  409. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  410. except Exception:
  411. self.log.exception("Failed to automatically enable custom puppet")
  412. async def _try_sync(self) -> None:
  413. try:
  414. await self.sync()
  415. except Exception as e:
  416. self.log.exception("Exception while syncing")
  417. if isinstance(e, IGCheckpointError):
  418. self.log.debug("Checkpoint error content: %s", e.body)
  419. await self.push_bridge_state(
  420. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  421. )
  422. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  423. return {
  424. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  425. for portal in await DBPortal.find_private_chats_of(self.igpk)
  426. if portal.mxid
  427. }
  428. async def refresh(self, resync: bool = True, update_proxy: bool = False) -> None:
  429. self._is_refreshing = True
  430. try:
  431. await self.stop_listen()
  432. self.state.reset_pigeon_session_id()
  433. if update_proxy and self.proxy_handler.update_proxy_url(reason="reconnect"):
  434. await self.on_proxy_update()
  435. if resync:
  436. retry_count = 0
  437. minutes = 1
  438. while True:
  439. try:
  440. await self.sync()
  441. return
  442. except Exception as e:
  443. if retry_count >= 4 and minutes < 10:
  444. minutes += 1
  445. retry_count += 1
  446. s = "s" if minutes != 1 else ""
  447. self.log.exception(
  448. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  449. )
  450. if isinstance(e, IGCheckpointError):
  451. self.log.debug("Checkpoint error content: %s", e.body)
  452. await self.push_bridge_state(
  453. BridgeStateEvent.UNKNOWN_ERROR,
  454. error="unknown-error",
  455. message="An unknown error occurred while connecting to Instagram",
  456. info={"python_error": str(e)},
  457. )
  458. await asyncio.sleep(minutes * 60)
  459. else:
  460. self.start_listen()
  461. finally:
  462. self._is_refreshing = False
  463. async def _handle_checkpoint(
  464. self,
  465. e: IGChallengeError | IGConsentRequiredError,
  466. on: str,
  467. client: AndroidAPI | None = None,
  468. ) -> None:
  469. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  470. client = client or self.client
  471. self.client = None
  472. self.mqtt = None
  473. if isinstance(e, IGConsentRequiredError):
  474. await self.push_bridge_state(
  475. BridgeStateEvent.BAD_CREDENTIALS,
  476. error="ig-consent-required",
  477. info=e.body.serialize(),
  478. )
  479. return
  480. error_code = "ig-checkpoint"
  481. try:
  482. resp = await client.challenge_reset()
  483. info = {
  484. "challenge_context": (
  485. resp.challenge_context.serialize() if resp.challenge_context_str else None
  486. ),
  487. "step_name": resp.step_name,
  488. "step_data": resp.step_data.serialize() if resp.step_data else None,
  489. "user_id": resp.user_id,
  490. "action": resp.action,
  491. "status": resp.status,
  492. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  493. }
  494. self.log.debug(f"Challenge state: {resp.serialize()}")
  495. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  496. error_code = "ig-checkpoint-locked"
  497. except Exception:
  498. self.log.exception("Error resetting challenge state")
  499. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  500. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  501. async def _sync_thread(self, thread: Thread) -> bool:
  502. """
  503. Sync a specific thread. Returns whether the thread had messages after the last message in
  504. the database before the sync.
  505. """
  506. self.log.debug(f"Syncing thread {thread.thread_id}")
  507. forward_messages = thread.items
  508. assert self.client
  509. portal = await po.Portal.get_by_thread(thread, self.igpk)
  510. assert portal
  511. # Create or update the Matrix room
  512. if not portal.mxid:
  513. await portal.create_matrix_room(self, thread)
  514. else:
  515. await portal.update_matrix_room(self, thread)
  516. if not self.config["bridge.backfill.enable_initial"]:
  517. return True
  518. last_message = await DBMessage.get_last(portal.mxid)
  519. cursor = thread.oldest_cursor
  520. if last_message:
  521. original_number_of_messages = len(thread.items)
  522. new_messages = [
  523. m for m in thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  524. ]
  525. forward_messages = new_messages
  526. portal.log.debug(
  527. f"{len(new_messages)}/{original_number_of_messages} messages are after most recent"
  528. " message."
  529. )
  530. # Fetch more messages until we get back to messages that have been bridged already.
  531. while len(new_messages) > 0 and len(new_messages) == original_number_of_messages:
  532. await asyncio.sleep(self.config["bridge.backfill.incremental.page_delay"])
  533. portal.log.debug("Fetching more messages for forward backfill")
  534. resp = await self.client.get_thread(portal.thread_id, cursor=cursor)
  535. if len(resp.thread.items) == 0:
  536. break
  537. original_number_of_messages = len(resp.thread.items)
  538. new_messages = [
  539. m for m in resp.thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  540. ]
  541. forward_messages = new_messages + forward_messages
  542. cursor = resp.thread.oldest_cursor
  543. portal.log.debug(
  544. f"{len(new_messages)}/{original_number_of_messages} messages are after most "
  545. "recent message."
  546. )
  547. elif not portal.first_event_id:
  548. self.log.debug(
  549. f"Skipping backfilling {portal.thread_id} as the first event ID is not known"
  550. )
  551. return False
  552. if forward_messages:
  553. portal.cursor = cursor
  554. await portal.update()
  555. mark_read = thread.read_state == 0 or (
  556. (hours := self.config["bridge.backfill.unread_hours_threshold"]) > 0
  557. and (
  558. datetime.fromtimestamp(forward_messages[0].timestamp_ms / 1000)
  559. < datetime.now() - timedelta(hours=hours)
  560. )
  561. )
  562. base_insertion_event_id = await portal.backfill_message_page(
  563. self,
  564. list(reversed(forward_messages)),
  565. forward=True,
  566. last_message=last_message,
  567. mark_read=mark_read,
  568. )
  569. if (
  570. not self.bridge.homeserver_software.is_hungry
  571. and self.config["bridge.backfill.msc2716"]
  572. ):
  573. await portal.send_post_backfill_dummy(
  574. forward_messages[0].timestamp, base_insertion_event_id=base_insertion_event_id
  575. )
  576. if (
  577. mark_read
  578. and not self.bridge.homeserver_software.is_hungry
  579. and (puppet := await self.get_puppet())
  580. ):
  581. last_message = await DBMessage.get_last(portal.mxid)
  582. if last_message:
  583. await puppet.intent_for(portal).mark_read(portal.mxid, last_message.mxid)
  584. await portal._update_read_receipts(thread.last_seen_at)
  585. if self.config["bridge.backfill.msc2716"]:
  586. await portal.enqueue_immediate_backfill(self, 1)
  587. return len(forward_messages) > 0
  588. async def sync(self, increment_total_backfilled_portals: bool = False) -> None:
  589. await self.run_with_sync_lock(partial(self._sync, increment_total_backfilled_portals))
  590. async def _sync(self, increment_total_backfilled_portals: bool = False) -> None:
  591. if not self._listen_task:
  592. self.state.reset_pigeon_session_id()
  593. sleep_minutes = 2
  594. while True:
  595. try:
  596. resp = await self.client.get_inbox()
  597. break
  598. except IGNotLoggedInError as e:
  599. self.log.exception("Got not logged in error while syncing")
  600. await self.logout(error=e)
  601. return
  602. except IGRateLimitError as e:
  603. self.log.error(
  604. "Got ratelimit error while trying to get inbox (%s), retrying in %d minutes",
  605. e.body,
  606. sleep_minutes,
  607. )
  608. await self.push_bridge_state(
  609. BridgeStateEvent.TRANSIENT_DISCONNECT, error="ig-rate-limit"
  610. )
  611. await asyncio.sleep(sleep_minutes * 60)
  612. sleep_minutes += 2
  613. except IGCheckpointError as e:
  614. self.log.debug("Checkpoint error content: %s", e.body)
  615. raise
  616. except (IGChallengeError, IGConsentRequiredError) as e:
  617. await self._handle_checkpoint(e, on="sync")
  618. return
  619. self.seq_id = resp.seq_id
  620. self.snapshot_at_ms = resp.snapshot_at_ms
  621. await self.save_seq_id()
  622. if not self._listen_task:
  623. self.start_listen(is_after_sync=True)
  624. sync_count = min(
  625. self.config["bridge.backfill.max_conversations"],
  626. self.config["bridge.max_startup_thread_sync_count"],
  627. )
  628. self.log.debug(f"Fetching {sync_count} threads, 20 at a time...")
  629. local_limit: int | None = sync_count
  630. if sync_count == 0:
  631. return
  632. elif sync_count < 0:
  633. local_limit = None
  634. await self._sync_threads_with_delay(
  635. self.client.iter_inbox(
  636. self._update_seq_id_and_cursor, start_at=resp, local_limit=local_limit
  637. ),
  638. stop_when_threads_have_no_messages_to_backfill=True,
  639. increment_total_backfilled_portals=increment_total_backfilled_portals,
  640. local_limit=local_limit,
  641. )
  642. try:
  643. await self.update_direct_chats()
  644. except Exception:
  645. self.log.exception("Error updating direct chat list")
  646. async def backfill_threads(self):
  647. try:
  648. await self.run_with_sync_lock(self._backfill_threads)
  649. except Exception:
  650. self.log.exception("Error in thread backfill loop")
  651. async def _backfill_threads(self):
  652. assert self.client
  653. if not self.config["bridge.backfill.enable"]:
  654. return
  655. max_conversations = self.config["bridge.backfill.max_conversations"] or 0
  656. if 0 <= max_conversations <= (self.total_backfilled_portals or 0):
  657. self.log.info("Backfill max_conversations count reached, not syncing any more portals")
  658. return
  659. elif self.thread_sync_completed:
  660. self.log.debug("Thread backfill is marked as completed, not syncing more portals")
  661. return
  662. local_limit = (
  663. max_conversations - (self.total_backfilled_portals or 0)
  664. if max_conversations >= 0
  665. else None
  666. )
  667. start_at = None
  668. if self.oldest_cursor:
  669. start_at = DMInboxResponse(
  670. status="",
  671. seq_id=self.seq_id,
  672. snapshot_at_ms=0,
  673. pending_requests_total=0,
  674. has_pending_top_requests=False,
  675. viewer=None,
  676. inbox=DMInbox(
  677. threads=[],
  678. has_older=True,
  679. unseen_count=0,
  680. unseen_count_ts=0,
  681. blended_inbox_enabled=False,
  682. oldest_cursor=self.oldest_cursor,
  683. ),
  684. )
  685. backoff = self.config.get("bridge.backfill.backoff.thread_list", 300)
  686. await self._sync_threads_with_delay(
  687. self.client.iter_inbox(
  688. self._update_seq_id_and_cursor,
  689. start_at=start_at,
  690. local_limit=local_limit,
  691. rate_limit_exceeded_backoff=backoff,
  692. ),
  693. increment_total_backfilled_portals=True,
  694. local_limit=local_limit,
  695. )
  696. await self.update_direct_chats()
  697. def _update_seq_id_and_cursor(self, seq_id: int, cursor: str | None):
  698. self.seq_id = seq_id
  699. if cursor:
  700. self.oldest_cursor = cursor
  701. async def _sync_threads_with_delay(
  702. self,
  703. threads: AsyncIterable[Thread],
  704. increment_total_backfilled_portals: bool = False,
  705. stop_when_threads_have_no_messages_to_backfill: bool = False,
  706. local_limit: int | None = None,
  707. ):
  708. sync_delay = self.config["bridge.backfill.min_sync_thread_delay"]
  709. last_thread_sync_ts = 0.0
  710. found_thread_count = 0
  711. async for thread in threads:
  712. found_thread_count += 1
  713. now = time.monotonic()
  714. if now < last_thread_sync_ts + sync_delay:
  715. delay = last_thread_sync_ts + sync_delay - now
  716. self.log.debug("Thread sync is happening too quickly. Waiting for %ds", delay)
  717. await asyncio.sleep(delay)
  718. last_thread_sync_ts = time.monotonic()
  719. had_new_messages = await self._sync_thread(thread)
  720. if not had_new_messages and stop_when_threads_have_no_messages_to_backfill:
  721. self.log.debug("Got to threads with no new messages. Stopping sync.")
  722. return
  723. if increment_total_backfilled_portals:
  724. self.total_backfilled_portals = (self.total_backfilled_portals or 0) + 1
  725. await self.update()
  726. if local_limit is None or found_thread_count < local_limit:
  727. if local_limit is None:
  728. self.log.info(
  729. "Reached end of thread list with no limit, marking thread sync as completed"
  730. )
  731. else:
  732. self.log.info(
  733. f"Reached end of thread list (got {found_thread_count} with "
  734. f"limit {local_limit}), marking thread sync as completed"
  735. )
  736. self.thread_sync_completed = True
  737. await self.update()
  738. async def run_with_sync_lock(self, func: Callable[[], Awaitable]):
  739. with self._sync_lock:
  740. retry_count = 0
  741. while retry_count < 5:
  742. try:
  743. retry_count += 1
  744. await func()
  745. # The sync was successful. Exit the loop.
  746. return
  747. except IGNotLoggedInError as e:
  748. await self.logout(error=e)
  749. return
  750. except Exception:
  751. self.log.exception(
  752. "Failed to sync threads. Waiting 30 seconds before retrying sync."
  753. )
  754. await asyncio.sleep(30)
  755. # If we get here, it means that the sync has failed five times. If this happens, most
  756. # likely something very bad has happened.
  757. self.log.error("Failed to sync threads five times. Will not retry.")
  758. def start_listen(self, is_after_sync: bool = False) -> None:
  759. self.shutdown = False
  760. task = self._listen(
  761. seq_id=self.seq_id, snapshot_at_ms=self.snapshot_at_ms, is_after_sync=is_after_sync
  762. )
  763. self._listen_task = self.loop.create_task(task)
  764. async def delayed_start_listen(self, sleep: int) -> None:
  765. await asyncio.sleep(sleep)
  766. if self.is_connected:
  767. self.log.debug(
  768. "Already reconnected before delay after MQTT reconnection error finished"
  769. )
  770. else:
  771. self.log.debug("Reconnecting after MQTT connection error")
  772. self.start_listen()
  773. async def fetch_user_and_reconnect(self, sleep_first: int | None = None) -> None:
  774. if sleep_first:
  775. await asyncio.sleep(sleep_first)
  776. if self.is_connected:
  777. self.log.debug("Canceling user fetch, already reconnected")
  778. return
  779. self.log.debug("Refetching current user after disconnection")
  780. errors = 0
  781. while True:
  782. try:
  783. resp = await self.client.current_user()
  784. except RETRYABLE_PROXY_EXCEPTIONS as e:
  785. # These are retried by the client up to 10 times, but we actually want to retry
  786. # these indefinitely so we capture them here again and retry.
  787. self.log.warning(
  788. f"Proxy error fetching user from Instagram: {e}, retrying in 1 minute",
  789. )
  790. await asyncio.sleep(60)
  791. except IGNotLoggedInError as e:
  792. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  793. await self.logout(error=e)
  794. return
  795. except (IGChallengeError, IGConsentRequiredError) as e:
  796. await self._handle_checkpoint(e, on="reconnect")
  797. return
  798. except IGUnknownError as e:
  799. if "non-JSON body" not in e:
  800. raise
  801. errors += 1
  802. if errors > 10:
  803. raise
  804. self.log.warning(
  805. "Non-JSON body while trying to check user for reconnection, retrying in 10s"
  806. )
  807. await asyncio.sleep(10)
  808. except Exception as e:
  809. self.log.exception("Error while reconnecting to Instagram")
  810. if isinstance(e, IGCheckpointError):
  811. self.log.debug("Checkpoint error content: %s", e.body)
  812. await self.push_bridge_state(
  813. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  814. )
  815. return
  816. else:
  817. self.log.debug(f"Confirmed current user {resp.user.pk}")
  818. self.start_listen()
  819. return
  820. async def _listen(self, seq_id: int, snapshot_at_ms: int, is_after_sync: bool) -> None:
  821. try:
  822. await self.mqtt.listen(
  823. graphql_subs={
  824. GraphQLSubscription.app_presence(),
  825. GraphQLSubscription.direct_typing(self.state.user_id),
  826. GraphQLSubscription.direct_status(),
  827. },
  828. skywalker_subs={
  829. SkywalkerSubscription.direct_sub(self.state.user_id),
  830. SkywalkerSubscription.live_sub(self.state.user_id),
  831. },
  832. seq_id=seq_id,
  833. snapshot_at_ms=snapshot_at_ms,
  834. )
  835. except IrisSubscribeError as e:
  836. if is_after_sync:
  837. self.log.exception("Got IrisSubscribeError right after refresh")
  838. await self.send_bridge_notice(
  839. f"Reconnecting failed again after refresh: {e}",
  840. important=True,
  841. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  842. error_code="ig-refresh-connection-error",
  843. error_message=str(e),
  844. info={"python_error": str(e)},
  845. )
  846. else:
  847. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  848. background_task.create(self.refresh())
  849. except MQTTReconnectionError as e:
  850. self.log.warning(
  851. f"Unexpected connection error: {e}, reconnecting in 1 minute", exc_info=True
  852. )
  853. await self.send_bridge_notice(
  854. f"Error in listener: {e}",
  855. important=True,
  856. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  857. error_code="ig-connection-error-socket",
  858. )
  859. self.mqtt.disconnect()
  860. background_task.create(self.delayed_start_listen(sleep=60))
  861. except (MQTTNotConnected, MQTTNotLoggedIn, MQTTConnectionUnauthorized) as e:
  862. self.log.warning(f"Unexpected connection error: {e}, checking auth and reconnecting")
  863. await self.send_bridge_notice(
  864. f"Error in listener: {e}",
  865. important=True,
  866. state_event=BridgeStateEvent.TRANSIENT_DISCONNECT,
  867. error_code="ig-connection-error-maybe-auth",
  868. )
  869. self.mqtt.disconnect()
  870. background_task.create(self.fetch_user_and_reconnect())
  871. except Exception as e:
  872. self.log.exception("Fatal error in listener, reconnecting in 5 minutes")
  873. await self.send_bridge_notice(
  874. "Fatal error in listener (see logs for more info)",
  875. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  876. important=True,
  877. error_code="ig-unknown-connection-error",
  878. info={"python_error": str(e)},
  879. )
  880. self.mqtt.disconnect()
  881. background_task.create(self.fetch_user_and_reconnect(sleep_first=300))
  882. else:
  883. if not self.shutdown:
  884. await self.send_bridge_notice(
  885. "Instagram connection closed without error",
  886. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  887. error_code="ig-disconnected",
  888. )
  889. finally:
  890. self._listen_task = None
  891. self._is_connected = False
  892. self._track_metric(METRIC_CONNECTED, False)
  893. async def stop_listen(self) -> None:
  894. if self.mqtt:
  895. self.shutdown = True
  896. self.mqtt.disconnect()
  897. if self._listen_task:
  898. await self._listen_task
  899. self.shutdown = False
  900. self._track_metric(METRIC_CONNECTED, False)
  901. self._is_connected = False
  902. await self.update()
  903. def stop_backfill_tasks(self) -> None:
  904. if self._backfill_loop_task:
  905. self._backfill_loop_task.cancel()
  906. self._backfill_loop_task = None
  907. if self._thread_sync_task:
  908. self._thread_sync_task.cancel()
  909. self._thread_sync_task = None
  910. async def logout(self, error: IGNotLoggedInError | None = None) -> None:
  911. await self.stop_listen()
  912. self.stop_backfill_tasks()
  913. if self.client and error is None:
  914. try:
  915. await self.client.logout(one_tap_app_login=False)
  916. except Exception:
  917. self.log.debug("Exception logging out", exc_info=True)
  918. if self.mqtt:
  919. self.mqtt.disconnect()
  920. self._track_metric(METRIC_CONNECTED, False)
  921. self._track_metric(METRIC_LOGGED_IN, False)
  922. if error is None:
  923. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  924. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  925. if puppet and puppet.is_real_user:
  926. await puppet.switch_mxid(None, None)
  927. try:
  928. del self.by_igpk[self.igpk]
  929. except KeyError:
  930. pass
  931. self.igpk = None
  932. else:
  933. self.log.debug("Auth error body: %s", error.body.serialize())
  934. await self.send_bridge_notice(
  935. f"You have been logged out of Instagram: {error.proper_message}",
  936. important=True,
  937. state_event=BridgeStateEvent.BAD_CREDENTIALS,
  938. error_code="ig-auth-error",
  939. error_message=error.proper_message,
  940. info={"cnd_action": "reauth"},
  941. )
  942. self.client = None
  943. self.mqtt = None
  944. self.state = None
  945. self.seq_id = None
  946. self.snapshot_at_ms = None
  947. self.thread_sync_completed = False
  948. self._is_logged_in = False
  949. await self.update()
  950. # endregion
  951. # region Event handlers
  952. async def _save_seq_id_after_sleep(self) -> None:
  953. await asyncio.sleep(120)
  954. self._seq_id_save_task = None
  955. self.log.trace("Saving sequence ID %d/%d", self.seq_id, self.snapshot_at_ms)
  956. try:
  957. await self.save_seq_id()
  958. except Exception:
  959. self.log.exception("Error saving sequence ID")
  960. async def update_seq_id(self, evt: NewSequenceID) -> None:
  961. self.seq_id = evt.seq_id
  962. self.snapshot_at_ms = evt.snapshot_at_ms
  963. if not self._seq_id_save_task or self._seq_id_save_task.done():
  964. self.log.trace("Starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  965. self._seq_id_save_task = asyncio.create_task(self._save_seq_id_after_sleep())
  966. else:
  967. self.log.trace("Not starting seq id save task (%d/%d)", evt.seq_id, evt.snapshot_at_ms)
  968. @async_time(METRIC_MESSAGE)
  969. async def handle_message(self, evt: MessageSyncEvent) -> None:
  970. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  971. if not portal or not portal.mxid:
  972. self.log.debug("Got message in thread with no portal, getting info...")
  973. resp = await self.client.get_thread(evt.message.thread_id)
  974. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  975. self.log.debug("Got info for unknown portal, creating room")
  976. await portal.create_matrix_room(self, resp.thread)
  977. if not portal.mxid:
  978. self.log.warning(
  979. "Room creation appears to have failed, "
  980. f"dropping message in {evt.message.thread_id}"
  981. )
  982. return
  983. self.log.trace(f"Received message sync event {evt.message}")
  984. if evt.message.new_reaction:
  985. await portal.handle_instagram_reaction(
  986. evt.message, remove=evt.message.op == Operation.REMOVE
  987. )
  988. return
  989. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  990. if evt.message.op == Operation.ADD:
  991. if not sender:
  992. # I don't think we care about adds with no sender
  993. return
  994. await portal.handle_instagram_item(self, sender, evt.message)
  995. elif evt.message.op == Operation.REMOVE:
  996. # Removes don't have a sender, only the message sender can unsend messages anyway
  997. await portal.handle_instagram_remove(evt.message.item_id)
  998. elif evt.message.op == Operation.REPLACE:
  999. await portal.handle_instagram_update(evt.message)
  1000. @async_time(METRIC_THREAD_SYNC)
  1001. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  1002. self.log.trace("Thread sync event content: %s", evt)
  1003. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  1004. if portal.mxid:
  1005. self.log.debug("Got thread sync event for %s with existing portal", portal.thread_id)
  1006. await portal.update_matrix_room(self, evt)
  1007. elif evt.is_group:
  1008. self.log.debug(
  1009. "Got thread sync event for group %s without existing portal, creating room",
  1010. portal.thread_id,
  1011. )
  1012. await portal.create_matrix_room(self, evt)
  1013. else:
  1014. self.log.debug(
  1015. "Got thread sync event for DM %s without existing portal, ignoring",
  1016. portal.thread_id,
  1017. )
  1018. async def handle_thread_remove(self, evt: ThreadRemoveEvent) -> None:
  1019. self.log.debug("Got thread remove event: %s", evt.serialize())
  1020. @async_time(METRIC_RTD)
  1021. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  1022. if not isinstance(evt.value, ActivityIndicatorData):
  1023. return
  1024. now = int(time.time() * 1000)
  1025. date = evt.value.timestamp_ms
  1026. expiry = date + evt.value.ttl
  1027. if expiry < now:
  1028. return
  1029. if evt.activity_indicator_id in self._activity_indicator_ids:
  1030. return
  1031. # TODO clear expired items from this dict
  1032. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  1033. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  1034. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  1035. if not puppet or not portal or not portal.mxid:
  1036. return
  1037. is_typing = evt.value.activity_status != TypingStatus.OFF
  1038. if puppet.pk == self.igpk:
  1039. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  1040. await puppet.intent_for(portal).set_typing(portal.mxid, timeout=evt.value.ttl)
  1041. # endregion
  1042. # region Database getters
  1043. def _add_to_cache(self) -> None:
  1044. self.by_mxid[self.mxid] = self
  1045. if self.igpk:
  1046. self.by_igpk[self.igpk] = self
  1047. @classmethod
  1048. @async_getter_lock
  1049. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  1050. # Never allow ghosts to be users
  1051. if pu.Puppet.get_id_from_mxid(mxid):
  1052. return None
  1053. try:
  1054. return cls.by_mxid[mxid]
  1055. except KeyError:
  1056. pass
  1057. user = cast(cls, await super().get_by_mxid(mxid))
  1058. if user is not None:
  1059. user._add_to_cache()
  1060. return user
  1061. if create:
  1062. user = cls(mxid)
  1063. await user.insert()
  1064. user._add_to_cache()
  1065. return user
  1066. return None
  1067. @classmethod
  1068. @async_getter_lock
  1069. async def get_by_igpk(cls, igpk: int) -> User | None:
  1070. try:
  1071. return cls.by_igpk[igpk]
  1072. except KeyError:
  1073. pass
  1074. user = cast(cls, await super().get_by_igpk(igpk))
  1075. if user is not None:
  1076. user._add_to_cache()
  1077. return user
  1078. return None
  1079. @classmethod
  1080. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  1081. users = await super().all_logged_in()
  1082. user: cls
  1083. for index, user in enumerate(users):
  1084. try:
  1085. yield cls.by_mxid[user.mxid]
  1086. except KeyError:
  1087. user._add_to_cache()
  1088. yield user
  1089. # endregion