user.py 49 KB

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