user.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. IGResponseError,
  31. IGUnknownError,
  32. IGUserIDNotFoundError,
  33. IrisSubscribeError,
  34. MQTTConnectionUnauthorized,
  35. MQTTNotConnected,
  36. MQTTNotLoggedIn,
  37. MQTTReconnectionError,
  38. )
  39. from mauigpapi.mqtt import (
  40. Connect,
  41. Disconnect,
  42. GraphQLSubscription,
  43. NewSequenceID,
  44. ProxyUpdate,
  45. SkywalkerSubscription,
  46. )
  47. from mauigpapi.types import (
  48. ActivityIndicatorData,
  49. CurrentUser,
  50. MessageSyncEvent,
  51. Operation,
  52. RealtimeDirectEvent,
  53. Thread,
  54. ThreadRemoveEvent,
  55. ThreadSyncEvent,
  56. TypingStatus,
  57. )
  58. from mauigpapi.types.direct_inbox import DMInbox, DMInboxResponse
  59. from mautrix.appservice import AppService
  60. from mautrix.bridge import BaseUser, async_getter_lock
  61. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  62. from mautrix.util import background_task
  63. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  64. from mautrix.util.logging import TraceLogger
  65. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  66. from mautrix.util.proxy import RETRYABLE_PROXY_EXCEPTIONS, ProxyHandler
  67. from mautrix.util.simple_lock import SimpleLock
  68. from . import portal as po, puppet as pu
  69. from .config import Config
  70. from .db import Backfill, Message as DBMessage, Portal as DBPortal, User as DBUser
  71. if TYPE_CHECKING:
  72. from .__main__ import InstagramBridge
  73. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  74. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  75. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  76. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  77. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  78. BridgeState.human_readable_errors.update(
  79. {
  80. "ig-connection-error": "Instagram disconnected unexpectedly",
  81. "ig-refresh-connection-error": "Reconnecting failed again after refresh: {message}",
  82. "ig-connection-fatal-error": "Instagram disconnected unexpectedly",
  83. "ig-auth-error": "Authentication error from Instagram: {message}, please login again to continue",
  84. "ig-checkpoint": "Instagram checkpoint error. Please check the Instagram website.",
  85. "ig-consent-required": "Instagram requires a consent update. Please check the Instagram website.",
  86. "ig-checkpoint-locked": "Instagram checkpoint error. Please check the Instagram website.",
  87. "ig-rate-limit": "Got Instagram ratelimit error, waiting a few minutes before retrying...",
  88. "ig-disconnected": None,
  89. "logged-out": "You've been logged out of instagram, please login again to continue",
  90. }
  91. )
  92. class User(DBUser, BaseUser):
  93. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  94. _activity_indicator_ids: dict[str, int] = {}
  95. by_mxid: dict[UserID, User] = {}
  96. by_igpk: dict[int, User] = {}
  97. config: Config
  98. az: AppService
  99. loop: asyncio.AbstractEventLoop
  100. client: AndroidAPI | None
  101. mqtt: AndroidMQTT | None
  102. _listen_task: asyncio.Task | None = None
  103. _sync_lock: SimpleLock
  104. _backfill_loop_task: asyncio.Task | None
  105. _thread_sync_task: asyncio.Task | None
  106. _seq_id_save_task: asyncio.Task | None
  107. permission_level: str
  108. username: str | None
  109. _notice_room_lock: asyncio.Lock
  110. _notice_send_lock: asyncio.Lock
  111. _is_logged_in: bool
  112. _is_connected: bool
  113. shutdown: bool
  114. remote_typing_status: TypingStatus | None
  115. def __init__(
  116. self,
  117. mxid: UserID,
  118. igpk: int | None = None,
  119. state: AndroidState | None = None,
  120. notice_room: RoomID | None = None,
  121. seq_id: int | None = None,
  122. snapshot_at_ms: int | None = None,
  123. oldest_cursor: str | None = None,
  124. total_backfilled_portals: int | None = None,
  125. thread_sync_completed: bool = False,
  126. ) -> None:
  127. super().__init__(
  128. mxid=mxid,
  129. igpk=igpk,
  130. state=state,
  131. notice_room=notice_room,
  132. seq_id=seq_id,
  133. snapshot_at_ms=snapshot_at_ms,
  134. oldest_cursor=oldest_cursor,
  135. total_backfilled_portals=total_backfilled_portals,
  136. thread_sync_completed=thread_sync_completed,
  137. )
  138. BaseUser.__init__(self)
  139. self._notice_room_lock = asyncio.Lock()
  140. self._notice_send_lock = asyncio.Lock()
  141. self.command_status = None
  142. perms = self.config.get_permissions(mxid)
  143. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  144. self.client = None
  145. self.mqtt = None
  146. self.username = None
  147. self._is_logged_in = False
  148. self._is_connected = False
  149. self._is_refreshing = False
  150. self.shutdown = False
  151. self._sync_lock = SimpleLock(
  152. "Waiting for thread sync to finish before handling %s", log=self.log
  153. )
  154. self._listen_task = None
  155. self._thread_sync_task = None
  156. self._backfill_loop_task = None
  157. self.remote_typing_status = None
  158. self._seq_id_save_task = None
  159. self.proxy_handler = ProxyHandler(
  160. api_url=self.config["bridge.get_proxy_api_url"],
  161. )
  162. @classmethod
  163. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  164. cls.bridge = bridge
  165. cls.config = bridge.config
  166. cls.az = bridge.az
  167. cls.loop = bridge.loop
  168. return (user.try_connect() async for user in cls.all_logged_in())
  169. # region Connection management
  170. async def is_logged_in(self) -> bool:
  171. return bool(self.client) and self._is_logged_in
  172. async def get_puppet(self) -> pu.Puppet | None:
  173. if not self.igpk:
  174. return None
  175. return await pu.Puppet.get_by_pk(self.igpk)
  176. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  177. if not self.igpk:
  178. return None
  179. portal = await po.Portal.find_private_chat(self.igpk, puppet.pk)
  180. if portal:
  181. return portal
  182. if create:
  183. # TODO add error handling somewhere
  184. thread = await self.client.create_group_thread([puppet.pk])
  185. portal = await po.Portal.get_by_thread(thread, self.igpk)
  186. await portal.update_info(thread, self)
  187. return portal
  188. return None
  189. async def try_connect(self) -> None:
  190. while True:
  191. try:
  192. await self.connect()
  193. except RETRYABLE_PROXY_EXCEPTIONS as e:
  194. # These are retried by the client up to 10 times, but we actually want to retry
  195. # these indefinitely so we capture them here again and retry.
  196. self.log.warning(
  197. f"Proxy error connecting to Instagram: {e}, retrying in 1 minute",
  198. )
  199. await asyncio.sleep(60)
  200. continue
  201. except Exception as e:
  202. self.log.exception("Error while connecting to Instagram")
  203. await self.push_bridge_state(
  204. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  205. )
  206. return
  207. @property
  208. def api_log(self) -> TraceLogger:
  209. return self.ig_base_log.getChild("http").getChild(self.mxid)
  210. @property
  211. def is_connected(self) -> bool:
  212. return bool(self.client) and bool(self.mqtt) and self._is_connected
  213. async def ensure_connected(self, max_wait_seconds: int = 5) -> None:
  214. sleep_interval = 0.1
  215. max_attempts = max_wait_seconds / sleep_interval
  216. attempts = 0
  217. while True:
  218. if self.is_connected:
  219. return
  220. attempts += 1
  221. if attempts > max_attempts:
  222. raise Exception("You're not connected to instagram")
  223. await asyncio.sleep(sleep_interval)
  224. async def connect(self, user: CurrentUser | None = None) -> None:
  225. if not self.state:
  226. await self.push_bridge_state(
  227. BridgeStateEvent.BAD_CREDENTIALS,
  228. error="logged-out",
  229. info={"cnd_action": "reauth"},
  230. )
  231. return
  232. client = AndroidAPI(
  233. self.state,
  234. log=self.api_log,
  235. proxy_handler=self.proxy_handler,
  236. on_proxy_update=self.on_proxy_update,
  237. on_response_error=self.on_response_error,
  238. )
  239. if not user:
  240. try:
  241. resp = await client.current_user()
  242. user = resp.user
  243. except IGNotLoggedInError as e:
  244. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  245. await self.logout(error=e)
  246. return
  247. except IGCheckpointError as e:
  248. self.log.debug("Checkpoint error content: %s", e.body)
  249. raise
  250. except (IGChallengeError, IGConsentRequiredError) as e:
  251. await self._handle_checkpoint(e, on="connect", client=client)
  252. return
  253. self.client = client
  254. self._is_logged_in = True
  255. self.igpk = user.pk
  256. self.username = user.username
  257. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  258. self._track_metric(METRIC_LOGGED_IN, True)
  259. self.by_igpk[self.igpk] = self
  260. self.mqtt = AndroidMQTT(
  261. self.state,
  262. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid),
  263. proxy_handler=self.proxy_handler,
  264. )
  265. self.mqtt.add_event_handler(Connect, self.on_connect)
  266. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  267. self.mqtt.add_event_handler(NewSequenceID, self.update_seq_id)
  268. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  269. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  270. self.mqtt.add_event_handler(ThreadRemoveEvent, self.handle_thread_remove)
  271. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  272. self.mqtt.add_event_handler(ProxyUpdate, self.on_proxy_update)
  273. await self.update()
  274. self.loop.create_task(self._try_sync_puppet(user))
  275. self.loop.create_task(self._post_connect())
  276. async def _post_connect(self):
  277. # Backfill requests are handled synchronously so as not to overload the homeserver.
  278. # Users can configure their backfill stages to be more or less aggressive with backfilling
  279. # to try and avoid getting banned.
  280. if not self._backfill_loop_task or self._backfill_loop_task.done():
  281. self._backfill_loop_task = asyncio.create_task(self._handle_backfill_requests_loop())
  282. if not self.seq_id:
  283. await self._try_sync()
  284. else:
  285. self.log.debug("Connecting to MQTT directly as resync_on_startup is false")
  286. self.start_listen()
  287. if self.config["bridge.backfill.enable"]:
  288. if self._thread_sync_task and not self._thread_sync_task.done():
  289. self.log.warning("Cancelling existing background thread sync task")
  290. self._thread_sync_task.cancel()
  291. self._thread_sync_task = asyncio.create_task(self.backfill_threads())
  292. if self.bridge.homeserver_software.is_hungry:
  293. self.log.info("Updating contact info for all users")
  294. asyncio.gather(*[puppet.update_contact_info() async for puppet in pu.Puppet.get_all()])
  295. async def _handle_backfill_requests_loop(self) -> None:
  296. if not self.config["bridge.backfill.enable"] or not self.config["bridge.backfill.msc2716"]:
  297. return
  298. while True:
  299. await self._sync_lock.wait("backfill request")
  300. req = await Backfill.get_next(self.mxid)
  301. if not req:
  302. await asyncio.sleep(30)
  303. continue
  304. self.log.info("Backfill request %s", req)
  305. try:
  306. portal = await po.Portal.get_by_thread_id(
  307. req.portal_thread_id, receiver=req.portal_receiver
  308. )
  309. await req.mark_dispatched()
  310. await portal.backfill(self, req)
  311. await req.mark_done()
  312. except IGNotLoggedInError as e:
  313. self.log.exception("User got logged out during backfill loop")
  314. break
  315. except (IGChallengeError, IGConsentRequiredError) as e:
  316. self.log.exception("User got a challenge during backfill loop")
  317. await self._handle_checkpoint(e, on="backfill")
  318. break
  319. except Exception as e:
  320. self.log.exception("Failed to backfill portal %s: %s", req.portal_thread_id, e)
  321. # Don't try again to backfill this portal for a minute.
  322. await req.set_cooldown_timeout(60)
  323. self._backfill_loop_task = None
  324. async def on_connect(self, evt: Connect) -> None:
  325. self.log.debug("Connected to Instagram")
  326. self._track_metric(METRIC_CONNECTED, True)
  327. self._is_connected = True
  328. await self.send_bridge_notice("Connected to Instagram")
  329. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  330. async def on_disconnect(self, evt: Disconnect) -> None:
  331. self.log.debug("Disconnected from Instagram")
  332. self._track_metric(METRIC_CONNECTED, False)
  333. self._is_connected = False
  334. async def on_proxy_update(self, evt: ProxyUpdate | None = None) -> None:
  335. if self.client:
  336. self.client.setup_http(self.state.cookies.jar)
  337. if self.mqtt:
  338. self.mqtt.setup_proxy()
  339. if self.command_status:
  340. self.command_status["api"].setup_http(self.command_status["state"].cookies.jar)
  341. async def on_response_error(self, err: IGResponseError) -> None:
  342. if isinstance(err, IGNotLoggedInError) and (await self.is_logged_in()):
  343. self.log.warning(f"Noticed logout in API error response: {err}")
  344. await self.logout(error=err)
  345. # TODO this stuff could probably be moved to mautrix-python
  346. async def get_notice_room(self) -> RoomID:
  347. if not self.notice_room:
  348. async with self._notice_room_lock:
  349. # If someone already created the room while this call was waiting,
  350. # don't make a new room
  351. if self.notice_room:
  352. return self.notice_room
  353. creation_content = {}
  354. if not self.config["bridge.federate_rooms"]:
  355. creation_content["m.federate"] = False
  356. self.notice_room = await self.az.intent.create_room(
  357. is_direct=True,
  358. invitees=[self.mxid],
  359. topic="Instagram bridge notices",
  360. creation_content=creation_content,
  361. )
  362. await self.update()
  363. return self.notice_room
  364. async def fill_bridge_state(self, state: BridgeState) -> None:
  365. await super().fill_bridge_state(state)
  366. if not state.remote_id:
  367. if self.igpk:
  368. state.remote_id = str(self.igpk)
  369. else:
  370. try:
  371. state.remote_id = self.state.user_id
  372. except IGUserIDNotFoundError:
  373. state.remote_id = None
  374. if self.username:
  375. state.remote_name = f"@{self.username}"
  376. async def get_bridge_states(self) -> list[BridgeState]:
  377. if not self.state:
  378. return []
  379. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  380. if self.is_connected:
  381. state.state_event = BridgeStateEvent.CONNECTED
  382. elif self._is_refreshing or self.mqtt:
  383. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  384. return [state]
  385. async def send_bridge_notice(
  386. self,
  387. text: str,
  388. edit: EventID | None = None,
  389. state_event: BridgeStateEvent | None = None,
  390. important: bool = False,
  391. error_code: str | None = None,
  392. error_message: str | None = None,
  393. info: dict | None = None,
  394. ) -> EventID | None:
  395. if state_event:
  396. await self.push_bridge_state(
  397. state_event,
  398. error=error_code,
  399. message=error_message if error_code else text,
  400. info=info,
  401. )
  402. if self.config["bridge.disable_bridge_notices"]:
  403. return None
  404. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  405. self.log.debug("Not sending unimportant bridge notice: %s", text)
  406. return None
  407. event_id = None
  408. try:
  409. self.log.debug("Sending bridge notice: %s", text)
  410. content = TextMessageEventContent(
  411. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  412. )
  413. if edit:
  414. content.set_edit(edit)
  415. # This is locked to prevent notices going out in the wrong order
  416. async with self._notice_send_lock:
  417. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  418. except Exception:
  419. self.log.warning("Failed to send bridge notice", exc_info=True)
  420. return edit or event_id
  421. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  422. puppet = await pu.Puppet.get_by_pk(self.igpk)
  423. try:
  424. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  425. self.log.info("Automatically enabling custom puppet")
  426. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  427. except Exception:
  428. self.log.exception("Failed to automatically enable custom puppet")
  429. try:
  430. await puppet.update_info(user_info, self)
  431. except Exception:
  432. self.log.exception("Failed to update own puppet info")
  433. async def _try_sync(self) -> None:
  434. try:
  435. await self.sync()
  436. except Exception as e:
  437. self.log.exception("Exception while syncing")
  438. if isinstance(e, IGCheckpointError):
  439. self.log.debug("Checkpoint error content: %s", e.body)
  440. await self.push_bridge_state(
  441. BridgeStateEvent.UNKNOWN_ERROR, info={"python_error": str(e)}
  442. )
  443. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  444. return {
  445. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  446. for portal in await DBPortal.find_private_chats_of(self.igpk)
  447. if portal.mxid
  448. }
  449. async def refresh(self, resync: bool = True, update_proxy: bool = False) -> None:
  450. self._is_refreshing = True
  451. try:
  452. await self.stop_listen()
  453. self.state.reset_pigeon_session_id()
  454. if update_proxy and self.proxy_handler.update_proxy_url(reason="reconnect"):
  455. await self.on_proxy_update()
  456. if resync:
  457. retry_count = 0
  458. minutes = 1
  459. while True:
  460. try:
  461. await self.sync()
  462. return
  463. except Exception as e:
  464. if retry_count >= 4 and minutes < 10:
  465. minutes += 1
  466. retry_count += 1
  467. s = "s" if minutes != 1 else ""
  468. self.log.exception(
  469. f"Error while syncing for refresh, retrying in {minutes} minute{s}"
  470. )
  471. if isinstance(e, IGCheckpointError):
  472. self.log.debug("Checkpoint error content: %s", e.body)
  473. await self.push_bridge_state(
  474. BridgeStateEvent.UNKNOWN_ERROR,
  475. error="unknown-error",
  476. message="An unknown error occurred while connecting to Instagram",
  477. info={"python_error": str(e)},
  478. )
  479. await asyncio.sleep(minutes * 60)
  480. else:
  481. self.start_listen()
  482. finally:
  483. self._is_refreshing = False
  484. async def _handle_checkpoint(
  485. self,
  486. e: IGChallengeError | IGConsentRequiredError,
  487. on: str,
  488. client: AndroidAPI | None = None,
  489. ) -> None:
  490. self.log.warning(f"Got checkpoint error on {on}: {e.body.serialize()}")
  491. client = client or self.client
  492. self.client = None
  493. self.mqtt = None
  494. if isinstance(e, IGConsentRequiredError):
  495. await self.push_bridge_state(
  496. BridgeStateEvent.BAD_CREDENTIALS,
  497. error="ig-consent-required",
  498. info=e.body.serialize(),
  499. )
  500. return
  501. error_code = "ig-checkpoint"
  502. try:
  503. resp = await client.challenge_reset()
  504. info = {
  505. "challenge_context": (
  506. resp.challenge_context.serialize() if resp.challenge_context_str else None
  507. ),
  508. "step_name": resp.step_name,
  509. "step_data": resp.step_data.serialize() if resp.step_data else None,
  510. "user_id": resp.user_id,
  511. "action": resp.action,
  512. "status": resp.status,
  513. "challenge": e.body.challenge.serialize() if e.body.challenge else None,
  514. }
  515. self.log.debug(f"Challenge state: {resp.serialize()}")
  516. if resp.challenge_context.challenge_type_enum == "HACKED_LOCK":
  517. error_code = "ig-checkpoint-locked"
  518. except Exception:
  519. self.log.exception("Error resetting challenge state")
  520. info = {"challenge": e.body.challenge.serialize() if e.body.challenge else None}
  521. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=error_code, info=info)
  522. async def _sync_thread(
  523. self, thread: Thread, enqueue_backfill: bool = True, portal: po.Portal | None = None
  524. ) -> bool:
  525. """
  526. Sync a specific thread. Returns whether the thread had messages after the last message in
  527. the database before the sync.
  528. """
  529. self.log.debug(f"Syncing thread {thread.thread_id}")
  530. forward_messages = thread.items
  531. assert self.client
  532. if not portal:
  533. portal = await po.Portal.get_by_thread(thread, self.igpk)
  534. assert portal
  535. else:
  536. assert portal.thread_id == thread.thread_id
  537. # Create or update the Matrix room
  538. if not portal.mxid:
  539. await portal.create_matrix_room(self, thread)
  540. else:
  541. await portal.update_matrix_room(self, thread)
  542. if not self.config["bridge.backfill.enable_initial"]:
  543. return True
  544. last_message = await DBMessage.get_last(portal.mxid)
  545. cursor = thread.oldest_cursor
  546. if last_message:
  547. original_number_of_messages = len(thread.items)
  548. new_messages = [
  549. m for m in thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  550. ]
  551. forward_messages = new_messages
  552. portal.log.debug(
  553. f"{len(new_messages)}/{original_number_of_messages} messages are after most recent"
  554. " message."
  555. )
  556. # Fetch more messages until we get back to messages that have been bridged already.
  557. while len(new_messages) > 0 and len(new_messages) == original_number_of_messages:
  558. await asyncio.sleep(self.config["bridge.backfill.incremental.page_delay"])
  559. portal.log.debug("Fetching more messages for forward backfill")
  560. resp = await self.client.get_thread(portal.thread_id, cursor=cursor)
  561. if len(resp.thread.items) == 0:
  562. break
  563. original_number_of_messages = len(resp.thread.items)
  564. new_messages = [
  565. m for m in resp.thread.items if last_message.ig_timestamp_ms < m.timestamp_ms
  566. ]
  567. forward_messages = new_messages + forward_messages
  568. cursor = resp.thread.oldest_cursor
  569. portal.log.debug(
  570. f"{len(new_messages)}/{original_number_of_messages} messages are after most "
  571. "recent message."
  572. )
  573. elif not portal.first_event_id:
  574. self.log.debug(
  575. f"Skipping backfilling {portal.thread_id} as the first event ID is not known"
  576. )
  577. return False
  578. if forward_messages:
  579. portal.cursor = cursor
  580. await portal.update()
  581. mark_read = thread.read_state == 0 or (
  582. (hours := self.config["bridge.backfill.unread_hours_threshold"]) > 0
  583. and (
  584. datetime.fromtimestamp(forward_messages[0].timestamp_ms / 1000)
  585. < datetime.now() - timedelta(hours=hours)
  586. )
  587. )
  588. base_insertion_event_id = await portal.backfill_message_page(
  589. self,
  590. list(reversed(forward_messages)),
  591. forward=True,
  592. last_message=last_message,
  593. mark_read=mark_read,
  594. )
  595. if (
  596. not self.bridge.homeserver_software.is_hungry
  597. and self.config["bridge.backfill.msc2716"]
  598. ):
  599. await portal.send_post_backfill_dummy(
  600. forward_messages[0].timestamp, base_insertion_event_id=base_insertion_event_id
  601. )
  602. if (
  603. mark_read
  604. and not self.bridge.homeserver_software.is_hungry
  605. and (puppet := await self.get_puppet())
  606. ):
  607. last_message = await DBMessage.get_last(portal.mxid)
  608. if last_message:
  609. await puppet.intent_for(portal).mark_read(portal.mxid, last_message.mxid)
  610. await portal._update_read_receipts(thread.last_seen_at)
  611. if self.config["bridge.backfill.msc2716"] and enqueue_backfill:
  612. await portal.enqueue_immediate_backfill(self, 1)
  613. return len(forward_messages) > 0
  614. async def sync(self, increment_total_backfilled_portals: bool = False) -> None:
  615. await self.run_with_sync_lock(partial(self._sync, increment_total_backfilled_portals))
  616. async def _sync(self, increment_total_backfilled_portals: bool = False) -> None:
  617. if not self._listen_task:
  618. self.state.reset_pigeon_session_id()
  619. sleep_minutes = 2
  620. while True:
  621. try:
  622. resp = await self.client.get_inbox()
  623. break
  624. except IGNotLoggedInError as e:
  625. self.log.exception("Got not logged in error while syncing")
  626. return
  627. except IGRateLimitError as e:
  628. self.log.error(
  629. "Got ratelimit error while trying to get inbox (%s), retrying in %d minutes",
  630. e.body,
  631. sleep_minutes,
  632. )
  633. await self.push_bridge_state(
  634. BridgeStateEvent.TRANSIENT_DISCONNECT, error="ig-rate-limit"
  635. )
  636. await asyncio.sleep(sleep_minutes * 60)
  637. sleep_minutes += 2
  638. except IGCheckpointError as e:
  639. self.log.debug("Checkpoint error content: %s", e.body)
  640. raise
  641. except (IGChallengeError, IGConsentRequiredError) as e:
  642. await self._handle_checkpoint(e, on="sync")
  643. return
  644. self.seq_id = resp.seq_id
  645. self.snapshot_at_ms = resp.snapshot_at_ms
  646. await self.save_seq_id()
  647. if not self._listen_task:
  648. self.start_listen(is_after_sync=True)
  649. sync_count = min(
  650. self.config["bridge.backfill.max_conversations"],
  651. self.config["bridge.max_startup_thread_sync_count"],
  652. )
  653. self.log.debug(f"Fetching {sync_count} threads, 20 at a time...")
  654. local_limit: int | None = sync_count
  655. if sync_count == 0:
  656. return
  657. elif sync_count < 0:
  658. local_limit = None
  659. await self._sync_threads_with_delay(
  660. self.client.iter_inbox(
  661. self._update_seq_id_and_cursor, start_at=resp, local_limit=local_limit
  662. ),
  663. stop_when_threads_have_no_messages_to_backfill=True,
  664. increment_total_backfilled_portals=increment_total_backfilled_portals,
  665. local_limit=local_limit,
  666. )
  667. try:
  668. await self.update_direct_chats()
  669. except Exception:
  670. self.log.exception("Error updating direct chat list")
  671. async def backfill_threads(self):
  672. try:
  673. await self.run_with_sync_lock(self._backfill_threads)
  674. except Exception:
  675. self.log.exception("Error in thread backfill loop")
  676. async def _backfill_threads(self):
  677. assert self.client
  678. if not self.config["bridge.backfill.enable"]:
  679. return
  680. max_conversations = self.config["bridge.backfill.max_conversations"] or 0
  681. if 0 <= max_conversations <= (self.total_backfilled_portals or 0):
  682. self.log.info("Backfill max_conversations count reached, not syncing any more portals")
  683. return
  684. elif self.thread_sync_completed:
  685. self.log.debug("Thread backfill is marked as completed, not syncing more portals")
  686. return
  687. local_limit = (
  688. max_conversations - (self.total_backfilled_portals or 0)
  689. if max_conversations >= 0
  690. else None
  691. )
  692. start_at = None
  693. if self.oldest_cursor:
  694. start_at = DMInboxResponse(
  695. status="",
  696. seq_id=self.seq_id,
  697. snapshot_at_ms=0,
  698. pending_requests_total=0,
  699. has_pending_top_requests=False,
  700. viewer=None,
  701. inbox=DMInbox(
  702. threads=[],
  703. has_older=True,
  704. unseen_count=0,
  705. unseen_count_ts=0,
  706. blended_inbox_enabled=False,
  707. oldest_cursor=self.oldest_cursor,
  708. ),
  709. )
  710. backoff = self.config.get("bridge.backfill.backoff.thread_list", 300)
  711. await self._sync_threads_with_delay(
  712. self.client.iter_inbox(
  713. self._update_seq_id_and_cursor,
  714. start_at=start_at,
  715. local_limit=local_limit,
  716. rate_limit_exceeded_backoff=backoff,
  717. ),
  718. increment_total_backfilled_portals=True,
  719. local_limit=local_limit,
  720. )
  721. await self.update_direct_chats()
  722. def _update_seq_id_and_cursor(self, seq_id: int, cursor: str | None):
  723. self.seq_id = seq_id
  724. if cursor:
  725. self.oldest_cursor = cursor
  726. async def _sync_threads_with_delay(
  727. self,
  728. threads: AsyncIterable[Thread],
  729. increment_total_backfilled_portals: bool = False,
  730. stop_when_threads_have_no_messages_to_backfill: bool = False,
  731. local_limit: int | None = None,
  732. ):
  733. sync_delay = self.config["bridge.backfill.min_sync_thread_delay"]
  734. last_thread_sync_ts = 0.0
  735. found_thread_count = 0
  736. async for thread in threads:
  737. found_thread_count += 1
  738. now = time.monotonic()
  739. if now < last_thread_sync_ts + sync_delay:
  740. delay = last_thread_sync_ts + sync_delay - now
  741. self.log.debug("Thread sync is happening too quickly. Waiting for %ds", delay)
  742. await asyncio.sleep(delay)
  743. last_thread_sync_ts = time.monotonic()
  744. had_new_messages = await self._sync_thread(thread)
  745. if not had_new_messages and stop_when_threads_have_no_messages_to_backfill:
  746. self.log.debug("Got to threads with no new messages. Stopping sync.")
  747. return
  748. if increment_total_backfilled_portals:
  749. self.total_backfilled_portals = (self.total_backfilled_portals or 0) + 1
  750. await self.update()
  751. if local_limit is None or found_thread_count < local_limit:
  752. if local_limit is None:
  753. self.log.info(
  754. "Reached end of thread list with no limit, marking thread sync as completed"
  755. )
  756. else:
  757. self.log.info(
  758. f"Reached end of thread list (got {found_thread_count} with "
  759. f"limit {local_limit}), marking thread sync as completed"
  760. )
  761. self.thread_sync_completed = True
  762. await self.update()
  763. async def run_with_sync_lock(self, func: Callable[[], Awaitable]):
  764. with self._sync_lock:
  765. retry_count = 0
  766. while retry_count < 5:
  767. try:
  768. retry_count += 1
  769. await func()
  770. # The sync was successful. Exit the loop.
  771. return
  772. except IGNotLoggedInError as e:
  773. return
  774. except Exception:
  775. self.log.exception(
  776. "Failed to sync threads. Waiting 30 seconds before retrying sync."
  777. )
  778. await asyncio.sleep(30)
  779. # If we get here, it means that the sync has failed five times. If this happens, most
  780. # likely something very bad has happened.
  781. self.log.error("Failed to sync threads five times. Will not retry.")
  782. def start_listen(self, is_after_sync: bool = False) -> None:
  783. self.shutdown = False
  784. task = self._listen(
  785. seq_id=self.seq_id, snapshot_at_ms=self.snapshot_at_ms, is_after_sync=is_after_sync
  786. )
  787. self._listen_task = self.loop.create_task(task)
  788. async def delayed_start_listen(self, sleep: int) -> None:
  789. await asyncio.sleep(sleep)
  790. if self.is_connected:
  791. self.log.debug(
  792. "Already reconnected before delay after MQTT reconnection error finished"
  793. )
  794. else:
  795. self.log.debug("Reconnecting after MQTT connection error")
  796. self.start_listen()
  797. async def fetch_user_and_reconnect(self, sleep_first: int | None = None) -> None:
  798. if sleep_first:
  799. await asyncio.sleep(sleep_first)
  800. if self.is_connected:
  801. self.log.debug("Canceling user fetch, already reconnected")
  802. return
  803. self.log.debug("Refetching current user after disconnection")
  804. errors = 0
  805. while True:
  806. try:
  807. resp = await self.client.current_user()
  808. except RETRYABLE_PROXY_EXCEPTIONS as e:
  809. # These are retried by the client up to 10 times, but we actually want to retry
  810. # these indefinitely so we capture them here again and retry.
  811. self.log.warning(
  812. f"Proxy error fetching user from Instagram: {e}, retrying in 1 minute",
  813. )
  814. await asyncio.sleep(60)
  815. except IGNotLoggedInError as e:
  816. self.log.warning(f"Failed to reconnect to Instagram: {e}, logging out")
  817. return
  818. except (IGChallengeError, IGConsentRequiredError) as e:
  819. await self._handle_checkpoint(e, on="reconnect")
  820. return
  821. except IGUnknownError:
  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