user.py 50 KB

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