conn.py 32 KB

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