conn.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 Any, Awaitable, Callable, Iterable, Type, TypeVar
  18. from collections import defaultdict
  19. from socket import error as SocketError, socket
  20. import asyncio
  21. import json
  22. import logging
  23. import re
  24. import time
  25. import zlib
  26. from yarl import URL
  27. import paho.mqtt.client as pmc
  28. from mautrix.util import background_task
  29. from mautrix.util.logging import TraceLogger
  30. from mautrix.util.proxy import ProxyHandler, proxy_with_retry
  31. from ..errors import (
  32. IrisSubscribeError,
  33. MQTTConnectionUnauthorized,
  34. MQTTNotConnected,
  35. MQTTNotLoggedIn,
  36. MQTTReconnectionError,
  37. )
  38. from ..state import AndroidState
  39. from ..types import (
  40. AppPresenceEventPayload,
  41. ClientConfigUpdatePayload,
  42. CommandResponse,
  43. IrisPayload,
  44. IrisPayloadData,
  45. LiveVideoCommentPayload,
  46. MessageSyncEvent,
  47. MessageSyncMessage,
  48. Operation,
  49. PubsubEvent,
  50. PubsubPayload,
  51. ReactionStatus,
  52. ReactionType,
  53. RealtimeDirectEvent,
  54. RealtimeZeroProvisionPayload,
  55. ThreadAction,
  56. ThreadItemType,
  57. ThreadRemoveEvent,
  58. ThreadSyncEvent,
  59. TypingStatus,
  60. )
  61. from .events import Connect, Disconnect, NewSequenceID, ProxyUpdate
  62. from .otclient import MQTToTClient
  63. from .subscription import GraphQLQueryID, RealtimeTopic, everclear_subscriptions
  64. from .thrift import ForegroundStateConfig, IncomingMessage, RealtimeClientInfo, RealtimeConfig
  65. try:
  66. import socks
  67. except ImportError:
  68. socks = None
  69. T = TypeVar("T")
  70. ACTIVITY_INDICATOR_REGEX = re.compile(
  71. r"/direct_v2/threads/([\w_]+)/activity_indicator_id/([\w_]+)"
  72. )
  73. INBOX_THREAD_REGEX = re.compile(r"/direct_v2/inbox/threads/([\w_]+)")
  74. REQUEST_PUBLISH_TIMEOUT = 5
  75. REQUEST_RESPONSE_TIMEOUT = 30
  76. class AndroidMQTT:
  77. _loop: asyncio.AbstractEventLoop
  78. _client: MQTToTClient
  79. log: TraceLogger
  80. state: AndroidState
  81. _graphql_subs: set[str]
  82. _skywalker_subs: set[str]
  83. _iris_seq_id: int | None
  84. _iris_snapshot_at_ms: int | None
  85. _publish_waiters: dict[int, asyncio.Future]
  86. _response_waiters: dict[RealtimeTopic, asyncio.Future]
  87. _response_waiter_locks: dict[RealtimeTopic, asyncio.Lock]
  88. _message_response_waiter_lock: asyncio.Lock
  89. _message_response_waiter_id: str | None
  90. _message_response_waiter: asyncio.Future | None
  91. _disconnect_error: Exception | None
  92. _event_handlers: dict[Type[T], list[Callable[[T], Awaitable[None]]]]
  93. _outgoing_events: asyncio.Queue
  94. _event_dispatcher_task: asyncio.Task | None
  95. # region Initialization
  96. def __init__(
  97. self,
  98. state: AndroidState,
  99. log: TraceLogger | None = None,
  100. proxy_handler: ProxyHandler | None = None,
  101. ) -> None:
  102. self._graphql_subs = set()
  103. self._skywalker_subs = set()
  104. self._iris_seq_id = None
  105. self._iris_snapshot_at_ms = None
  106. self._publish_waiters = {}
  107. self._response_waiters = {}
  108. self._message_response_waiter_lock = asyncio.Lock()
  109. self._message_response_waiter_id = None
  110. self._message_response_waiter = None
  111. self._disconnect_error = None
  112. self._response_waiter_locks = defaultdict(lambda: asyncio.Lock())
  113. self._event_handlers = defaultdict(lambda: [])
  114. self._event_dispatcher_task = None
  115. self._outgoing_events = asyncio.Queue()
  116. self.log = log or logging.getLogger("mauigpapi.mqtt")
  117. self._loop = asyncio.get_running_loop()
  118. self.state = state
  119. self._client = MQTToTClient(
  120. client_id=self._form_client_id(),
  121. clean_session=True,
  122. protocol=pmc.MQTTv31,
  123. transport="tcp",
  124. )
  125. self.proxy_handler = proxy_handler
  126. self.setup_proxy()
  127. self._client.enable_logger()
  128. self._client.tls_set()
  129. # mqtt.max_inflight_messages_set(20) # The rest will get queued
  130. # mqtt.max_queued_messages_set(0) # Unlimited messages can be queued
  131. # mqtt.message_retry_set(20) # Retry sending for at least 20 seconds
  132. # mqtt.reconnect_delay_set(min_delay=1, max_delay=120)
  133. self._client.connect_async("edge-mqtt.facebook.com", 443, keepalive=60)
  134. self._client.on_message = self._on_message_handler
  135. self._client.on_publish = self._on_publish_handler
  136. self._client.on_connect = self._on_connect_handler
  137. self._client.on_disconnect = self._on_disconnect_handler
  138. self._client.on_socket_open = self._on_socket_open
  139. self._client.on_socket_close = self._on_socket_close
  140. self._client.on_socket_register_write = self._on_socket_register_write
  141. self._client.on_socket_unregister_write = self._on_socket_unregister_write
  142. def setup_proxy(self):
  143. http_proxy = self.proxy_handler.get_proxy_url() if self.proxy_handler else None
  144. if http_proxy:
  145. if not socks:
  146. self.log.warning("http_proxy is set, but pysocks is not installed")
  147. else:
  148. proxy_url = URL(http_proxy)
  149. proxy_type = {
  150. "http": socks.HTTP,
  151. "https": socks.HTTP,
  152. "socks": socks.SOCKS5,
  153. "socks5": socks.SOCKS5,
  154. "socks4": socks.SOCKS4,
  155. }[proxy_url.scheme]
  156. self._client.proxy_set(
  157. proxy_type=proxy_type,
  158. proxy_addr=proxy_url.host,
  159. proxy_port=proxy_url.port,
  160. proxy_username=proxy_url.user,
  161. proxy_password=proxy_url.password,
  162. )
  163. def _clear_publish_waiters(self) -> None:
  164. for waiter in self._publish_waiters.values():
  165. if not waiter.done():
  166. waiter.set_exception(MQTTNotConnected("MQTT disconnected before PUBACK received"))
  167. self._publish_waiters = {}
  168. def _form_client_id(self) -> bytes:
  169. subscribe_topics = [
  170. RealtimeTopic.PUBSUB, # 88
  171. RealtimeTopic.SUB_IRIS_RESPONSE, # 135
  172. RealtimeTopic.RS_REQ, # 244
  173. RealtimeTopic.REALTIME_SUB, # 149
  174. RealtimeTopic.REGION_HINT, # 150
  175. RealtimeTopic.RS_RESP, # 245
  176. RealtimeTopic.T_RTC_LOG, # 274
  177. RealtimeTopic.SEND_MESSAGE_RESPONSE, # 133
  178. RealtimeTopic.MESSAGE_SYNC, # 146
  179. RealtimeTopic.LIGHTSPEED_RESPONSE, # 179
  180. RealtimeTopic.UNKNOWN_PP, # 34
  181. ]
  182. subscribe_topic_ids = [int(topic.encoded) for topic in subscribe_topics]
  183. password = f"authorization={self.state.session.authorization}"
  184. cfg = RealtimeConfig(
  185. client_identifier=self.state.device.phone_id[:20],
  186. client_info=RealtimeClientInfo(
  187. user_id=int(self.state.user_id),
  188. user_agent=self.state.user_agent,
  189. client_capabilities=0b10110111,
  190. endpoint_capabilities=0,
  191. publish_format=1,
  192. no_automatic_foreground=True,
  193. make_user_available_in_foreground=False,
  194. device_id=self.state.device.phone_id,
  195. is_initially_foreground=False,
  196. network_type=1,
  197. network_subtype=-1,
  198. client_mqtt_session_id=int(time.time() * 1000) & 0xFFFFFFFF,
  199. subscribe_topics=subscribe_topic_ids,
  200. client_type="cookie_auth",
  201. app_id=567067343352427,
  202. # region_preference=self.state.session.region_hint or "LLA",
  203. device_secret="",
  204. client_stack=3,
  205. ),
  206. password=password,
  207. app_specific_info={
  208. "capabilities": self.state.application.CAPABILITIES,
  209. "app_version": self.state.application.APP_VERSION,
  210. "everclear_subscriptions": json.dumps(everclear_subscriptions),
  211. "User-Agent": self.state.user_agent,
  212. "Accept-Language": self.state.device.language.replace("_", "-"),
  213. "platform": "android",
  214. "ig_mqtt_route": "django",
  215. "pubsub_msg_type_blacklist": "direct, typing_type",
  216. "auth_cache_enabled": "1",
  217. },
  218. )
  219. return zlib.compress(cfg.to_thrift(), level=9)
  220. # endregion
  221. def _on_socket_open(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  222. self._loop.add_reader(sock, client.loop_read)
  223. def _on_socket_close(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  224. self._loop.remove_reader(sock)
  225. def _on_socket_register_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  226. self._loop.add_writer(sock, client.loop_write)
  227. def _on_socket_unregister_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  228. self._loop.remove_writer(sock)
  229. def _on_connect_handler(
  230. self, client: MQTToTClient, _: Any, flags: dict[str, Any], rc: int
  231. ) -> None:
  232. if rc != 0:
  233. err = pmc.connack_string(rc)
  234. self.log.error("MQTT Connection Error: %s (%d)", err, rc)
  235. if rc == pmc.CONNACK_REFUSED_NOT_AUTHORIZED:
  236. self._disconnect_error = MQTTConnectionUnauthorized()
  237. self.disconnect()
  238. return
  239. self._loop.create_task(self._post_connect())
  240. def _on_disconnect_handler(self, client: MQTToTClient, _: Any, rc: int) -> None:
  241. err_str = "Generic error." if rc == pmc.MQTT_ERR_NOMEM else pmc.error_string(rc)
  242. self.log.debug("MQTT disconnection code %d: %s", rc, err_str)
  243. self._clear_publish_waiters()
  244. async def _post_connect(self) -> None:
  245. await self._dispatch(Connect())
  246. self.log.debug("Re-subscribing to things after connect")
  247. if self._graphql_subs:
  248. res = await self.graphql_subscribe(self._graphql_subs)
  249. self.log.trace("GraphQL subscribe response: %s", res)
  250. if self._skywalker_subs:
  251. res = await self.skywalker_subscribe(self._skywalker_subs)
  252. self.log.trace("Skywalker subscribe response: %s", res)
  253. if self._iris_seq_id:
  254. retry = 0
  255. while True:
  256. try:
  257. await self.iris_subscribe(self._iris_seq_id, self._iris_snapshot_at_ms)
  258. break
  259. except (asyncio.TimeoutError, IrisSubscribeError) as e:
  260. self.log.exception("Error requesting iris subscribe")
  261. retry += 1
  262. if retry >= 5 or isinstance(e, IrisSubscribeError):
  263. self._disconnect_error = e
  264. self.disconnect()
  265. break
  266. await asyncio.sleep(5)
  267. self.log.debug("Retrying iris subscribe")
  268. def _on_publish_handler(self, client: MQTToTClient, _: Any, mid: int) -> None:
  269. try:
  270. waiter = self._publish_waiters[mid]
  271. except KeyError:
  272. self.log.trace(f"Got publish confirmation for {mid}, but no waiters")
  273. return
  274. self.log.trace(f"Got publish confirmation for {mid}")
  275. if not waiter.done():
  276. waiter.set_result(None)
  277. # region Incoming event parsing
  278. def _parse_direct_thread_path(self, path: str) -> dict:
  279. try:
  280. blank, direct_v2, threads, thread_id, *rest = path.split("/")
  281. except (ValueError, IndexError) as e:
  282. self.log.debug(f"Got {e!r} while parsing path {path}")
  283. raise
  284. if (blank, direct_v2, threads) != ("", "direct_v2", "threads"):
  285. self.log.debug(f"Got unexpected first parts in direct thread path {path}")
  286. raise ValueError("unexpected first three parts in _parse_direct_thread_path")
  287. additional = {"thread_id": thread_id}
  288. if rest:
  289. subitem_key = rest[0]
  290. if subitem_key == "approval_required_for_new_members":
  291. additional["approval_required_for_new_members"] = True
  292. elif subitem_key == "participants" and len(rest) > 2 and rest[2] == "has_seen":
  293. additional["has_seen"] = int(rest[1])
  294. elif subitem_key == "items":
  295. additional["item_id"] = rest[1]
  296. if len(rest) > 4 and rest[2] == "reactions":
  297. additional["reaction_type"] = ReactionType(rest[3])
  298. additional["reaction_user_id"] = int(rest[4])
  299. elif subitem_key in "admin_user_ids":
  300. additional["admin_user_id"] = int(rest[1])
  301. elif subitem_key == "activity_indicator_id":
  302. additional["activity_indicator_id"] = rest[1]
  303. self.log.trace("Parsed path %s -> %s", path, additional)
  304. return additional
  305. def _on_messager_sync_item(self, part: IrisPayloadData, parsed_item: IrisPayload) -> bool:
  306. if part.path.startswith("/direct_v2/threads/"):
  307. raw_message = {
  308. "path": part.path,
  309. "op": part.op,
  310. **self._parse_direct_thread_path(part.path),
  311. }
  312. try:
  313. json_value = json.loads(part.value)
  314. if "reaction_type" in raw_message:
  315. self.log.trace("Treating %s as new reaction data", json_value)
  316. raw_message["new_reaction"] = json_value
  317. json_value["sender_id"] = raw_message.pop("reaction_user_id")
  318. json_value["type"] = raw_message.pop("reaction_type")
  319. json_value["client_context"] = parsed_item.mutation_token
  320. if part.op == Operation.REMOVE:
  321. json_value["emoji"] = None
  322. json_value["timestamp"] = None
  323. else:
  324. raw_message = {
  325. **raw_message,
  326. **json_value,
  327. }
  328. except (json.JSONDecodeError, TypeError):
  329. raw_message["value"] = part.value
  330. message = MessageSyncMessage.deserialize(raw_message)
  331. evt = MessageSyncEvent(iris=parsed_item, message=message)
  332. elif part.path.startswith("/direct_v2/inbox/threads/"):
  333. if part.op == Operation.REMOVE:
  334. blank, direct_v2, inbox, threads, thread_id, *_ = part.path.split("/")
  335. evt = ThreadRemoveEvent.deserialize(
  336. {
  337. "thread_id": thread_id,
  338. "path": part.path,
  339. "op": part.op,
  340. **json.loads(part.value),
  341. }
  342. )
  343. else:
  344. evt = ThreadSyncEvent.deserialize(
  345. {
  346. "path": part.path,
  347. "op": part.op,
  348. **json.loads(part.value),
  349. }
  350. )
  351. else:
  352. self.log.warning(f"Unsupported path {part.path}")
  353. return False
  354. self._outgoing_events.put_nowait(evt)
  355. return True
  356. def _on_message_sync(self, payload: bytes) -> None:
  357. parsed = json.loads(payload.decode("utf-8"))
  358. self.log.trace("Got message sync event: %s", parsed)
  359. has_items = False
  360. for sync_item in parsed:
  361. parsed_item = IrisPayload.deserialize(sync_item)
  362. if self._iris_seq_id < parsed_item.seq_id:
  363. self.log.trace(f"Got new seq_id: {parsed_item.seq_id}")
  364. self._iris_seq_id = parsed_item.seq_id
  365. self._iris_snapshot_at_ms = int(time.time() * 1000)
  366. background_task.create(
  367. self._dispatch(NewSequenceID(self._iris_seq_id, self._iris_snapshot_at_ms))
  368. )
  369. for part in parsed_item.data:
  370. has_items = self._on_messager_sync_item(part, parsed_item) or has_items
  371. if has_items and not self._event_dispatcher_task:
  372. self._event_dispatcher_task = asyncio.create_task(self._dispatcher_loop())
  373. def _on_pubsub(self, payload: bytes) -> None:
  374. parsed_thrift = IncomingMessage.from_thrift(payload)
  375. self.log.trace(f"Got pubsub event {parsed_thrift.topic} / {parsed_thrift.payload}")
  376. message = PubsubPayload.parse_json(parsed_thrift.payload)
  377. for data in message.data:
  378. match = ACTIVITY_INDICATOR_REGEX.match(data.path)
  379. if match:
  380. evt = PubsubEvent(
  381. data=data,
  382. base=message,
  383. thread_id=match.group(1),
  384. activity_indicator_id=match.group(2),
  385. )
  386. self._loop.create_task(self._dispatch(evt))
  387. elif not data.double_publish:
  388. self.log.debug("Pubsub: no activity indicator on data: %s", data)
  389. else:
  390. self.log.debug("Pubsub: double publish: %s", data.path)
  391. def _parse_realtime_sub_item(self, topic: str | GraphQLQueryID, raw: dict) -> Iterable[Any]:
  392. if topic == GraphQLQueryID.APP_PRESENCE:
  393. yield AppPresenceEventPayload.deserialize(raw).presence_event
  394. elif topic == GraphQLQueryID.ZERO_PROVISION:
  395. yield RealtimeZeroProvisionPayload.deserialize(raw).zero_product_provisioning_event
  396. elif topic == GraphQLQueryID.CLIENT_CONFIG_UPDATE:
  397. yield ClientConfigUpdatePayload.deserialize(raw).client_config_update_event
  398. elif topic == GraphQLQueryID.LIVE_REALTIME_COMMENTS:
  399. yield LiveVideoCommentPayload.deserialize(raw).live_video_comment_event
  400. elif topic == "direct":
  401. event = raw["event"]
  402. for item in raw["data"]:
  403. yield RealtimeDirectEvent.deserialize(
  404. {
  405. "event": event,
  406. **self._parse_direct_thread_path(item["path"]),
  407. **item,
  408. }
  409. )
  410. def _on_realtime_sub(self, payload: bytes) -> None:
  411. parsed_thrift = IncomingMessage.from_thrift(payload)
  412. try:
  413. topic = GraphQLQueryID(parsed_thrift.topic)
  414. except ValueError:
  415. topic = parsed_thrift.topic
  416. self.log.trace(f"Got realtime sub event {topic} / {parsed_thrift.payload}")
  417. allowed = (
  418. "direct",
  419. GraphQLQueryID.APP_PRESENCE,
  420. GraphQLQueryID.ZERO_PROVISION,
  421. GraphQLQueryID.CLIENT_CONFIG_UPDATE,
  422. GraphQLQueryID.LIVE_REALTIME_COMMENTS,
  423. )
  424. if topic not in allowed:
  425. return
  426. parsed_json = json.loads(parsed_thrift.payload)
  427. for evt in self._parse_realtime_sub_item(topic, parsed_json):
  428. self._loop.create_task(self._dispatch(evt))
  429. def _handle_send_response(self, message: pmc.MQTTMessage) -> None:
  430. data = json.loads(message.payload.decode("utf-8"))
  431. try:
  432. ccid = data["payload"]["client_context"]
  433. except KeyError:
  434. self.log.warning(
  435. "Didn't find client_context in send message response: %s", message.payload
  436. )
  437. ccid = self._message_response_waiter_id
  438. else:
  439. if ccid != self._message_response_waiter_id:
  440. self.log.error(
  441. "Mismatching client_context in send message response (%s != %s)",
  442. ccid,
  443. self._message_response_waiter_id,
  444. )
  445. return
  446. if self._message_response_waiter and not self._message_response_waiter.done():
  447. self.log.debug("Got response to %s: %s", ccid, message.payload)
  448. self._message_response_waiter.set_result(message)
  449. self._message_response_waiter = None
  450. self._message_response_waiter_id = None
  451. else:
  452. self.log.warning("Didn't find task waiting for response %s", message.payload)
  453. def _on_message_handler(self, client: MQTToTClient, _: Any, message: pmc.MQTTMessage) -> None:
  454. try:
  455. topic = RealtimeTopic.decode(message.topic)
  456. # Instagram Android MQTT messages are always compressed
  457. message.payload = zlib.decompress(message.payload)
  458. if topic == RealtimeTopic.MESSAGE_SYNC:
  459. self._on_message_sync(message.payload)
  460. elif topic == RealtimeTopic.PUBSUB:
  461. self._on_pubsub(message.payload)
  462. elif topic == RealtimeTopic.REALTIME_SUB:
  463. self._on_realtime_sub(message.payload)
  464. elif topic == RealtimeTopic.SEND_MESSAGE_RESPONSE:
  465. self._handle_send_response(message)
  466. else:
  467. try:
  468. waiter = self._response_waiters.pop(topic)
  469. except KeyError:
  470. self.log.debug(
  471. "No handler for MQTT message in %s: %s", topic.value, message.payload
  472. )
  473. else:
  474. if not waiter.done():
  475. waiter.set_result(message)
  476. self.log.trace("Got response %s: %s", topic.value, message.payload)
  477. else:
  478. self.log.debug(
  479. "Got response in %s, but waiter was already cancelled: %s",
  480. topic,
  481. message.payload,
  482. )
  483. except Exception:
  484. self.log.exception("Error in incoming MQTT message handler")
  485. self.log.trace("Errored MQTT payload: %s", message.payload)
  486. # endregion
  487. async def _reconnect(self) -> None:
  488. try:
  489. self.log.trace("Trying to reconnect to MQTT")
  490. self._client.reconnect()
  491. except (SocketError, OSError, pmc.WebsocketConnectionError) as e:
  492. raise MQTTReconnectionError("MQTT reconnection failed") from e
  493. def add_event_handler(
  494. self, evt_type: Type[T], handler: Callable[[T], Awaitable[None]]
  495. ) -> None:
  496. self._event_handlers[evt_type].append(handler)
  497. async def _dispatch(self, evt: T) -> None:
  498. for handler in self._event_handlers[type(evt)]:
  499. try:
  500. await handler(evt)
  501. except Exception:
  502. self.log.exception(f"Error in {type(evt).__name__} handler")
  503. def disconnect(self) -> None:
  504. self._client.disconnect()
  505. async def _dispatcher_loop(self) -> None:
  506. loop_id = f"{hex(id(self))}#{time.monotonic()}"
  507. self.log.debug(f"Dispatcher loop {loop_id} starting")
  508. try:
  509. while True:
  510. evt = await self._outgoing_events.get()
  511. await asyncio.shield(self._dispatch(evt))
  512. except asyncio.CancelledError:
  513. tasks = self._outgoing_events
  514. self._outgoing_events = asyncio.Queue()
  515. if not tasks.empty():
  516. self.log.debug(
  517. f"Dispatcher loop {loop_id} stopping after dispatching {tasks.qsize()} events"
  518. )
  519. while not tasks.empty():
  520. await self._dispatch(tasks.get_nowait())
  521. raise
  522. finally:
  523. self.log.debug(f"Dispatcher loop {loop_id} stopped")
  524. async def listen(
  525. self,
  526. graphql_subs: set[str] | None = None,
  527. skywalker_subs: set[str] | None = None,
  528. seq_id: int = None,
  529. snapshot_at_ms: int = None,
  530. retry_limit: int = 5,
  531. ) -> None:
  532. self._graphql_subs = graphql_subs or set()
  533. self._skywalker_subs = skywalker_subs or set()
  534. self._iris_seq_id = seq_id
  535. self._iris_snapshot_at_ms = snapshot_at_ms
  536. self.log.debug("Connecting to Instagram MQTT")
  537. async def connect_and_watch():
  538. await self._reconnect()
  539. while True:
  540. try:
  541. await asyncio.sleep(1)
  542. except asyncio.CancelledError:
  543. self.disconnect()
  544. # this might not be necessary
  545. self._client.loop_misc()
  546. return
  547. rc = self._client.loop_misc()
  548. # If disconnect() has been called
  549. # Beware, internal API, may have to change this to something more stable!
  550. if self._client._state == pmc.mqtt_cs_disconnecting:
  551. return # Stop listening
  552. if rc != pmc.MQTT_ERR_SUCCESS:
  553. # If known/expected error
  554. if rc == pmc.MQTT_ERR_CONN_LOST:
  555. await self._dispatch(Disconnect(reason="Connection lost, retrying"))
  556. raise MQTTNotConnected("MQTT_ERR_CONN_LOST")
  557. elif rc == pmc.MQTT_ERR_NOMEM:
  558. # This error is wrongly classified
  559. # See https://github.com/eclipse/paho.mqtt.python/issues/340
  560. await self._dispatch(Disconnect(reason="Connection lost, retrying"))
  561. raise MQTTNotConnected("MQTT_ERR_NOMEM")
  562. elif rc == pmc.MQTT_ERR_CONN_REFUSED:
  563. await self._dispatch(Disconnect(reason="Connection refused, retrying"))
  564. raise MQTTNotLoggedIn("MQTT_ERR_CONN_REFUSED")
  565. elif rc == pmc.MQTT_ERR_NO_CONN:
  566. await self._dispatch(Disconnect(reason="Connection dropped, retrying"))
  567. raise MQTTNotConnected("MQTT_ERR_NO_CONN")
  568. else:
  569. err = pmc.error_string(rc)
  570. self.log.error("MQTT Error: %s", err)
  571. await self._dispatch(Disconnect(reason=f"MQTT Error: {err}, retrying"))
  572. raise MQTTNotConnected(err)
  573. await proxy_with_retry(
  574. "mqtt.listen",
  575. lambda: connect_and_watch(),
  576. logger=self.log,
  577. proxy_handler=self.proxy_handler,
  578. on_proxy_change=lambda: self._dispatch(ProxyUpdate()),
  579. max_retries=retry_limit,
  580. retryable_exceptions=(MQTTNotConnected, MQTTReconnectionError),
  581. # Wait 1s * errors, max 10s for fast reconnect or die
  582. max_wait_seconds=10,
  583. multiply_wait_seconds=1,
  584. )
  585. if self._event_dispatcher_task:
  586. self._event_dispatcher_task.cancel()
  587. self._event_dispatcher_task = None
  588. if self._disconnect_error:
  589. self.log.info("disconnect_error is set, raising and clearing variable")
  590. err = self._disconnect_error
  591. self._disconnect_error = None
  592. raise err
  593. # region Basic outgoing MQTT
  594. @staticmethod
  595. def _publish_cancel_later(fut: asyncio.Future) -> None:
  596. if not fut.done():
  597. fut.set_exception(asyncio.TimeoutError("MQTT publish timed out"))
  598. @staticmethod
  599. def _request_cancel_later(fut: asyncio.Future) -> None:
  600. if not fut.done():
  601. fut.set_exception(asyncio.TimeoutError("MQTT request timed out"))
  602. def publish(self, topic: RealtimeTopic, payload: str | bytes | dict) -> asyncio.Future:
  603. if isinstance(payload, dict):
  604. payload = json.dumps(payload)
  605. if isinstance(payload, str):
  606. payload = payload.encode("utf-8")
  607. self.log.trace(f"Publishing message in {topic.value} ({topic.encoded}): {payload}")
  608. payload = zlib.compress(payload, level=9)
  609. info = self._client.publish(topic.encoded, payload, qos=1)
  610. self.log.trace(f"Published message ID: {info.mid}")
  611. fut = self._loop.create_future()
  612. timeout_handle = self._loop.call_later(
  613. REQUEST_PUBLISH_TIMEOUT, self._publish_cancel_later, fut
  614. )
  615. fut.add_done_callback(lambda _: timeout_handle.cancel())
  616. self._publish_waiters[info.mid] = fut
  617. return fut
  618. async def request(
  619. self,
  620. topic: RealtimeTopic,
  621. response: RealtimeTopic,
  622. payload: str | bytes | dict,
  623. timeout: int | None = None,
  624. ) -> pmc.MQTTMessage:
  625. async with self._response_waiter_locks[response]:
  626. fut = self._loop.create_future()
  627. self._response_waiters[response] = fut
  628. try:
  629. await self.publish(topic, payload)
  630. except asyncio.TimeoutError:
  631. self.log.warning("Publish timed out - try forcing reconnect")
  632. self._client.reconnect()
  633. except MQTTNotConnected:
  634. self.log.warning(
  635. "MQTT disconnected before PUBACK - wait a hot minute, we should get "
  636. "the response after we auto reconnect"
  637. )
  638. self.log.trace(
  639. f"Request published to {topic.value}, waiting for response {response.name}"
  640. )
  641. timeout_handle = self._loop.call_later(
  642. timeout or REQUEST_RESPONSE_TIMEOUT, self._request_cancel_later, fut
  643. )
  644. fut.add_done_callback(lambda _: timeout_handle.cancel())
  645. return await fut
  646. async def iris_subscribe(self, seq_id: int, snapshot_at_ms: int) -> None:
  647. self.log.debug(f"Requesting iris subscribe {seq_id}/{snapshot_at_ms}")
  648. resp = await self.request(
  649. RealtimeTopic.SUB_IRIS,
  650. RealtimeTopic.SUB_IRIS_RESPONSE,
  651. {
  652. "seq_id": seq_id,
  653. "snapshot_at_ms": snapshot_at_ms,
  654. "snapshot_app_version": self.state.application.APP_VERSION,
  655. "timezone_offset": int(self.state.device.timezone_offset),
  656. "subscription_type": "message",
  657. },
  658. timeout=20,
  659. )
  660. self.log.debug("Iris subscribe response: %s", resp.payload.decode("utf-8"))
  661. resp_dict = json.loads(resp.payload.decode("utf-8"))
  662. if resp_dict["error_type"] and resp_dict["error_message"]:
  663. raise IrisSubscribeError(resp_dict["error_type"], resp_dict["error_message"])
  664. latest_seq_id = resp_dict.get("latest_seq_id")
  665. if latest_seq_id > self._iris_seq_id:
  666. self.log.info(f"Latest sequence ID is {latest_seq_id}, catching up from {seq_id}")
  667. self._iris_seq_id = latest_seq_id
  668. self._iris_snapshot_at_ms = resp_dict.get("subscribed_at_ms", int(time.time() * 1000))
  669. background_task.create(
  670. self._dispatch(NewSequenceID(self._iris_seq_id, self._iris_snapshot_at_ms))
  671. )
  672. def graphql_subscribe(self, subs: set[str]) -> asyncio.Future:
  673. self._graphql_subs |= subs
  674. return self.publish(RealtimeTopic.REALTIME_SUB, {"sub": list(subs)})
  675. def graphql_unsubscribe(self, subs: set[str]) -> asyncio.Future:
  676. self._graphql_subs -= subs
  677. return self.publish(RealtimeTopic.REALTIME_SUB, {"unsub": list(subs)})
  678. def skywalker_subscribe(self, subs: set[str]) -> asyncio.Future:
  679. self._skywalker_subs |= subs
  680. return self.publish(RealtimeTopic.PUBSUB, {"sub": list(subs)})
  681. def skywalker_unsubscribe(self, subs: set[str]) -> asyncio.Future:
  682. self._skywalker_subs -= subs
  683. return self.publish(RealtimeTopic.PUBSUB, {"unsub": list(subs)})
  684. # endregion
  685. # region Actually sending messages and stuff
  686. async def send_foreground_state(self, state: ForegroundStateConfig) -> None:
  687. self.log.debug("Updating foreground state: %s", state)
  688. await self.publish(
  689. RealtimeTopic.FOREGROUND_STATE, zlib.compress(state.to_thrift(), level=9)
  690. )
  691. if state.keep_alive_timeout:
  692. self._client._keepalive = state.keep_alive_timeout
  693. async def send_command(
  694. self,
  695. thread_id: str,
  696. action: ThreadAction,
  697. client_context: str | None = None,
  698. **kwargs: Any,
  699. ) -> CommandResponse | None:
  700. self.log.debug(f"Preparing to send {action} to {thread_id} with {client_context}")
  701. client_context = client_context or self.state.gen_client_context()
  702. req = {
  703. "thread_id": thread_id,
  704. "client_context": client_context,
  705. "offline_threading_id": client_context,
  706. "action": action.value,
  707. # "device_id": self.state.cookies["ig_did"],
  708. **kwargs,
  709. }
  710. lock_start = time.monotonic()
  711. async with self._message_response_waiter_lock:
  712. lock_wait_dur = time.monotonic() - lock_start
  713. if lock_wait_dur > 1:
  714. self.log.warning(f"Waited {lock_wait_dur:.3f} seconds to send {client_context}")
  715. fut = self._message_response_waiter = asyncio.Future()
  716. self._message_response_waiter_id = client_context
  717. self.log.debug(f"Publishing {action} to {thread_id} with {client_context}")
  718. try:
  719. await self.publish(RealtimeTopic.SEND_MESSAGE, req)
  720. except asyncio.TimeoutError:
  721. self.log.warning("Publish timed out - try forcing reconnect")
  722. self._client.reconnect()
  723. except MQTTNotConnected:
  724. self.log.warning(
  725. "MQTT disconnected before PUBACK - wait a hot minute, we should get "
  726. "the response after we auto reconnect"
  727. )
  728. self.log.trace(
  729. f"Request published to {RealtimeTopic.SEND_MESSAGE}, "
  730. f"waiting for response {RealtimeTopic.SEND_MESSAGE_RESPONSE}"
  731. )
  732. try:
  733. resp = await asyncio.wait_for(fut, timeout=REQUEST_RESPONSE_TIMEOUT)
  734. except asyncio.TimeoutError:
  735. self.log.error(f"Request with ID {client_context} timed out!")
  736. raise
  737. return CommandResponse.parse_json(resp.payload.decode("utf-8"))
  738. def send_item(
  739. self,
  740. thread_id: str,
  741. item_type: ThreadItemType,
  742. shh_mode: bool = False,
  743. client_context: str | None = None,
  744. **kwargs: Any,
  745. ) -> Awaitable[CommandResponse]:
  746. return self.send_command(
  747. thread_id,
  748. item_type=item_type.value,
  749. is_shh_mode=str(int(shh_mode)),
  750. action=ThreadAction.SEND_ITEM,
  751. client_context=client_context,
  752. **kwargs,
  753. )
  754. def send_hashtag(
  755. self,
  756. thread_id: str,
  757. hashtag: str,
  758. text: str = "",
  759. shh_mode: bool = False,
  760. client_context: str | None = None,
  761. ) -> Awaitable[CommandResponse]:
  762. return self.send_item(
  763. thread_id,
  764. text=text,
  765. item_id=hashtag,
  766. shh_mode=shh_mode,
  767. item_type=ThreadItemType.HASHTAG,
  768. client_context=client_context,
  769. )
  770. def send_like(
  771. self, thread_id: str, shh_mode: bool = False, client_context: str | None = None
  772. ) -> Awaitable[CommandResponse]:
  773. return self.send_item(
  774. thread_id,
  775. shh_mode=shh_mode,
  776. item_type=ThreadItemType.LIKE,
  777. client_context=client_context,
  778. )
  779. def send_location(
  780. self,
  781. thread_id: str,
  782. venue_id: str,
  783. text: str = "",
  784. shh_mode: bool = False,
  785. client_context: str | None = None,
  786. ) -> Awaitable[CommandResponse]:
  787. return self.send_item(
  788. thread_id,
  789. text=text,
  790. item_id=venue_id,
  791. shh_mode=shh_mode,
  792. item_type=ThreadItemType.LOCATION,
  793. client_context=client_context,
  794. )
  795. def send_media(
  796. self,
  797. thread_id: str,
  798. media_id: str,
  799. text: str = "",
  800. shh_mode: bool = False,
  801. client_context: str | None = None,
  802. ) -> Awaitable[CommandResponse]:
  803. return self.send_item(
  804. thread_id,
  805. text=text,
  806. media_id=media_id,
  807. shh_mode=shh_mode,
  808. item_type=ThreadItemType.MEDIA_SHARE,
  809. client_context=client_context,
  810. )
  811. def send_profile(
  812. self,
  813. thread_id: str,
  814. user_id: str,
  815. text: str = "",
  816. shh_mode: bool = False,
  817. client_context: str | None = None,
  818. ) -> Awaitable[CommandResponse]:
  819. return self.send_item(
  820. thread_id,
  821. text=text,
  822. item_id=user_id,
  823. shh_mode=shh_mode,
  824. item_type=ThreadItemType.PROFILE,
  825. client_context=client_context,
  826. )
  827. def send_reaction(
  828. self,
  829. thread_id: str,
  830. emoji: str,
  831. item_id: str,
  832. reaction_status: ReactionStatus = ReactionStatus.CREATED,
  833. target_item_type: ThreadItemType = ThreadItemType.TEXT,
  834. shh_mode: bool = False,
  835. client_context: str | None = None,
  836. ) -> Awaitable[CommandResponse]:
  837. return self.send_item(
  838. thread_id,
  839. reaction_status=reaction_status.value,
  840. node_type="item",
  841. reaction_type="like",
  842. target_item_type=target_item_type.value,
  843. emoji=emoji,
  844. item_id=item_id,
  845. reaction_action_source="double_tap",
  846. shh_mode=shh_mode,
  847. item_type=ThreadItemType.REACTION,
  848. client_context=client_context,
  849. )
  850. def send_user_story(
  851. self,
  852. thread_id: str,
  853. media_id: str,
  854. text: str = "",
  855. shh_mode: bool = False,
  856. client_context: str | None = None,
  857. ) -> Awaitable[CommandResponse]:
  858. return self.send_item(
  859. thread_id,
  860. text=text,
  861. item_id=media_id,
  862. shh_mode=shh_mode,
  863. item_type=ThreadItemType.REEL_SHARE,
  864. client_context=client_context,
  865. )
  866. def send_text(
  867. self,
  868. thread_id: str,
  869. text: str = "",
  870. urls: list[str] | None = None,
  871. shh_mode: bool = False,
  872. client_context: str | None = None,
  873. replied_to_item_id: str | None = None,
  874. replied_to_client_context: str | None = None,
  875. ) -> Awaitable[CommandResponse]:
  876. args = {
  877. "text": text,
  878. }
  879. item_type = ThreadItemType.TEXT
  880. if urls is not None:
  881. args = {
  882. "link_text": text,
  883. "link_urls": json.dumps(urls or []),
  884. }
  885. item_type = ThreadItemType.LINK
  886. return self.send_item(
  887. thread_id,
  888. **args,
  889. shh_mode=shh_mode,
  890. item_type=item_type,
  891. client_context=client_context,
  892. replied_to_item_id=replied_to_item_id,
  893. replied_to_client_context=replied_to_client_context,
  894. )
  895. def mark_seen(
  896. self, thread_id: str, item_id: str, client_context: str | None = None
  897. ) -> Awaitable[None]:
  898. return self.send_command(
  899. thread_id,
  900. item_id=item_id,
  901. action=ThreadAction.MARK_SEEN,
  902. client_context=client_context,
  903. )
  904. def mark_visual_item_seen(
  905. self, thread_id: str, item_id: str, client_context: str | None = None
  906. ) -> Awaitable[CommandResponse]:
  907. return self.send_command(
  908. thread_id,
  909. item_id=item_id,
  910. action=ThreadAction.MARK_VISUAL_ITEM_SEEN,
  911. client_context=client_context,
  912. )
  913. def indicate_activity(
  914. self,
  915. thread_id: str,
  916. activity_status: TypingStatus = TypingStatus.TEXT,
  917. client_context: str | None = None,
  918. ) -> Awaitable[CommandResponse]:
  919. return self.send_command(
  920. thread_id,
  921. activity_status=activity_status.value,
  922. action=ThreadAction.INDICATE_ACTIVITY,
  923. client_context=client_context,
  924. )
  925. # endregion