conn.py 39 KB

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