user.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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, cast
  18. import asyncio
  19. import logging
  20. import time
  21. from mauigpapi import AndroidAPI, AndroidMQTT, AndroidState
  22. from mauigpapi.errors import (
  23. IGNotLoggedInError,
  24. IGUserIDNotFoundError,
  25. IrisSubscribeError,
  26. MQTTNotConnected,
  27. MQTTNotLoggedIn,
  28. )
  29. from mauigpapi.mqtt import Connect, Disconnect, GraphQLSubscription, SkywalkerSubscription
  30. from mauigpapi.types import (
  31. ActivityIndicatorData,
  32. CurrentUser,
  33. MessageSyncEvent,
  34. Operation,
  35. RealtimeDirectEvent,
  36. Thread,
  37. ThreadSyncEvent,
  38. TypingStatus,
  39. )
  40. from mautrix.appservice import AppService
  41. from mautrix.bridge import BaseUser, async_getter_lock
  42. from mautrix.types import EventID, MessageType, RoomID, TextMessageEventContent, UserID
  43. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  44. from mautrix.util.logging import TraceLogger
  45. from mautrix.util.opt_prometheus import Gauge, Summary, async_time
  46. from . import portal as po, puppet as pu
  47. from .config import Config
  48. from .db import Portal as DBPortal, User as DBUser
  49. if TYPE_CHECKING:
  50. from .__main__ import InstagramBridge
  51. METRIC_MESSAGE = Summary("bridge_on_message", "calls to handle_message")
  52. METRIC_THREAD_SYNC = Summary("bridge_on_thread_sync", "calls to handle_thread_sync")
  53. METRIC_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  54. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  55. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  56. BridgeState.human_readable_errors.update(
  57. {
  58. "ig-connection-error": "Instagram disconnected unexpectedly",
  59. "ig-auth-error": "Authentication error from Instagram: {message}",
  60. "ig-disconnected": None,
  61. "ig-no-mqtt": "You're not connected to Instagram",
  62. "logged-out": "You're not logged into Instagram",
  63. }
  64. )
  65. class User(DBUser, BaseUser):
  66. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  67. _activity_indicator_ids: dict[str, int] = {}
  68. by_mxid: dict[UserID, User] = {}
  69. by_igpk: dict[int, User] = {}
  70. config: Config
  71. az: AppService
  72. loop: asyncio.AbstractEventLoop
  73. client: AndroidAPI | None
  74. mqtt: AndroidMQTT | None
  75. _listen_task: asyncio.Task | None = None
  76. permission_level: str
  77. username: str | None
  78. _notice_room_lock: asyncio.Lock
  79. _notice_send_lock: asyncio.Lock
  80. _is_logged_in: bool
  81. _is_connected: bool
  82. shutdown: bool
  83. remote_typing_status: TypingStatus | None
  84. def __init__(
  85. self,
  86. mxid: UserID,
  87. igpk: int | None = None,
  88. state: AndroidState | None = None,
  89. notice_room: RoomID | None = None,
  90. ) -> None:
  91. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  92. BaseUser.__init__(self)
  93. self._notice_room_lock = asyncio.Lock()
  94. self._notice_send_lock = asyncio.Lock()
  95. perms = self.config.get_permissions(mxid)
  96. self.relay_whitelisted, self.is_whitelisted, self.is_admin, self.permission_level = perms
  97. self.client = None
  98. self.mqtt = None
  99. self.username = None
  100. self._is_logged_in = False
  101. self._is_connected = False
  102. self._is_refreshing = False
  103. self.shutdown = False
  104. self._listen_task = None
  105. self.remote_typing_status = None
  106. @classmethod
  107. def init_cls(cls, bridge: "InstagramBridge") -> AsyncIterable[Awaitable[None]]:
  108. cls.bridge = bridge
  109. cls.config = bridge.config
  110. cls.az = bridge.az
  111. cls.loop = bridge.loop
  112. return (user.try_connect() async for user in cls.all_logged_in())
  113. # region Connection management
  114. async def is_logged_in(self) -> bool:
  115. return bool(self.client) and self._is_logged_in
  116. async def get_puppet(self) -> pu.Puppet | None:
  117. if not self.igpk:
  118. return None
  119. return await pu.Puppet.get_by_pk(self.igpk)
  120. async def get_portal_with(self, puppet: pu.Puppet, create: bool = True) -> po.Portal | None:
  121. # We should probably make this work eventually, but for now, creating chats will just not
  122. # work.
  123. return None
  124. async def try_connect(self) -> None:
  125. try:
  126. await self.connect()
  127. except Exception:
  128. self.log.exception("Error while connecting to Instagram")
  129. @property
  130. def api_log(self) -> TraceLogger:
  131. return self.ig_base_log.getChild("http").getChild(self.mxid)
  132. @property
  133. def is_connected(self) -> bool:
  134. return bool(self.client) and bool(self.mqtt) and self._is_connected
  135. async def connect(self) -> None:
  136. client = AndroidAPI(self.state, log=self.api_log)
  137. try:
  138. resp = await client.current_user()
  139. except IGNotLoggedInError as e:
  140. self.log.warning(f"Failed to connect to Instagram: {e}, logging out")
  141. await self.send_bridge_notice(
  142. f"You have been logged out of Instagram: {e!s}",
  143. important=True,
  144. error_code="ig-auth-error",
  145. error_message=str(e),
  146. )
  147. await self.logout(from_error=True)
  148. return
  149. self.client = client
  150. self._is_logged_in = True
  151. self.igpk = resp.user.pk
  152. self.username = resp.user.username
  153. await self.push_bridge_state(BridgeStateEvent.CONNECTING)
  154. self._track_metric(METRIC_LOGGED_IN, True)
  155. self.by_igpk[self.igpk] = self
  156. self.mqtt = AndroidMQTT(
  157. self.state, loop=self.loop, log=self.ig_base_log.getChild("mqtt").getChild(self.mxid)
  158. )
  159. self.mqtt.add_event_handler(Connect, self.on_connect)
  160. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  161. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  162. self.mqtt.add_event_handler(ThreadSyncEvent, self.handle_thread_sync)
  163. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  164. await self.update()
  165. self.loop.create_task(self._try_sync_puppet(resp.user))
  166. self.loop.create_task(self._try_sync())
  167. async def on_connect(self, evt: Connect) -> None:
  168. self.log.debug("Connected to Instagram")
  169. self._track_metric(METRIC_CONNECTED, True)
  170. self._is_connected = True
  171. await self.send_bridge_notice("Connected to Instagram")
  172. await self.push_bridge_state(BridgeStateEvent.CONNECTED)
  173. async def on_disconnect(self, evt: Disconnect) -> None:
  174. self.log.debug("Disconnected from Instagram")
  175. self._track_metric(METRIC_CONNECTED, False)
  176. self._is_connected = False
  177. # TODO this stuff could probably be moved to mautrix-python
  178. async def get_notice_room(self) -> RoomID:
  179. if not self.notice_room:
  180. async with self._notice_room_lock:
  181. # If someone already created the room while this call was waiting,
  182. # don't make a new room
  183. if self.notice_room:
  184. return self.notice_room
  185. creation_content = {}
  186. if not self.config["bridge.federate_rooms"]:
  187. creation_content["m.federate"] = False
  188. self.notice_room = await self.az.intent.create_room(
  189. is_direct=True,
  190. invitees=[self.mxid],
  191. topic="Instagram bridge notices",
  192. creation_content=creation_content,
  193. )
  194. await self.update()
  195. return self.notice_room
  196. async def fill_bridge_state(self, state: BridgeState) -> None:
  197. await super().fill_bridge_state(state)
  198. if not state.remote_id:
  199. if self.igpk:
  200. state.remote_id = str(self.igpk)
  201. else:
  202. try:
  203. state.remote_id = self.state.user_id
  204. except IGUserIDNotFoundError:
  205. state.remote_id = None
  206. if self.username:
  207. state.remote_name = f"@{self.username}"
  208. async def get_bridge_states(self) -> list[BridgeState]:
  209. if not self.state:
  210. return []
  211. state = BridgeState(state_event=BridgeStateEvent.UNKNOWN_ERROR)
  212. if self.is_connected:
  213. state.state_event = BridgeStateEvent.CONNECTED
  214. elif self._is_refreshing or self.mqtt:
  215. state.state_event = BridgeStateEvent.TRANSIENT_DISCONNECT
  216. return [state]
  217. async def send_bridge_notice(
  218. self,
  219. text: str,
  220. edit: EventID | None = None,
  221. state_event: BridgeStateEvent | None = None,
  222. important: bool = False,
  223. error_code: str | None = None,
  224. error_message: str | None = None,
  225. ) -> EventID | None:
  226. if state_event:
  227. await self.push_bridge_state(
  228. state_event, error=error_code, message=error_message if error_code else text
  229. )
  230. if self.config["bridge.disable_bridge_notices"]:
  231. return None
  232. if not important and not self.config["bridge.unimportant_bridge_notices"]:
  233. self.log.debug("Not sending unimportant bridge notice: %s", text)
  234. return None
  235. event_id = None
  236. try:
  237. self.log.debug("Sending bridge notice: %s", text)
  238. content = TextMessageEventContent(
  239. body=text, msgtype=(MessageType.TEXT if important else MessageType.NOTICE)
  240. )
  241. if edit:
  242. content.set_edit(edit)
  243. # This is locked to prevent notices going out in the wrong order
  244. async with self._notice_send_lock:
  245. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  246. except Exception:
  247. self.log.warning("Failed to send bridge notice", exc_info=True)
  248. return edit or event_id
  249. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  250. puppet = await pu.Puppet.get_by_pk(self.igpk)
  251. try:
  252. await puppet.update_info(user_info, self)
  253. except Exception:
  254. self.log.exception("Failed to update own puppet info")
  255. try:
  256. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  257. self.log.info(f"Automatically enabling custom puppet")
  258. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  259. except Exception:
  260. self.log.exception("Failed to automatically enable custom puppet")
  261. async def _try_sync(self) -> None:
  262. try:
  263. await self.sync()
  264. except Exception:
  265. self.log.exception("Exception while syncing")
  266. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  267. async def get_direct_chats(self) -> dict[UserID, list[RoomID]]:
  268. return {
  269. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  270. for portal in await DBPortal.find_private_chats_of(self.igpk)
  271. if portal.mxid
  272. }
  273. async def refresh(self, resync: bool = True) -> None:
  274. self._is_refreshing = True
  275. try:
  276. await self.stop_listen()
  277. if resync:
  278. retry_count = 0
  279. while True:
  280. try:
  281. await self.sync()
  282. return
  283. except Exception:
  284. if retry_count >= 4:
  285. raise
  286. retry_count += 1
  287. self.log.exception("Error while syncing for refresh, retrying in 1 minute")
  288. await self.push_bridge_state(BridgeStateEvent.UNKNOWN_ERROR)
  289. await asyncio.sleep(60)
  290. else:
  291. await self.start_listen()
  292. finally:
  293. self._is_refreshing = False
  294. async def _sync_thread(self, thread: Thread, min_active_at: int) -> None:
  295. portal = await po.Portal.get_by_thread(thread, self.igpk)
  296. if portal.mxid:
  297. self.log.debug(f"{thread.thread_id} has a portal, syncing and backfilling...")
  298. await portal.update_matrix_room(self, thread, backfill=True)
  299. elif thread.last_activity_at > min_active_at:
  300. self.log.debug(f"{thread.thread_id} has been active recently, creating portal...")
  301. await portal.create_matrix_room(self, thread)
  302. else:
  303. self.log.debug(f"{thread.thread_id} is not active and doesn't have a portal")
  304. async def sync(self) -> None:
  305. resp = await self.client.get_inbox()
  306. if not self._listen_task:
  307. await self.start_listen(resp.seq_id, resp.snapshot_at_ms)
  308. max_age = self.config["bridge.portal_create_max_age"] * 1_000_000
  309. limit = self.config["bridge.chat_sync_limit"]
  310. min_active_at = (time.time() * 1_000_000) - max_age
  311. i = 0
  312. await self.push_bridge_state(BridgeStateEvent.BACKFILLING)
  313. async for thread in self.client.iter_inbox(start_at=resp):
  314. try:
  315. await self._sync_thread(thread, min_active_at)
  316. except Exception:
  317. self.log.exception(f"Error syncing thread {thread.thread_id}")
  318. i += 1
  319. if i >= limit:
  320. break
  321. try:
  322. await self.update_direct_chats()
  323. except Exception:
  324. self.log.exception("Error updating direct chat list")
  325. async def start_listen(
  326. self, seq_id: int | None = None, snapshot_at_ms: int | None = None
  327. ) -> None:
  328. self.shutdown = False
  329. if not seq_id:
  330. resp = await self.client.get_inbox(limit=1)
  331. seq_id, snapshot_at_ms = resp.seq_id, resp.snapshot_at_ms
  332. task = self.listen(seq_id=seq_id, snapshot_at_ms=snapshot_at_ms)
  333. self._listen_task = self.loop.create_task(task)
  334. async def listen(self, seq_id: int, snapshot_at_ms: int) -> None:
  335. try:
  336. await self.mqtt.listen(
  337. graphql_subs={
  338. GraphQLSubscription.app_presence(),
  339. GraphQLSubscription.direct_typing(self.state.user_id),
  340. GraphQLSubscription.direct_status(),
  341. },
  342. skywalker_subs={
  343. SkywalkerSubscription.direct_sub(self.state.user_id),
  344. SkywalkerSubscription.live_sub(self.state.user_id),
  345. },
  346. seq_id=seq_id,
  347. snapshot_at_ms=snapshot_at_ms,
  348. )
  349. except IrisSubscribeError as e:
  350. self.log.warning(f"Got IrisSubscribeError {e}, refreshing...")
  351. await self.refresh()
  352. except (MQTTNotConnected, MQTTNotLoggedIn) as e:
  353. await self.send_bridge_notice(
  354. f"Error in listener: {e}",
  355. important=True,
  356. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  357. error_code="ig-connection-error",
  358. )
  359. self.mqtt.disconnect()
  360. except Exception:
  361. self.log.exception("Fatal error in listener")
  362. await self.send_bridge_notice(
  363. "Fatal error in listener (see logs for more info)",
  364. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  365. important=True,
  366. error_code="ig-connection-error",
  367. )
  368. self.mqtt.disconnect()
  369. else:
  370. if not self.shutdown:
  371. await self.send_bridge_notice(
  372. "Instagram connection closed without error",
  373. state_event=BridgeStateEvent.UNKNOWN_ERROR,
  374. error_code="ig-disconnected",
  375. )
  376. finally:
  377. self._listen_task = None
  378. self._is_connected = False
  379. self._track_metric(METRIC_CONNECTED, False)
  380. async def stop_listen(self) -> None:
  381. if self.mqtt:
  382. self.shutdown = True
  383. self.mqtt.disconnect()
  384. if self._listen_task:
  385. await self._listen_task
  386. self.shutdown = False
  387. self._track_metric(METRIC_CONNECTED, False)
  388. self._is_connected = False
  389. await self.update()
  390. async def logout(self, from_error: bool = False) -> None:
  391. if self.client:
  392. try:
  393. await self.client.logout(one_tap_app_login=False)
  394. except Exception:
  395. self.log.debug("Exception logging out", exc_info=True)
  396. if self.mqtt:
  397. self.mqtt.disconnect()
  398. self._track_metric(METRIC_CONNECTED, False)
  399. self._track_metric(METRIC_LOGGED_IN, False)
  400. if not from_error:
  401. await self.push_bridge_state(BridgeStateEvent.LOGGED_OUT)
  402. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  403. if puppet and puppet.is_real_user:
  404. await puppet.switch_mxid(None, None)
  405. try:
  406. del self.by_igpk[self.igpk]
  407. except KeyError:
  408. pass
  409. self.igpk = None
  410. else:
  411. await self.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS)
  412. self.client = None
  413. self.mqtt = None
  414. self.state = None
  415. self._is_logged_in = False
  416. await self.update()
  417. # endregion
  418. # region Event handlers
  419. @async_time(METRIC_MESSAGE)
  420. async def handle_message(self, evt: MessageSyncEvent) -> None:
  421. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  422. if not portal or not portal.mxid:
  423. self.log.debug("Got message in thread with no portal, getting info...")
  424. resp = await self.client.get_thread(evt.message.thread_id)
  425. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  426. self.log.debug("Got info for unknown portal, creating room")
  427. await portal.create_matrix_room(self, resp.thread)
  428. if not portal.mxid:
  429. self.log.warning(
  430. "Room creation appears to have failed, "
  431. f"dropping message in {evt.message.thread_id}"
  432. )
  433. return
  434. self.log.trace(f"Received message sync event {evt.message}")
  435. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  436. if evt.message.op == Operation.ADD:
  437. if not sender:
  438. # I don't think we care about adds with no sender
  439. return
  440. await portal.handle_instagram_item(self, sender, evt.message)
  441. elif evt.message.op == Operation.REMOVE:
  442. # Removes don't have a sender, only the message sender can unsend messages anyway
  443. await portal.handle_instagram_remove(evt.message.item_id)
  444. elif evt.message.op == Operation.REPLACE:
  445. await portal.handle_instagram_update(evt.message)
  446. @async_time(METRIC_THREAD_SYNC)
  447. async def handle_thread_sync(self, evt: ThreadSyncEvent) -> None:
  448. self.log.trace("Received thread sync event %s", evt)
  449. portal = await po.Portal.get_by_thread(evt, receiver=self.igpk)
  450. await portal.create_matrix_room(self, evt)
  451. @async_time(METRIC_RTD)
  452. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  453. if not isinstance(evt.value, ActivityIndicatorData):
  454. return
  455. now = int(time.time() * 1000)
  456. date = int(evt.value.timestamp) // 1000
  457. expiry = date + evt.value.ttl
  458. if expiry < now:
  459. return
  460. if evt.activity_indicator_id in self._activity_indicator_ids:
  461. return
  462. # TODO clear expired items from this dict
  463. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  464. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  465. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  466. if not puppet or not portal or not portal.mxid:
  467. return
  468. is_typing = evt.value.activity_status != TypingStatus.OFF
  469. if puppet.pk == self.igpk:
  470. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  471. await puppet.intent_for(portal).set_typing(
  472. portal.mxid, is_typing=is_typing, timeout=evt.value.ttl
  473. )
  474. # endregion
  475. # region Database getters
  476. def _add_to_cache(self) -> None:
  477. self.by_mxid[self.mxid] = self
  478. if self.igpk:
  479. self.by_igpk[self.igpk] = self
  480. @classmethod
  481. @async_getter_lock
  482. async def get_by_mxid(cls, mxid: UserID, *, create: bool = True) -> User | None:
  483. # Never allow ghosts to be users
  484. if pu.Puppet.get_id_from_mxid(mxid):
  485. return None
  486. try:
  487. return cls.by_mxid[mxid]
  488. except KeyError:
  489. pass
  490. user = cast(cls, await super().get_by_mxid(mxid))
  491. if user is not None:
  492. user._add_to_cache()
  493. return user
  494. if create:
  495. user = cls(mxid)
  496. await user.insert()
  497. user._add_to_cache()
  498. return user
  499. return None
  500. @classmethod
  501. @async_getter_lock
  502. async def get_by_igpk(cls, igpk: int) -> User | None:
  503. try:
  504. return cls.by_igpk[igpk]
  505. except KeyError:
  506. pass
  507. user = cast(cls, await super().get_by_igpk(igpk))
  508. if user is not None:
  509. user._add_to_cache()
  510. return user
  511. return None
  512. @classmethod
  513. async def all_logged_in(cls) -> AsyncGenerator[User, None]:
  514. users = await super().all_logged_in()
  515. user: cls
  516. for index, user in enumerate(users):
  517. try:
  518. yield cls.by_mxid[user.mxid]
  519. except KeyError:
  520. user._add_to_cache()
  521. yield user
  522. # endregion