user.py 18 KB

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