user.py 48 KB

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