thread.py 6.8 KB

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