base.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 Optional, Dict, Any, TypeVar, Type
  17. import asyncio
  18. import random
  19. import time
  20. import json
  21. from aiohttp import ClientSession, ClientResponse
  22. from yarl import URL
  23. from mautrix.types import JSON, Serializable
  24. from ..state import AndroidState
  25. from ..errors import (IGActionSpamError, IGNotFoundError, IGRateLimitError, IGCheckpointError,
  26. IGUserHasLoggedOutError, IGLoginRequiredError, IGPrivateUserError,
  27. IGSentryBlockError, IGInactiveUserError, IGResponseError,
  28. IGLoginBadPasswordError, IGLoginInvalidUserError,
  29. IGLoginTwoFactorRequiredError)
  30. T = TypeVar('T')
  31. class BaseAndroidAPI:
  32. url = URL("https://i.instagram.com")
  33. http: ClientSession
  34. state: AndroidState
  35. def __init__(self, state: AndroidState) -> None:
  36. self.http = ClientSession(cookie_jar=state.cookies.jar)
  37. self.state = state
  38. @staticmethod
  39. def sign(req: Any, filter_nulls: bool = False) -> Dict[str, str]:
  40. if isinstance(req, Serializable):
  41. req = req.serialize()
  42. if isinstance(req, dict):
  43. def remove_nulls(d: dict) -> dict:
  44. return {k: remove_nulls(v) if isinstance(v, dict) else v
  45. for k, v in d.items() if v is not None}
  46. req = json.dumps(remove_nulls(req) if filter_nulls else req)
  47. return {"signed_body": f"SIGNATURE.{req}"}
  48. @property
  49. def _headers(self) -> Dict[str, str]:
  50. headers = {
  51. "User-Agent": self.state.user_agent,
  52. "X-Ads-Opt-Out": str(int(self.state.session.ads_opt_out)),
  53. # "X-DEVICE-ID": self.state.device.uuid,
  54. "X-CM-Bandwidth-KBPS": "-1.000",
  55. "X-CM-Latency": "-1.000",
  56. "X-IG-App-Locale": self.state.device.language,
  57. "X-IG-Device-Locale": self.state.device.language,
  58. "X-Pigeon-Session-Id": self.state.pigeon_session_id,
  59. "X-Pigeon-Rawclienttime": str(round(time.time(), 3)),
  60. "X-IG-Connection-Speed": f"{random.randint(1000, 3700)}kbps",
  61. "X-IG-Bandwidth-Speed-KBPS": "-1.000",
  62. "X-IG-Bandwidth-TotalBytes-B": "0",
  63. "X-IG-Bandwidth-TotalTime-MS": "0",
  64. "X-IG-EU-DC-ENABLED": (str(self.state.session.eu_dc_enabled).lower()
  65. if self.state.session.eu_dc_enabled is not None else None),
  66. "X-IG-Extended-CDN-Thumbnail-Cache-Busting-Value":
  67. str(self.state.session.thumbnail_cache_busting_value),
  68. "X-Bloks-Version-Id": self.state.application.BLOKS_VERSION_ID,
  69. "X-MID": self.state.cookies.get_value("mid"),
  70. "X-IG-WWW-Claim": self.state.session.ig_www_claim or "0",
  71. "X-Bloks-Is-Layout-RTL": str(self.state.device.is_layout_rtl).lower(),
  72. "X-IG-Connection-Type": self.state.device.connection_type,
  73. "X-Ig-Capabilities": self.state.application.CAPABILITIES,
  74. "X-IG-App-Id": self.state.application.FACEBOOK_ANALYTICS_APPLICATION_ID,
  75. "X-IG-Device-ID": self.state.device.uuid,
  76. "X-IG-Android-ID": self.state.device.id,
  77. "Accept-Language": self.state.device.language.replace("_", "-"),
  78. "X-FB-HTTP-Engine": "Liger",
  79. "Authorization": self.state.session.authorization,
  80. "Accept-Encoding": "gzip",
  81. "Connection": "close",
  82. }
  83. return {k: v for k, v in headers.items() if v is not None}
  84. async def std_http_post(self, path: str, data: Optional[JSON] = None, raw: bool = False,
  85. filter_nulls: bool = False, headers: Optional[Dict[str, str]] = None,
  86. response_type: Optional[Type[T]] = JSON) -> T:
  87. headers = {**self._headers, **headers} if headers else self._headers
  88. if not raw:
  89. data = self.sign(data, filter_nulls=filter_nulls)
  90. resp = await self.http.post(url=self.url.with_path(path), headers=headers, data=data)
  91. print(f"{path} response: {await resp.text()}")
  92. if response_type is str or response_type is None:
  93. self._handle_response_headers(resp)
  94. if response_type is str:
  95. return await resp.text()
  96. return None
  97. json_data = await self._handle_response(resp)
  98. if response_type is not JSON:
  99. return response_type.deserialize(json_data)
  100. return json_data
  101. async def std_http_get(self, path: str, query: Optional[Dict[str, str]] = None,
  102. headers: Optional[Dict[str, str]] = None,
  103. response_type: Optional[Type[T]] = JSON) -> T:
  104. headers = {**self._headers, **headers} if headers else self._headers
  105. query = {k: v for k, v in (query or {}).items() if v is not None}
  106. resp = await self.http.get(url=self.url.with_path(path).with_query(query), headers=headers)
  107. print(f"{path} response: {await resp.text()}")
  108. if response_type is None:
  109. self._handle_response_headers(resp)
  110. return None
  111. json_data = await self._handle_response(resp)
  112. if response_type is not JSON:
  113. return response_type.deserialize(json_data)
  114. return json_data
  115. async def _handle_response(self, resp: ClientResponse) -> JSON:
  116. self._handle_response_headers(resp)
  117. body = await resp.json()
  118. if body["status"] == "ok":
  119. return body
  120. else:
  121. await self._raise_response_error(resp)
  122. async def _raise_response_error(self, resp: ClientResponse) -> None:
  123. try:
  124. data = await resp.json()
  125. except json.JSONDecodeError:
  126. data = {}
  127. if data.get("spam", False):
  128. raise IGActionSpamError(resp, data)
  129. elif data.get("two_factor_required", False):
  130. raise IGLoginTwoFactorRequiredError(resp, data)
  131. elif resp.status == 404:
  132. raise IGNotFoundError(resp, data)
  133. elif resp.status == 429:
  134. raise IGRateLimitError(resp, data)
  135. message = data.get("message")
  136. if isinstance(message, str):
  137. if message == "challenge_required":
  138. err = IGCheckpointError(resp, data)
  139. self.state.challenge_path = err.url
  140. raise err
  141. elif message == "user_has_logged_out":
  142. raise IGUserHasLoggedOutError(resp, data)
  143. elif message == "login_required":
  144. raise IGLoginRequiredError(resp, data)
  145. elif message.lower() == "not authorized to view user":
  146. raise IGPrivateUserError(resp, data)
  147. error_type = data.get("error_type")
  148. if error_type == "sentry_block":
  149. raise IGSentryBlockError(resp, data)
  150. elif error_type == "inactive_user":
  151. raise IGInactiveUserError(resp, data)
  152. elif error_type == "bad_password":
  153. raise IGLoginBadPasswordError(resp, data)
  154. elif error_type == "invalid_user":
  155. raise IGLoginInvalidUserError(resp, data)
  156. raise IGResponseError(resp, data)
  157. def _handle_response_headers(self, resp: ClientResponse) -> None:
  158. fields = {
  159. "X-IG-Set-WWW-Claim": "ig_www_claim",
  160. "IG-Set-Authorization": "authorization",
  161. "IG-Set-Password-Encryption-Key-ID": "password_encryption_key_id",
  162. "IG-Set-Password-Encryption-Pub-Key": "password_encryption_pubkey",
  163. "IG-Set-IG-U-IG-Direct-Region-Hint": "region_hint"
  164. }
  165. for header, field in fields.items():
  166. value = resp.headers.get(header)
  167. if value and (header != "IG-Set-Authorization" or not value.endswith(":")):
  168. setattr(self.state.session, field, value)