conn.py 27 KB

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