conn.py 40 KB

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