thread.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 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 AsyncIterable, Callable, Type
  18. import asyncio
  19. import json
  20. from mauigpapi.errors.response import IGRateLimitError
  21. from ..types import (
  22. CommandResponse,
  23. DMInboxResponse,
  24. DMThreadResponse,
  25. Thread,
  26. ThreadAction,
  27. ThreadItemType,
  28. )
  29. from .base import BaseAndroidAPI, T
  30. class ThreadAPI(BaseAndroidAPI):
  31. async def get_inbox(
  32. self,
  33. cursor: str | None = None,
  34. seq_id: str | None = None,
  35. message_limit: int | None = 10,
  36. limit: int = 20,
  37. pending: bool = False,
  38. spam: bool = False,
  39. direction: str = "older",
  40. ) -> DMInboxResponse:
  41. query = {
  42. "visual_message_return_type": "unseen",
  43. "cursor": cursor,
  44. "direction": direction if cursor else None,
  45. "seq_id": seq_id,
  46. "thread_message_limit": message_limit,
  47. "persistentBadging": "true",
  48. "limit": limit,
  49. "push_disabled": "true",
  50. "is_prefetching": "false",
  51. }
  52. inbox_type = "inbox"
  53. if pending:
  54. inbox_type = "pending_inbox"
  55. if spam:
  56. inbox_type = "spam_inbox"
  57. elif not cursor:
  58. query["fetch_reason"] = "initial_snapshot" # can also be manual_refresh
  59. headers = {
  60. # MainFeedFragment:feed_timeline for limit=0 cold start fetch
  61. "ig-client-endpoint": "DirectInboxFragment:direct_inbox",
  62. }
  63. return await self.std_http_get(
  64. f"/api/v1/direct_v2/{inbox_type}/", query=query, response_type=DMInboxResponse
  65. )
  66. async def iter_inbox(
  67. self,
  68. update_seq_id_and_cursor: Callable[[int, str | None], None],
  69. start_at: DMInboxResponse | None = None,
  70. local_limit: int | None = None,
  71. rate_limit_exceeded_backoff: float = 60.0,
  72. ) -> AsyncIterable[Thread]:
  73. thread_counter = 0
  74. if start_at:
  75. cursor = start_at.inbox.oldest_cursor
  76. seq_id = start_at.seq_id
  77. has_more = start_at.inbox.has_older
  78. for thread in start_at.inbox.threads:
  79. yield thread
  80. thread_counter += 1
  81. if local_limit and thread_counter >= local_limit:
  82. return
  83. update_seq_id_and_cursor(seq_id, cursor)
  84. else:
  85. cursor = None
  86. seq_id = None
  87. has_more = True
  88. while has_more:
  89. try:
  90. resp = await self.get_inbox(cursor=cursor, seq_id=seq_id)
  91. except IGRateLimitError:
  92. self.log.warning(
  93. "Fetching more threads failed due to rate limit. Waiting for "
  94. f"{rate_limit_exceeded_backoff} seconds before resuming."
  95. )
  96. await asyncio.sleep(rate_limit_exceeded_backoff)
  97. continue
  98. except Exception:
  99. self.log.exception("Failed to fetch more threads")
  100. raise
  101. seq_id = resp.seq_id
  102. cursor = resp.inbox.oldest_cursor
  103. has_more = resp.inbox.has_older
  104. for thread in resp.inbox.threads:
  105. yield thread
  106. thread_counter += 1
  107. if local_limit and thread_counter >= local_limit:
  108. return
  109. update_seq_id_and_cursor(seq_id, cursor)
  110. async def get_thread(
  111. self,
  112. thread_id: str,
  113. cursor: str | None = None,
  114. limit: int = 20,
  115. direction: str = "older",
  116. seq_id: int | None = None,
  117. ) -> DMThreadResponse:
  118. query = {
  119. "visual_message_return_type": "unseen",
  120. "cursor": cursor,
  121. "direction": direction,
  122. "seq_id": seq_id,
  123. "limit": limit,
  124. }
  125. headers = {
  126. "ig-client-endpoint": "DirectThreadFragment:direct_thread",
  127. "x-ig-nav-chain": "MainFeedFragment:feed_timeline:1:cold_start::,DirectInboxFragment:direct_inbox:4:on_launch_direct_inbox::",
  128. }
  129. return await self.std_http_get(
  130. f"/api/v1/direct_v2/threads/{thread_id}/", query=query, response_type=DMThreadResponse
  131. )
  132. # /threads/.../get_items/ with urlencoded form body:
  133. # visual_message_return_type: unseen
  134. # _uuid: device uuid
  135. # original_message_client_contexts:["client context"]
  136. # item_ids: [item id]
  137. async def get_thread_participant_requests(self, thread_id: str, page_size: int = 10):
  138. return await self.std_http_get(
  139. f"/api/v1/direct_v2/threads/{thread_id}/participant_requests/",
  140. query={"page_size": str(page_size)},
  141. )
  142. async def mark_seen(
  143. self, thread_id: str, item_id: str, client_context: str | None = None
  144. ) -> None:
  145. if not client_context:
  146. client_context = self.state.gen_client_context()
  147. data = {
  148. "thread_id": thread_id,
  149. "action": "mark_seen",
  150. "client_context": client_context,
  151. "_uuid": self.state.device.uuid,
  152. "offline_threading_id": client_context,
  153. }
  154. await self.std_http_post(
  155. f"/api/v1/direct_v2/threads/{thread_id}/items/{item_id}/seen/", data=data
  156. )
  157. async def create_group_thread(self, recipient_users: list[int | str]) -> Thread:
  158. return await self.std_http_post(
  159. "/api/v1/direct_v2/create_group_thread/",
  160. data={
  161. "_uuid": self.state.device.uuid,
  162. "_uid": self.state.session.ds_user_id,
  163. "recipient_users": json.dumps(
  164. [str(user) for user in recipient_users], separators=(",", ":")
  165. ),
  166. },
  167. response_type=Thread,
  168. )
  169. async def approve_thread(self, thread_id: int | str) -> None:
  170. await self.std_http_post(
  171. f"/api/v1/direct_v2/threads/{thread_id}/approve/",
  172. data={
  173. "filter": "DEFAULT",
  174. "_uuid": self.state.device.uuid,
  175. },
  176. raw=True,
  177. )
  178. async def approve_threads(self, thread_ids: list[int | str]) -> None:
  179. await self.std_http_post(
  180. "/api/v1/direct_v2/threads/approve_multiple/",
  181. data={
  182. "thread_ids": json.dumps(
  183. [str(thread) for thread in thread_ids], separators=(",", ":")
  184. ),
  185. "folder": "",
  186. },
  187. )
  188. async def delete_item(
  189. self, thread_id: str, item_id: str, orig_client_context: str | None = None
  190. ) -> None:
  191. await self.std_http_post(
  192. f"/api/v1/direct_v2/threads/{thread_id}/items/{item_id}/delete/",
  193. data={
  194. "is_shh_mode": "0",
  195. "send_attribution": "direct_thread",
  196. "_uuid": self.state.device.uuid,
  197. "original_message_client_context": orig_client_context,
  198. },
  199. )
  200. async def _broadcast(
  201. self,
  202. thread_id: str,
  203. item_type: str,
  204. response_type: Type[T],
  205. signed: bool = False,
  206. client_context: str | None = None,
  207. **kwargs,
  208. ) -> T:
  209. client_context = client_context or self.state.gen_client_context()
  210. form = {
  211. "action": ThreadAction.SEND_ITEM.value,
  212. "send_attribution": "direct_thread",
  213. "thread_ids": f"[{thread_id}]",
  214. "is_shh_mode": "0",
  215. "client_context": client_context,
  216. "device_id": self.state.device.id,
  217. "mutation_token": client_context,
  218. "_uuid": self.state.device.uuid,
  219. **kwargs,
  220. "offline_threading_id": client_context,
  221. "is_x_transport_forward": "false",
  222. }
  223. return await self.std_http_post(
  224. f"/api/v1/direct_v2/threads/broadcast/{item_type}/",
  225. data=form,
  226. raw=not signed,
  227. response_type=response_type,
  228. )
  229. async def broadcast(
  230. self,
  231. thread_id: str,
  232. item_type: ThreadItemType,
  233. signed: bool = False,
  234. client_context: str | None = None,
  235. **kwargs,
  236. ) -> CommandResponse:
  237. return await self._broadcast(
  238. thread_id, item_type.value, CommandResponse, signed, client_context, **kwargs
  239. )