user.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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)
  26. from mauigpapi.errors import IGNotLoggedInError
  27. from mautrix.bridge import BaseUser
  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_RTD = Summary("bridge_on_rtd", "calls to handle_rtd")
  39. METRIC_LOGGED_IN = Gauge("bridge_logged_in", "Users logged into the bridge")
  40. METRIC_CONNECTED = Gauge("bridge_connected", "Bridged users connected to Instagram")
  41. class User(DBUser, BaseUser):
  42. ig_base_log: TraceLogger = logging.getLogger("mau.instagram")
  43. _activity_indicator_ids: Dict[str, int] = {}
  44. by_mxid: Dict[UserID, 'User'] = {}
  45. by_igpk: Dict[int, 'User'] = {}
  46. config: Config
  47. az: AppService
  48. loop: asyncio.AbstractEventLoop
  49. client: Optional[AndroidAPI]
  50. mqtt: Optional[AndroidMQTT]
  51. _listen_task: Optional[asyncio.Task] = None
  52. permission_level: str
  53. username: Optional[str]
  54. _notice_room_lock: asyncio.Lock
  55. _notice_send_lock: asyncio.Lock
  56. _is_logged_in: bool
  57. remote_typing_status: Optional[TypingStatus]
  58. def __init__(self, mxid: UserID, igpk: Optional[int] = None,
  59. state: Optional[AndroidState] = None, notice_room: Optional[RoomID] = None
  60. ) -> None:
  61. super().__init__(mxid=mxid, igpk=igpk, state=state, notice_room=notice_room)
  62. self._notice_room_lock = asyncio.Lock()
  63. self._notice_send_lock = asyncio.Lock()
  64. perms = self.config.get_permissions(mxid)
  65. self.is_whitelisted, self.is_admin, self.permission_level = perms
  66. self.log = self.log.getChild(self.mxid)
  67. self.client = None
  68. self.mqtt = None
  69. self.username = None
  70. self.dm_update_lock = asyncio.Lock()
  71. self._metric_value = defaultdict(lambda: False)
  72. self._is_logged_in = False
  73. self._listen_task = None
  74. self.command_status = None
  75. self.remote_typing_status = None
  76. @classmethod
  77. def init_cls(cls, bridge: 'InstagramBridge') -> AsyncIterable[Awaitable[None]]:
  78. cls.bridge = bridge
  79. cls.config = bridge.config
  80. cls.az = bridge.az
  81. cls.loop = bridge.loop
  82. return (user.try_connect() async for user in cls.all_logged_in())
  83. # region Connection management
  84. async def is_logged_in(self) -> bool:
  85. return bool(self.client) and self._is_logged_in
  86. async def try_connect(self) -> None:
  87. try:
  88. await self.connect()
  89. except Exception:
  90. self.log.exception("Error while connecting to Instagram")
  91. @property
  92. def api_log(self) -> TraceLogger:
  93. return self.ig_base_log.getChild("http").getChild(self.mxid)
  94. async def connect(self) -> None:
  95. client = AndroidAPI(self.state, log=self.api_log)
  96. try:
  97. resp = await client.current_user()
  98. except IGNotLoggedInError as e:
  99. self.log.warning(f"Failed to connect to Instagram: {e}")
  100. # TODO show reason?
  101. await self.send_bridge_notice("You have been logged out of Instagram")
  102. return
  103. self.client = client
  104. self._is_logged_in = True
  105. self.igpk = resp.user.pk
  106. self.username = resp.user.username
  107. self._track_metric(METRIC_LOGGED_IN, True)
  108. self.by_igpk[self.igpk] = self
  109. self.mqtt = AndroidMQTT(self.state, loop=self.loop,
  110. log=self.ig_base_log.getChild("mqtt").getChild(self.mxid))
  111. self.mqtt.add_event_handler(Connect, self.on_connect)
  112. self.mqtt.add_event_handler(Disconnect, self.on_disconnect)
  113. self.mqtt.add_event_handler(MessageSyncEvent, self.handle_message)
  114. self.mqtt.add_event_handler(RealtimeDirectEvent, self.handle_rtd)
  115. await self.update()
  116. self.loop.create_task(self._try_sync_puppet(resp.user))
  117. self.loop.create_task(self._try_sync())
  118. async def on_connect(self, evt: Connect) -> None:
  119. self.log.debug("Connected to Instagram")
  120. self._track_metric(METRIC_CONNECTED, True)
  121. async def on_disconnect(self, evt: Disconnect) -> None:
  122. self.log.debug("Disconnected from Instagram")
  123. self._track_metric(METRIC_CONNECTED, False)
  124. # TODO this stuff could probably be moved to mautrix-python
  125. async def get_notice_room(self) -> RoomID:
  126. if not self.notice_room:
  127. async with self._notice_room_lock:
  128. # If someone already created the room while this call was waiting,
  129. # don't make a new room
  130. if self.notice_room:
  131. return self.notice_room
  132. self.notice_room = await self.az.intent.create_room(
  133. is_direct=True, invitees=[self.mxid],
  134. topic="Instagram bridge notices")
  135. await self.update()
  136. return self.notice_room
  137. async def send_bridge_notice(self, text: str, edit: Optional[EventID] = None,
  138. important: bool = False) -> Optional[EventID]:
  139. event_id = None
  140. try:
  141. self.log.debug("Sending bridge notice: %s", text)
  142. content = TextMessageEventContent(body=text, msgtype=(MessageType.TEXT if important
  143. else MessageType.NOTICE))
  144. if edit:
  145. content.set_edit(edit)
  146. # This is locked to prevent notices going out in the wrong order
  147. async with self._notice_send_lock:
  148. event_id = await self.az.intent.send_message(await self.get_notice_room(), content)
  149. except Exception:
  150. self.log.warning("Failed to send bridge notice", exc_info=True)
  151. return edit or event_id
  152. async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
  153. puppet = await pu.Puppet.get_by_pk(self.igpk)
  154. try:
  155. await puppet.update_info(user_info, self)
  156. except Exception:
  157. self.log.exception("Failed to update own puppet info")
  158. try:
  159. if puppet.custom_mxid != self.mxid and puppet.can_auto_login(self.mxid):
  160. self.log.info(f"Automatically enabling custom puppet")
  161. await puppet.switch_mxid(access_token="auto", mxid=self.mxid)
  162. except Exception:
  163. self.log.exception("Failed to automatically enable custom puppet")
  164. async def _try_sync(self) -> None:
  165. try:
  166. await self.sync()
  167. except Exception:
  168. self.log.exception("Exception while syncing")
  169. async def get_direct_chats(self) -> Dict[UserID, List[RoomID]]:
  170. return {
  171. pu.Puppet.get_mxid_from_id(portal.other_user_pk): [portal.mxid]
  172. for portal in await DBPortal.find_private_chats_of(self.igpk)
  173. if portal.mxid
  174. }
  175. async def sync(self) -> None:
  176. resp = await self.client.get_inbox()
  177. limit = self.config["bridge.initial_conversation_sync"]
  178. threads = sorted(resp.inbox.threads, key=lambda thread: thread.last_activity_at)
  179. if limit < 0:
  180. limit = len(threads)
  181. for i, thread in enumerate(threads):
  182. portal = await po.Portal.get_by_thread(thread, self.igpk)
  183. if portal.mxid:
  184. await portal.update_matrix_room(self, thread, backfill=True)
  185. elif i < limit:
  186. await portal.create_matrix_room(self, thread)
  187. await self.update_direct_chats()
  188. self._listen_task = self.loop.create_task(self.mqtt.listen(
  189. graphql_subs={GraphQLSubscription.app_presence(),
  190. GraphQLSubscription.direct_typing(self.state.user_id),
  191. GraphQLSubscription.direct_status()},
  192. skywalker_subs={SkywalkerSubscription.direct_sub(self.state.user_id),
  193. SkywalkerSubscription.live_sub(self.state.user_id)},
  194. seq_id=resp.seq_id, snapshot_at_ms=resp.snapshot_at_ms))
  195. async def stop(self) -> None:
  196. if self.mqtt:
  197. self.mqtt.disconnect()
  198. self._track_metric(METRIC_CONNECTED, False)
  199. await self.update()
  200. async def logout(self) -> None:
  201. if self.client:
  202. try:
  203. await self.client.logout(one_tap_app_login=False)
  204. except Exception:
  205. self.log.debug("Exception logging out", exc_info=True)
  206. if self.mqtt:
  207. self.mqtt.disconnect()
  208. self._track_metric(METRIC_CONNECTED, False)
  209. self._track_metric(METRIC_LOGGED_IN, False)
  210. puppet = await pu.Puppet.get_by_pk(self.igpk, create=False)
  211. if puppet and puppet.is_real_user:
  212. await puppet.switch_mxid(None, None)
  213. try:
  214. del self.by_igpk[self.igpk]
  215. except KeyError:
  216. pass
  217. self.client = None
  218. self.mqtt = None
  219. self.state = None
  220. self.igpk = None
  221. self._is_logged_in = False
  222. await self.update()
  223. # endregion
  224. # region Event handlers
  225. @async_time(METRIC_MESSAGE)
  226. async def handle_message(self, evt: MessageSyncEvent) -> None:
  227. portal = await po.Portal.get_by_thread_id(evt.message.thread_id, receiver=self.igpk)
  228. if not portal or not portal.mxid:
  229. self.log.debug("Got message in thread with no portal, getting info...")
  230. resp = await self.client.get_thread(evt.message.thread_id)
  231. portal = await po.Portal.get_by_thread(resp.thread, self.igpk)
  232. self.log.debug("Got info for unknown portal, creating room")
  233. await portal.create_matrix_room(self, resp.thread)
  234. if not portal.mxid:
  235. self.log.warning("Room creation appears to have failed, "
  236. f"dropping message in {evt.message.thread_id}")
  237. return
  238. self.log.trace(f"Received message sync event {evt.message}")
  239. sender = await pu.Puppet.get_by_pk(evt.message.user_id) if evt.message.user_id else None
  240. if evt.message.op == Operation.ADD:
  241. if not sender:
  242. # I don't think we care about adds with no sender
  243. return
  244. await portal.handle_instagram_item(self, sender, evt.message)
  245. elif evt.message.op == Operation.REMOVE:
  246. # Removes don't have a sender, only the message sender can unsend messages anyway
  247. await portal.handle_instagram_remove(evt.message.item_id)
  248. elif evt.message.op == Operation.REPLACE:
  249. await portal.handle_instagram_update(evt.message)
  250. @async_time(METRIC_RTD)
  251. async def handle_rtd(self, evt: RealtimeDirectEvent) -> None:
  252. if not isinstance(evt.value, ActivityIndicatorData):
  253. return
  254. now = int(time.time() * 1000)
  255. date = int(evt.value.timestamp) // 1000
  256. expiry = date + evt.value.ttl
  257. if expiry < now:
  258. return
  259. if evt.activity_indicator_id in self._activity_indicator_ids:
  260. return
  261. # TODO clear expired items from this dict
  262. self._activity_indicator_ids[evt.activity_indicator_id] = expiry
  263. puppet = await pu.Puppet.get_by_pk(int(evt.value.sender_id))
  264. portal = await po.Portal.get_by_thread_id(evt.thread_id, receiver=self.igpk)
  265. if not puppet or not portal:
  266. return
  267. is_typing = evt.value.activity_status != TypingStatus.OFF
  268. if puppet.pk == self.igpk:
  269. self.remote_typing_status = TypingStatus.TEXT if is_typing else TypingStatus.OFF
  270. await puppet.intent_for(portal).set_typing(portal.mxid, is_typing=is_typing,
  271. timeout=evt.value.ttl)
  272. # endregion
  273. # region Database getters
  274. def _add_to_cache(self) -> None:
  275. self.by_mxid[self.mxid] = self
  276. if self.igpk:
  277. self.by_igpk[self.igpk] = self
  278. @classmethod
  279. async def get_by_mxid(cls, mxid: UserID, create: bool = True) -> Optional['User']:
  280. # Never allow ghosts to be users
  281. if pu.Puppet.get_id_from_mxid(mxid):
  282. return None
  283. try:
  284. return cls.by_mxid[mxid]
  285. except KeyError:
  286. pass
  287. user = cast(cls, await super().get_by_mxid(mxid))
  288. if user is not None:
  289. user._add_to_cache()
  290. return user
  291. if create:
  292. user = cls(mxid)
  293. await user.insert()
  294. user._add_to_cache()
  295. return user
  296. return None
  297. @classmethod
  298. async def get_by_igpk(cls, igpk: int) -> Optional['User']:
  299. try:
  300. return cls.by_igpk[igpk]
  301. except KeyError:
  302. pass
  303. user = cast(cls, await super().get_by_igpk(igpk))
  304. if user is not None:
  305. user._add_to_cache()
  306. return user
  307. return None
  308. @classmethod
  309. async def all_logged_in(cls) -> AsyncGenerator['User', None]:
  310. users = await super().all_logged_in()
  311. user: cls
  312. for index, user in enumerate(users):
  313. try:
  314. yield cls.by_mxid[user.mxid]
  315. except KeyError:
  316. user._add_to_cache()
  317. yield user
  318. # endregion