thread.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 AsyncIterable, 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. direction: str = "older",
  39. ) -> DMInboxResponse:
  40. query = {
  41. "visual_message_return_type": "unseen",
  42. "cursor": cursor,
  43. "direction": direction if cursor else None,
  44. "seq_id": seq_id,
  45. "thread_message_limit": message_limit,
  46. "persistentBadging": "true",
  47. "limit": limit,
  48. }
  49. inbox_type = "pending_inbox" if pending else "inbox"
  50. return await self.std_http_get(
  51. f"/api/v1/direct_v2/{inbox_type}/", query=query, response_type=DMInboxResponse
  52. )
  53. async def iter_inbox(
  54. self,
  55. start_at: DMInboxResponse | None = None,
  56. local_limit: int | None = None,
  57. rate_limit_exceeded_backoff: float = 60.0,
  58. ) -> AsyncIterable[tuple[Thread, int | None, str | None]]:
  59. thread_counter = 0
  60. if start_at:
  61. cursor = start_at.inbox.oldest_cursor
  62. seq_id = start_at.seq_id
  63. has_more = start_at.inbox.has_older
  64. for thread in start_at.inbox.threads:
  65. yield thread, seq_id, cursor
  66. thread_counter += 1
  67. if local_limit and thread_counter >= local_limit:
  68. return
  69. else:
  70. cursor = None
  71. seq_id = None
  72. has_more = True
  73. while has_more:
  74. try:
  75. resp = await self.get_inbox(message_limit=10, cursor=cursor, seq_id=seq_id)
  76. except IGRateLimitError:
  77. self.log.warning(
  78. "Fetching more threads failed due to rate limit. Waiting for "
  79. f"{rate_limit_exceeded_backoff} seconds before resuming."
  80. )
  81. await asyncio.sleep(rate_limit_exceeded_backoff)
  82. continue
  83. except Exception:
  84. self.log.exception("Failed to fetch more threads")
  85. raise
  86. seq_id = resp.seq_id
  87. cursor = resp.inbox.oldest_cursor
  88. has_more = resp.inbox.has_older
  89. for thread in resp.inbox.threads:
  90. yield thread, seq_id, cursor
  91. thread_counter += 1
  92. if local_limit and thread_counter >= local_limit:
  93. return
  94. async def get_thread(
  95. self,
  96. thread_id: str,
  97. cursor: str | None = None,
  98. limit: int = 10,
  99. direction: str = "older",
  100. seq_id: int | None = None,
  101. ) -> DMThreadResponse:
  102. query = {
  103. "visual_message_return_type": "unseen",
  104. "cursor": cursor,
  105. "direction": direction,
  106. "seq_id": seq_id,
  107. "limit": limit,
  108. }
  109. return await self.std_http_get(
  110. f"/api/v1/direct_v2/threads/{thread_id}/", query=query, response_type=DMThreadResponse
  111. )
  112. async def create_group_thread(self, recipient_users: list[int | str]) -> Thread:
  113. return await self.std_http_post(
  114. "/api/v1/direct_v2/create_group_thread/",
  115. data={
  116. "_csrftoken": self.state.cookies.csrf_token,
  117. "_uuid": self.state.device.uuid,
  118. "_uid": self.state.session.ds_user_id,
  119. "recipient_users": json.dumps(
  120. [str(user) for user in recipient_users], separators=(",", ":")
  121. ),
  122. },
  123. response_type=Thread,
  124. )
  125. async def approve_thread(self, thread_id: int | str) -> None:
  126. await self.std_http_post(
  127. f"/api/v1/direct_v2/threads/{thread_id}/approve/",
  128. data={
  129. "filter": "DEFAULT",
  130. "_uuid": self.state.device.uuid,
  131. },
  132. raw=True,
  133. )
  134. async def approve_threads(self, thread_ids: list[int | str]) -> None:
  135. await self.std_http_post(
  136. "/api/v1/direct_v2/threads/approve_multiple/",
  137. data={
  138. "thread_ids": json.dumps(
  139. [str(thread) for thread in thread_ids], separators=(",", ":")
  140. ),
  141. "folder": "",
  142. },
  143. )
  144. async def delete_item(self, thread_id: str, item_id: str) -> None:
  145. await self.std_http_post(
  146. f"/api/v1/direct_v2/threads/{thread_id}/items/{item_id}/delete/",
  147. data={"_csrftoken": self.state.cookies.csrf_token, "_uuid": self.state.device.uuid},
  148. )
  149. async def _broadcast(
  150. self,
  151. thread_id: str,
  152. item_type: str,
  153. response_type: Type[T],
  154. signed: bool = False,
  155. client_context: str | None = None,
  156. **kwargs,
  157. ) -> T:
  158. client_context = client_context or self.state.gen_client_context()
  159. form = {
  160. "action": ThreadAction.SEND_ITEM.value,
  161. "send_attribution": "direct_thread",
  162. "thread_ids": f"[{thread_id}]",
  163. "is_shh_mode": "0",
  164. "client_context": client_context,
  165. "_csrftoken": self.state.cookies.csrf_token,
  166. "device_id": self.state.device.id,
  167. "mutation_token": client_context,
  168. "_uuid": self.state.device.uuid,
  169. **kwargs,
  170. "offline_threading_id": client_context,
  171. }
  172. return await self.std_http_post(
  173. f"/api/v1/direct_v2/threads/broadcast/{item_type}/",
  174. data=form,
  175. raw=not signed,
  176. response_type=response_type,
  177. )
  178. async def broadcast(
  179. self,
  180. thread_id: str,
  181. item_type: ThreadItemType,
  182. signed: bool = False,
  183. client_context: str | None = None,
  184. **kwargs,
  185. ) -> CommandResponse:
  186. return await self._broadcast(
  187. thread_id, item_type.value, CommandResponse, signed, client_context, **kwargs
  188. )