thread.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 = 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. async def create_group_thread(self, recipient_users: list[int | str]) -> Thread:
  133. return await self.std_http_post(
  134. "/api/v1/direct_v2/create_group_thread/",
  135. data={
  136. "_csrftoken": self.state.cookies.csrf_token,
  137. "_uuid": self.state.device.uuid,
  138. "_uid": self.state.session.ds_user_id,
  139. "recipient_users": json.dumps(
  140. [str(user) for user in recipient_users], separators=(",", ":")
  141. ),
  142. },
  143. response_type=Thread,
  144. )
  145. async def approve_thread(self, thread_id: int | str) -> None:
  146. await self.std_http_post(
  147. f"/api/v1/direct_v2/threads/{thread_id}/approve/",
  148. data={
  149. "filter": "DEFAULT",
  150. "_uuid": self.state.device.uuid,
  151. },
  152. raw=True,
  153. )
  154. async def approve_threads(self, thread_ids: list[int | str]) -> None:
  155. await self.std_http_post(
  156. "/api/v1/direct_v2/threads/approve_multiple/",
  157. data={
  158. "thread_ids": json.dumps(
  159. [str(thread) for thread in thread_ids], separators=(",", ":")
  160. ),
  161. "folder": "",
  162. },
  163. )
  164. async def delete_item(self, thread_id: str, item_id: str) -> None:
  165. await self.std_http_post(
  166. f"/api/v1/direct_v2/threads/{thread_id}/items/{item_id}/delete/",
  167. data={"_csrftoken": self.state.cookies.csrf_token, "_uuid": self.state.device.uuid},
  168. )
  169. async def _broadcast(
  170. self,
  171. thread_id: str,
  172. item_type: str,
  173. response_type: Type[T],
  174. signed: bool = False,
  175. client_context: str | None = None,
  176. **kwargs,
  177. ) -> T:
  178. client_context = client_context or self.state.gen_client_context()
  179. form = {
  180. "action": ThreadAction.SEND_ITEM.value,
  181. "send_attribution": "direct_thread",
  182. "thread_ids": f"[{thread_id}]",
  183. "is_shh_mode": "0",
  184. "client_context": client_context,
  185. "_csrftoken": self.state.cookies.csrf_token,
  186. "device_id": self.state.device.id,
  187. "mutation_token": client_context,
  188. "_uuid": self.state.device.uuid,
  189. **kwargs,
  190. "offline_threading_id": client_context,
  191. }
  192. return await self.std_http_post(
  193. f"/api/v1/direct_v2/threads/broadcast/{item_type}/",
  194. data=form,
  195. raw=not signed,
  196. response_type=response_type,
  197. )
  198. async def broadcast(
  199. self,
  200. thread_id: str,
  201. item_type: ThreadItemType,
  202. signed: bool = False,
  203. client_context: str | None = None,
  204. **kwargs,
  205. ) -> CommandResponse:
  206. return await self._broadcast(
  207. thread_id, item_type.value, CommandResponse, signed, client_context, **kwargs
  208. )