conn.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import (Union, Set, Optional, Any, Dict, Awaitable, Type, List, TypeVar, Callable,
  17. Iterable)
  18. from collections import defaultdict
  19. from socket import socket, error as SocketError
  20. from uuid import uuid4
  21. import logging
  22. import urllib.request
  23. import asyncio
  24. import zlib
  25. import time
  26. import json
  27. import re
  28. import paho.mqtt.client
  29. from paho.mqtt.client import MQTTMessage, WebsocketConnectionError
  30. from yarl import URL
  31. from mautrix.util.logging import TraceLogger
  32. from ..errors import MQTTNotLoggedIn, MQTTNotConnected
  33. from ..state import AndroidState
  34. from ..types import (CommandResponse, ThreadItemType, ThreadAction, ReactionStatus, TypingStatus,
  35. IrisPayload, PubsubPayload, AppPresenceEventPayload, RealtimeDirectEvent,
  36. RealtimeZeroProvisionPayload, ClientConfigUpdatePayload, MessageSyncEvent,
  37. MessageSyncMessage, LiveVideoCommentPayload, PubsubEvent, IrisPayloadData,
  38. ThreadSyncEvent)
  39. from .thrift import RealtimeConfig, RealtimeClientInfo, ForegroundStateConfig, IncomingMessage
  40. from .otclient import MQTToTClient
  41. from .subscription import everclear_subscriptions, RealtimeTopic, GraphQLQueryID
  42. from .events import Connect, Disconnect
  43. try:
  44. import socks
  45. except ImportError:
  46. socks = None
  47. T = TypeVar('T')
  48. ACTIVITY_INDICATOR_REGEX = re.compile(
  49. r"/direct_v2/threads/([\w_]+)/activity_indicator_id/([\w_]+)")
  50. INBOX_THREAD_REGEX = re.compile(
  51. r"/direct_v2/inbox/threads/([\w_]+)")
  52. class AndroidMQTT:
  53. _loop: asyncio.AbstractEventLoop
  54. _client: MQTToTClient
  55. log: TraceLogger
  56. state: AndroidState
  57. _graphql_subs: Set[str]
  58. _skywalker_subs: Set[str]
  59. _iris_seq_id: Optional[int]
  60. _iris_snapshot_at_ms: Optional[int]
  61. _publish_waiters: Dict[int, asyncio.Future]
  62. _response_waiters: Dict[RealtimeTopic, asyncio.Future]
  63. _response_waiter_locks: Dict[RealtimeTopic, asyncio.Lock]
  64. _message_response_waiters: Dict[str, asyncio.Future]
  65. _disconnect_error: Optional[Exception]
  66. _event_handlers: Dict[Type[T], List[Callable[[T], Awaitable[None]]]]
  67. # region Initialization
  68. def __init__(self, state: AndroidState, loop: Optional[asyncio.AbstractEventLoop] = None,
  69. log: Optional[TraceLogger] = None) -> None:
  70. self._graphql_subs = set()
  71. self._skywalker_subs = set()
  72. self._iris_seq_id = None
  73. self._iris_snapshot_at_ms = None
  74. self._publish_waiters = {}
  75. self._response_waiters = {}
  76. self._message_response_waiters = {}
  77. self._disconnect_error = None
  78. self._response_waiter_locks = defaultdict(lambda: asyncio.Lock())
  79. self._event_handlers = defaultdict(lambda: [])
  80. self.log = log or logging.getLogger("mauigpapi.mqtt")
  81. self._loop = loop or asyncio.get_event_loop()
  82. self.state = state
  83. self._client = MQTToTClient(
  84. client_id=self._form_client_id(),
  85. clean_session=True,
  86. protocol=paho.mqtt.client.MQTTv31,
  87. transport="tcp",
  88. )
  89. try:
  90. http_proxy = urllib.request.getproxies()["http"]
  91. except KeyError:
  92. http_proxy = None
  93. if http_proxy and socks and URL:
  94. proxy_url = URL(http_proxy)
  95. proxy_type = {
  96. "http": socks.HTTP,
  97. "https": socks.HTTP,
  98. "socks": socks.SOCKS5,
  99. "socks5": socks.SOCKS5,
  100. "socks4": socks.SOCKS4,
  101. }[proxy_url.scheme]
  102. self._client.proxy_set(proxy_type=proxy_type, proxy_addr=proxy_url.host,
  103. proxy_port=proxy_url.port, proxy_username=proxy_url.user,
  104. proxy_password=proxy_url.password)
  105. self._client.enable_logger()
  106. self._client.tls_set()
  107. # mqtt.max_inflight_messages_set(20) # The rest will get queued
  108. # mqtt.max_queued_messages_set(0) # Unlimited messages can be queued
  109. # mqtt.message_retry_set(20) # Retry sending for at least 20 seconds
  110. # mqtt.reconnect_delay_set(min_delay=1, max_delay=120)
  111. self._client.connect_async("edge-mqtt.facebook.com", 443, keepalive=60)
  112. self._client.on_message = self._on_message_handler
  113. self._client.on_publish = self._on_publish_handler
  114. self._client.on_connect = self._on_connect_handler
  115. # self._client.on_disconnect = self._on_disconnect_handler
  116. self._client.on_socket_open = self._on_socket_open
  117. self._client.on_socket_close = self._on_socket_close
  118. self._client.on_socket_register_write = self._on_socket_register_write
  119. self._client.on_socket_unregister_write = self._on_socket_unregister_write
  120. def _form_client_id(self) -> bytes:
  121. subscribe_topics = [RealtimeTopic.PUBSUB, RealtimeTopic.SUB_IRIS_RESPONSE,
  122. RealtimeTopic.REALTIME_SUB, RealtimeTopic.REGION_HINT,
  123. RealtimeTopic.SEND_MESSAGE_RESPONSE, RealtimeTopic.MESSAGE_SYNC,
  124. RealtimeTopic.UNKNOWN_179, RealtimeTopic.UNKNOWN_PP]
  125. subscribe_topic_ids = [int(topic.encoded) for topic in subscribe_topics]
  126. password = f"sessionid={self.state.cookies['sessionid']}"
  127. cfg = RealtimeConfig(
  128. client_identifier=self.state.device.phone_id[:20],
  129. client_info=RealtimeClientInfo(
  130. user_id=int(self.state.user_id),
  131. user_agent=self.state.user_agent,
  132. client_capabilities=0b10110111,
  133. endpoint_capabilities=0,
  134. publish_format=1,
  135. no_automatic_foreground=True,
  136. make_user_available_in_foreground=False,
  137. device_id=self.state.device.phone_id,
  138. is_initially_foreground=True,
  139. network_type=1,
  140. network_subtype=0,
  141. client_mqtt_session_id=int(time.time() * 1000) & 0xffffffff,
  142. subscribe_topics=subscribe_topic_ids,
  143. client_type="cookie_auth",
  144. app_id=567067343352427,
  145. region_preference=self.state.session.region_hint or "LLA",
  146. device_secret="",
  147. client_stack=3,
  148. ),
  149. password=password,
  150. app_specific_info={
  151. "app_version": self.state.application.APP_VERSION,
  152. "X-IG-Capabilities": self.state.application.CAPABILITIES,
  153. "everclear_subscriptions": json.dumps(everclear_subscriptions),
  154. "User-Agent": self.state.user_agent,
  155. "Accept-Language": self.state.device.language.replace("_", "-"),
  156. "platform": "android",
  157. "ig_mqtt_route": "django",
  158. "pubsub_msg_type_blacklist": "direct, typing_type",
  159. "auth_cache_enabled": "0",
  160. },
  161. )
  162. return zlib.compress(cfg.to_thrift(), level=9)
  163. # endregion
  164. def _on_socket_open(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  165. self._loop.add_reader(sock, client.loop_read)
  166. def _on_socket_close(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  167. self._loop.remove_reader(sock)
  168. def _on_socket_register_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  169. self._loop.add_writer(sock, client.loop_write)
  170. def _on_socket_unregister_write(self, client: MQTToTClient, _: Any, sock: socket) -> None:
  171. self._loop.remove_writer(sock)
  172. def _on_connect_handler(self, client: MQTToTClient, _: Any, flags: Dict[str, Any], rc: int
  173. ) -> None:
  174. if rc != 0:
  175. err = paho.mqtt.client.connack_string(rc)
  176. self.log.error("MQTT Connection Error: %s (%d)", err, rc)
  177. return
  178. self._loop.create_task(self._post_connect())
  179. async def _post_connect(self) -> None:
  180. await self._dispatch(Connect())
  181. self.log.debug("Re-subscribing to things after connect")
  182. if self._graphql_subs:
  183. res = await self.graphql_subscribe(self._graphql_subs)
  184. self.log.trace("GraphQL subscribe response: %s", res)
  185. if self._skywalker_subs:
  186. res = await self.skywalker_subscribe(self._skywalker_subs)
  187. self.log.trace("Skywalker subscribe response: %s", res)
  188. if self._iris_seq_id:
  189. await self.iris_subscribe(self._iris_seq_id, self._iris_snapshot_at_ms)
  190. def _on_publish_handler(self, client: MQTToTClient, _: Any, mid: int) -> None:
  191. try:
  192. waiter = self._publish_waiters[mid]
  193. except KeyError:
  194. self.log.trace(f"Got publish confirmation for {mid}, but no waiters")
  195. return
  196. self.log.trace(f"Got publish confirmation for {mid}")
  197. waiter.set_result(None)
  198. # region Incoming event parsing
  199. def _parse_direct_thread_path(self, path: str) -> dict:
  200. try:
  201. blank, direct_v2, threads, thread_id, *rest = path.split("/")
  202. assert blank == ""
  203. assert direct_v2 == "direct_v2"
  204. assert threads == "threads"
  205. except (AssertionError, ValueError, IndexError) as e:
  206. self.log.debug(f"Got {e!r} while parsing path {path}")
  207. raise
  208. additional = {
  209. "thread_id": thread_id
  210. }
  211. if rest:
  212. subitem_key = rest[0]
  213. if subitem_key == "approval_required_for_new_members":
  214. additional["approval_required_for_new_members"] = True
  215. elif subitem_key == "participants" and len(rest) > 2 and rest[2] == "has_seen":
  216. additional["has_seen"] = int(rest[1])
  217. elif subitem_key == "items":
  218. additional["item_id"] = rest[1]
  219. # TODO wtf is this?
  220. # it has something to do with reactions
  221. if len(rest) > 4:
  222. additional[rest[2]] = {
  223. rest[3]: rest[4],
  224. }
  225. elif subitem_key in "admin_user_ids":
  226. additional["admin_user_id"] = int(rest[1])
  227. elif subitem_key == "activity_indicator_id":
  228. additional["activity_indicator_id"] = rest[1]
  229. self.log.trace("Parsed path %s -> %s", path, additional)
  230. return additional
  231. def _on_messager_sync_item(self, part: IrisPayloadData, parsed_item: IrisPayload) -> None:
  232. if part.path.startswith("/direct_v2/threads/"):
  233. raw_message = {
  234. "path": part.path,
  235. "op": part.op,
  236. **self._parse_direct_thread_path(part.path),
  237. }
  238. try:
  239. raw_message = {
  240. **raw_message,
  241. **json.loads(part.value),
  242. }
  243. except (json.JSONDecodeError, TypeError):
  244. raw_message["value"] = part.value
  245. message = MessageSyncMessage.deserialize(raw_message)
  246. evt = MessageSyncEvent(iris=parsed_item, message=message)
  247. elif part.path.startswith("/direct_v2/inbox/threads/"):
  248. raw_message = {
  249. "path": part.path,
  250. "op": part.op,
  251. **json.loads(part.value),
  252. }
  253. evt = ThreadSyncEvent.deserialize(raw_message)
  254. else:
  255. self.log.warning(f"Unsupported path {part.path}")
  256. return
  257. self._loop.create_task(self._dispatch(evt))
  258. def _on_message_sync(self, payload: bytes) -> None:
  259. parsed = json.loads(payload.decode("utf-8"))
  260. self.log.trace("Got message sync event: %s", parsed)
  261. for sync_item in parsed:
  262. parsed_item = IrisPayload.deserialize(sync_item)
  263. if self._iris_seq_id < parsed_item.seq_id:
  264. self.log.trace(f"Got new seq_id: {parsed_item.seq_id}")
  265. self._iris_seq_id = parsed_item.seq_id
  266. self._iris_snapshot_at_ms = int(time.time() * 1000)
  267. for part in parsed_item.data:
  268. self._on_messager_sync_item(part, parsed_item)
  269. def _on_pubsub(self, payload: bytes) -> None:
  270. parsed_thrift = IncomingMessage.from_thrift(payload)
  271. self.log.trace(f"Got pubsub event {parsed_thrift.topic} / {parsed_thrift.payload}")
  272. message = PubsubPayload.parse_json(parsed_thrift.payload)
  273. for data in message.data:
  274. match = ACTIVITY_INDICATOR_REGEX.match(data.path)
  275. if match:
  276. evt = PubsubEvent(data=data, base=message, thread_id=match.group(1),
  277. activity_indicator_id=match.group(2))
  278. self._loop.create_task(self._dispatch(evt))
  279. elif not data.double_publish:
  280. self.log.debug("Pubsub: no activity indicator on data: %s", data)
  281. else:
  282. self.log.debug("Pubsub: double publish: %s", data.path)
  283. def _parse_realtime_sub_item(self, topic: Union[str, GraphQLQueryID], raw: dict
  284. ) -> Iterable[Any]:
  285. if topic == GraphQLQueryID.APP_PRESENCE:
  286. yield AppPresenceEventPayload.deserialize(raw).presence_event
  287. elif topic == GraphQLQueryID.ZERO_PROVISION:
  288. yield RealtimeZeroProvisionPayload.deserialize(raw).zero_product_provisioning_event
  289. elif topic == GraphQLQueryID.CLIENT_CONFIG_UPDATE:
  290. yield ClientConfigUpdatePayload.deserialize(raw).client_config_update_event
  291. elif topic == GraphQLQueryID.LIVE_REALTIME_COMMENTS:
  292. yield LiveVideoCommentPayload.deserialize(raw).live_video_comment_event
  293. elif topic == "direct":
  294. event = raw["event"]
  295. for item in raw["data"]:
  296. yield RealtimeDirectEvent.deserialize({
  297. "event": event,
  298. **self._parse_direct_thread_path(item["path"]),
  299. **item,
  300. })
  301. def _on_realtime_sub(self, payload: bytes) -> None:
  302. parsed_thrift = IncomingMessage.from_thrift(payload)
  303. try:
  304. topic = GraphQLQueryID(parsed_thrift.topic)
  305. except ValueError:
  306. topic = parsed_thrift.topic
  307. self.log.trace(f"Got realtime sub event {topic} / {parsed_thrift.payload}")
  308. allowed = ("direct", GraphQLQueryID.APP_PRESENCE, GraphQLQueryID.ZERO_PROVISION,
  309. GraphQLQueryID.CLIENT_CONFIG_UPDATE, GraphQLQueryID.LIVE_REALTIME_COMMENTS)
  310. if topic not in allowed:
  311. return
  312. parsed_json = json.loads(parsed_thrift.payload)
  313. for evt in self._parse_realtime_sub_item(topic, parsed_json):
  314. self._loop.create_task(self._dispatch(evt))
  315. def _on_message_handler(self, client: MQTToTClient, _: Any, message: MQTTMessage) -> None:
  316. try:
  317. topic = RealtimeTopic.decode(message.topic)
  318. # Instagram Android MQTT messages are always compressed
  319. message.payload = zlib.decompress(message.payload)
  320. if topic == RealtimeTopic.MESSAGE_SYNC:
  321. self._on_message_sync(message.payload)
  322. elif topic == RealtimeTopic.PUBSUB:
  323. self._on_pubsub(message.payload)
  324. elif topic == RealtimeTopic.REALTIME_SUB:
  325. self._on_realtime_sub(message.payload)
  326. elif topic == RealtimeTopic.SEND_MESSAGE_RESPONSE:
  327. try:
  328. data = json.loads(message.payload.decode("utf-8"))
  329. ccid = data["payload"]["client_context"]
  330. waiter = self._message_response_waiters.pop(ccid)
  331. except KeyError as e:
  332. self.log.debug("No handler (%s) for send message response: %s",
  333. e, message.payload)
  334. else:
  335. self.log.trace("Got response to %s: %s", ccid, message.payload)
  336. waiter.set_result(message)
  337. else:
  338. try:
  339. waiter = self._response_waiters.pop(topic)
  340. except KeyError:
  341. self.log.debug("No handler for MQTT message in %s: %s",
  342. topic.value, message.payload)
  343. else:
  344. self.log.trace("Got response %s: %s", topic.value, message.payload)
  345. waiter.set_result(message)
  346. except Exception:
  347. self.log.exception("Error in incoming MQTT message handler")
  348. self.log.trace("Errored MQTT payload: %s", message.payload)
  349. # endregion
  350. async def _reconnect(self) -> None:
  351. try:
  352. self.log.trace("Trying to reconnect to MQTT")
  353. self._client.reconnect()
  354. except (SocketError, OSError, WebsocketConnectionError) as e:
  355. # TODO custom class
  356. raise MQTTNotLoggedIn("MQTT reconnection failed") from e
  357. def add_event_handler(self, evt_type: Type[T], handler: Callable[[T], Awaitable[None]]
  358. ) -> None:
  359. self._event_handlers[evt_type].append(handler)
  360. async def _dispatch(self, evt: T) -> None:
  361. for handler in self._event_handlers[type(evt)]:
  362. try:
  363. await handler(evt)
  364. except Exception:
  365. self.log.exception(f"Error in {type(evt)} handler")
  366. def disconnect(self) -> None:
  367. self._client.disconnect()
  368. async def listen(self, graphql_subs: Set[str] = None, skywalker_subs: Set[str] = None,
  369. seq_id: int = None, snapshot_at_ms: int = None, retry_limit: int = 5) -> None:
  370. self._graphql_subs = graphql_subs or set()
  371. self._skywalker_subs = skywalker_subs or set()
  372. self._iris_seq_id = seq_id
  373. self._iris_snapshot_at_ms = snapshot_at_ms
  374. self.log.debug("Connecting to Instagram MQTT")
  375. await self._reconnect()
  376. connection_retries = 0
  377. while True:
  378. try:
  379. await asyncio.sleep(1)
  380. except asyncio.CancelledError:
  381. self.disconnect()
  382. # this might not be necessary
  383. self._client.loop_misc()
  384. break
  385. rc = self._client.loop_misc()
  386. # If disconnect() has been called
  387. # Beware, internal API, may have to change this to something more stable!
  388. if self._client._state == paho.mqtt.client.mqtt_cs_disconnecting:
  389. break # Stop listening
  390. if rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  391. # If known/expected error
  392. if rc == paho.mqtt.client.MQTT_ERR_CONN_LOST:
  393. await self._dispatch(Disconnect(reason="Connection lost, retrying"))
  394. elif rc == paho.mqtt.client.MQTT_ERR_NOMEM:
  395. # This error is wrongly classified
  396. # See https://github.com/eclipse/paho.mqtt.python/issues/340
  397. await self._dispatch(Disconnect(reason="Connection lost, retrying"))
  398. elif rc == paho.mqtt.client.MQTT_ERR_CONN_REFUSED:
  399. raise MQTTNotLoggedIn("MQTT connection refused")
  400. elif rc == paho.mqtt.client.MQTT_ERR_NO_CONN:
  401. if connection_retries > retry_limit:
  402. raise MQTTNotConnected(f"Connection failed {connection_retries} times")
  403. sleep = connection_retries * 2
  404. await self._dispatch(Disconnect(reason="MQTT Error: no connection, retrying "
  405. f"in {connection_retries} seconds"))
  406. await asyncio.sleep(sleep)
  407. else:
  408. err = paho.mqtt.client.error_string(rc)
  409. self.log.error("MQTT Error: %s", err)
  410. await self._dispatch(Disconnect(reason=f"MQTT Error: {err}, retrying"))
  411. await self._reconnect()
  412. connection_retries += 1
  413. else:
  414. connection_retries = 0
  415. if self._disconnect_error:
  416. self.log.info("disconnect_error is set, raising and clearing variable")
  417. err = self._disconnect_error
  418. self._disconnect_error = None
  419. raise err
  420. # region Basic outgoing MQTT
  421. def publish(self, topic: RealtimeTopic, payload: Union[str, bytes, dict]
  422. ) -> asyncio.Future:
  423. if isinstance(payload, dict):
  424. payload = json.dumps(payload)
  425. if isinstance(payload, str):
  426. payload = payload.encode("utf-8")
  427. self.log.trace(f"Publishing message in {topic.value} ({topic.encoded}): {payload}")
  428. payload = zlib.compress(payload, level=9)
  429. info = self._client.publish(topic.encoded, payload, qos=1)
  430. self.log.trace(f"Published message ID: {info.mid}")
  431. fut = asyncio.Future()
  432. self._publish_waiters[info.mid] = fut
  433. return fut
  434. async def request(self, topic: RealtimeTopic, response: RealtimeTopic,
  435. payload: Union[str, bytes, dict]) -> MQTTMessage:
  436. async with self._response_waiter_locks[response]:
  437. fut = asyncio.Future()
  438. self._response_waiters[response] = fut
  439. await self.publish(topic, payload)
  440. self.log.trace(f"Request published to {topic.value}, "
  441. f"waiting for response {response.name}")
  442. return await fut
  443. async def iris_subscribe(self, seq_id: int, snapshot_at_ms: int) -> None:
  444. self.log.debug(f"Requesting iris subscribe {seq_id}/{snapshot_at_ms}")
  445. resp = await self.request(RealtimeTopic.SUB_IRIS, RealtimeTopic.SUB_IRIS_RESPONSE,
  446. {"seq_id": seq_id, "snapshot_at_ms": snapshot_at_ms})
  447. # TODO check succeeded and raise error if needed
  448. self.log.debug("Iris subscribe response: %s", resp.payload.decode("utf-8"))
  449. def graphql_subscribe(self, subs: Set[str]) -> asyncio.Future:
  450. self._graphql_subs |= subs
  451. return self.publish(RealtimeTopic.REALTIME_SUB, {"sub": list(subs)})
  452. def graphql_unsubscribe(self, subs: Set[str]) -> asyncio.Future:
  453. self._graphql_subs -= subs
  454. return self.publish(RealtimeTopic.REALTIME_SUB, {"unsub": list(subs)})
  455. def skywalker_subscribe(self, subs: Set[str]) -> asyncio.Future:
  456. self._skywalker_subs |= subs
  457. return self.publish(RealtimeTopic.PUBSUB, {"sub": list(subs)})
  458. def skywalker_unsubscribe(self, subs: Set[str]) -> asyncio.Future:
  459. self._skywalker_subs -= subs
  460. return self.publish(RealtimeTopic.PUBSUB, {"unsub": list(subs)})
  461. # endregion
  462. # region Actually sending messages and stuff
  463. async def send_foreground_state(self, state: ForegroundStateConfig) -> None:
  464. self.log.debug("Updating foreground state: %s", state)
  465. await self.publish(RealtimeTopic.FOREGROUND_STATE,
  466. zlib.compress(state.to_thrift(), level=9))
  467. if state.keep_alive_timeout:
  468. self._client._keepalive = state.keep_alive_timeout
  469. async def send_command(self, thread_id: str, action: ThreadAction,
  470. client_context: Optional[str] = None,
  471. offline_threading_id: Optional[str] = None, **kwargs: Any
  472. ) -> Optional[CommandResponse]:
  473. client_context = client_context or str(uuid4())
  474. req = {
  475. "thread_id": thread_id,
  476. "client_context": client_context,
  477. "offline_threading_id": offline_threading_id or client_context,
  478. "action": action.value,
  479. # "device_id": self.state.cookies["ig_did"],
  480. **kwargs,
  481. }
  482. if action in (ThreadAction.MARK_SEEN,):
  483. # Some commands don't have client_context in the response, so we can't properly match
  484. # them to the requests. We probably don't need the data, so just ignore it.
  485. await self.publish(RealtimeTopic.SEND_MESSAGE, payload=req)
  486. return None
  487. else:
  488. fut = asyncio.Future()
  489. self._message_response_waiters[client_context] = fut
  490. await self.publish(RealtimeTopic.SEND_MESSAGE, req)
  491. self.log.trace(f"Request published to {RealtimeTopic.SEND_MESSAGE}, "
  492. f"waiting for response {RealtimeTopic.SEND_MESSAGE_RESPONSE}")
  493. resp = await fut
  494. return CommandResponse.parse_json(resp.payload.decode("utf-8"))
  495. def send_item(self, thread_id: str, item_type: ThreadItemType, shh_mode: bool = False,
  496. client_context: Optional[str] = None, offline_threading_id: Optional[str] = None,
  497. **kwargs: Any) -> Awaitable[CommandResponse]:
  498. return self.send_command(thread_id, item_type=item_type.value,
  499. is_shh_mode=str(int(shh_mode)), action=ThreadAction.SEND_ITEM,
  500. client_context=client_context,
  501. offline_threading_id=offline_threading_id, **kwargs)
  502. def send_hashtag(self, thread_id: str, hashtag: str, text: str = "", shh_mode: bool = False,
  503. client_context: Optional[str] = None,
  504. offline_threading_id: Optional[str] = None) -> Awaitable[CommandResponse]:
  505. return self.send_item(thread_id, text=text, item_id=hashtag, shh_mode=shh_mode,
  506. item_type=ThreadItemType.HASHTAG, client_context=client_context,
  507. offline_threading_id=offline_threading_id)
  508. def send_like(self, thread_id: str, shh_mode: bool = False,
  509. client_context: Optional[str] = None, offline_threading_id: Optional[str] = None,
  510. ) -> Awaitable[CommandResponse]:
  511. return self.send_item(thread_id, shh_mode=shh_mode, item_type=ThreadItemType.LIKE,
  512. client_context=client_context,
  513. offline_threading_id=offline_threading_id)
  514. def send_location(self, thread_id: str, venue_id: str, text: str = "",
  515. shh_mode: bool = False, client_context: Optional[str] = None,
  516. offline_threading_id: Optional[str] = None,
  517. ) -> Awaitable[CommandResponse]:
  518. return self.send_item(thread_id, text=text, item_id=venue_id, shh_mode=shh_mode,
  519. item_type=ThreadItemType.LOCATION, client_context=client_context,
  520. offline_threading_id=offline_threading_id)
  521. def send_media(self, thread_id: str, media_id: str, text: str = "", shh_mode: bool = False,
  522. client_context: Optional[str] = None,
  523. offline_threading_id: Optional[str] = None) -> Awaitable[CommandResponse]:
  524. return self.send_item(thread_id, text=text, media_id=media_id, shh_mode=shh_mode,
  525. item_type=ThreadItemType.MEDIA_SHARE, client_context=client_context,
  526. offline_threading_id=offline_threading_id)
  527. def send_profile(self, thread_id: str, user_id: str, text: str = "", shh_mode: bool = False,
  528. client_context: Optional[str] = None,
  529. offline_threading_id: Optional[str] = None) -> Awaitable[CommandResponse]:
  530. return self.send_item(thread_id, text=text, item_id=user_id, shh_mode=shh_mode,
  531. item_type=ThreadItemType.PROFILE, client_context=client_context,
  532. offline_threading_id=offline_threading_id)
  533. def send_reaction(self, thread_id: str, emoji: str, item_id: str,
  534. reaction_status: ReactionStatus = ReactionStatus.CREATED,
  535. target_item_type: ThreadItemType = ThreadItemType.TEXT,
  536. shh_mode: bool = False, client_context: Optional[str] = None,
  537. offline_threading_id: Optional[str] = None) -> Awaitable[CommandResponse]:
  538. return self.send_item(thread_id, reaction_status=reaction_status.value, node_type="item",
  539. reaction_type="like", target_item_type=target_item_type.value,
  540. emoji=emoji, item_id=item_id, reaction_action_source="double_tap",
  541. shh_mode=shh_mode, item_type=ThreadItemType.REACTION,
  542. client_context=client_context,
  543. offline_threading_id=offline_threading_id)
  544. def send_user_story(self, thread_id: str, media_id: str, text: str = "",
  545. shh_mode: bool = False, client_context: Optional[str] = None,
  546. offline_threading_id: Optional[str] = None) -> Awaitable[CommandResponse]:
  547. return self.send_item(thread_id, text=text, item_id=media_id, shh_mode=shh_mode,
  548. item_type=ThreadItemType.REEL_SHARE, client_context=client_context,
  549. offline_threading_id=offline_threading_id)
  550. def send_text(self, thread_id: str, text: str = "", shh_mode: bool = False,
  551. client_context: Optional[str] = None, offline_threading_id: Optional[str] = None
  552. ) -> Awaitable[CommandResponse]:
  553. return self.send_item(thread_id, text=text, shh_mode=shh_mode,
  554. item_type=ThreadItemType.TEXT, client_context=client_context,
  555. offline_threading_id=offline_threading_id)
  556. def mark_seen(self, thread_id: str, item_id: str, client_context: Optional[str] = None,
  557. offline_threading_id: Optional[str] = None) -> Awaitable[None]:
  558. return self.send_command(thread_id, item_id=item_id, action=ThreadAction.MARK_SEEN,
  559. client_context=client_context,
  560. offline_threading_id=offline_threading_id)
  561. def mark_visual_item_seen(self, thread_id: str, item_id: str,
  562. client_context: Optional[str] = None,
  563. offline_threading_id: Optional[str] = None
  564. ) -> Awaitable[CommandResponse]:
  565. return self.send_command(thread_id, item_id=item_id,
  566. action=ThreadAction.MARK_VISUAL_ITEM_SEEN,
  567. client_context=client_context,
  568. offline_threading_id=offline_threading_id)
  569. def indicate_activity(self, thread_id: str, activity_status: TypingStatus = TypingStatus.TEXT,
  570. client_context: Optional[str] = None,
  571. offline_threading_id: Optional[str] = None
  572. ) -> Awaitable[CommandResponse]:
  573. return self.send_command(thread_id, activity_status=activity_status.value,
  574. action=ThreadAction.INDICATE_ACTIVITY,
  575. client_context=client_context,
  576. offline_threading_id=offline_threading_id)
  577. # endregion