conn.py 36 KB

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