base.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 random
  18. import time
  19. import json
  20. from aiohttp import ClientSession, ClientResponse
  21. from yarl import URL
  22. from mautrix.types import JSON, Serializable
  23. from ..state import AndroidState
  24. from ..errors import (IGActionSpamError, IGNotFoundError, IGRateLimitError, IGCheckpointError,
  25. IGUserHasLoggedOutError, IGLoginRequiredError, IGPrivateUserError,
  26. IGSentryBlockError, IGInactiveUserError, IGResponseError, IGBad2FACodeError,
  27. IGLoginBadPasswordError, IGLoginInvalidUserError,
  28. IGLoginTwoFactorRequiredError)
  29. T = TypeVar('T')
  30. class BaseAndroidAPI:
  31. url = URL("https://i.instagram.com")
  32. http: ClientSession
  33. state: AndroidState
  34. def __init__(self, state: AndroidState) -> None:
  35. self.http = ClientSession(cookie_jar=state.cookies.jar)
  36. self.state = state
  37. @staticmethod
  38. def sign(req: Any, filter_nulls: bool = False) -> Dict[str, str]:
  39. if isinstance(req, Serializable):
  40. req = req.serialize()
  41. if isinstance(req, dict):
  42. def remove_nulls(d: dict) -> dict:
  43. return {k: remove_nulls(v) if isinstance(v, dict) else v
  44. for k, v in d.items() if v is not None}
  45. req = json.dumps(remove_nulls(req) if filter_nulls else req)
  46. return {"signed_body": f"SIGNATURE.{req}"}
  47. @property
  48. def _headers(self) -> Dict[str, str]:
  49. headers = {
  50. "x-ads-opt-out": str(int(self.state.session.ads_opt_out)),
  51. "x-device-id": self.state.device.uuid,
  52. "x-ig-app-locale": self.state.device.language,
  53. "x-ig-device-locale": self.state.device.language,
  54. "x-pigeon-session-id": self.state.pigeon_session_id,
  55. "x-pigeon-rawclienttime": str(round(time.time(), 3)),
  56. "x-ig-connection-speed": f"{random.randint(1000, 3700)}kbps",
  57. "x-ig-bandwidth-speed-kbps": "-1.000",
  58. "x-ig-bandwidth-totalbytes-b": "0",
  59. "x-ig-bandwidth-totaltime-ms": "0",
  60. "x-ig-eu-dc-enabled": (str(self.state.session.eu_dc_enabled).lower()
  61. if self.state.session.eu_dc_enabled is not None else None),
  62. "x-ig-app-startup-country": self.state.device.language.split("_")[1],
  63. "x-bloks-version-id": self.state.application.BLOKS_VERSION_ID,
  64. "x-ig-www-claim": self.state.session.ig_www_claim or "0",
  65. "x-bloks-is-layout-rtl": str(self.state.device.is_layout_rtl).lower(),
  66. "x-bloks-is-panorama-enabled": "true",
  67. "x-ig-device-id": self.state.device.uuid,
  68. "x-ig-android-id": self.state.device.id,
  69. "x-ig-connection-type": self.state.device.connection_type,
  70. "x-ig-capabilities": self.state.application.CAPABILITIES,
  71. "x-ig-app-id": self.state.application.FACEBOOK_ANALYTICS_APPLICATION_ID,
  72. "user-agent": self.state.user_agent,
  73. "accept-language": self.state.device.language.replace("_", "-"),
  74. "authorization": self.state.session.authorization,
  75. "x-mid": self.state.cookies.get_value("mid"),
  76. "ig-u-ig-direct-region-hint": self.state.session.region_hint,
  77. "ig-u-shbid": self.state.session.shbid,
  78. "ig-u-shbts": self.state.session.shbts,
  79. "ig-u-ds-user-id": self.state.session.ds_user_id,
  80. "ig-u-rur": self.state.session.rur,
  81. "x-fb-http-engine": "Liger",
  82. "x-fb-client-ip": "True",
  83. "accept-encoding": "gzip",
  84. }
  85. return {k: v for k, v in headers.items() if v is not None}
  86. async def std_http_post(self, path: str, data: Optional[JSON] = None, raw: bool = False,
  87. filter_nulls: bool = False, headers: Optional[Dict[str, str]] = None,
  88. response_type: Optional[Type[T]] = JSON) -> T:
  89. headers = {**self._headers, **headers} if headers else self._headers
  90. if not raw:
  91. data = self.sign(data, filter_nulls=filter_nulls)
  92. resp = await self.http.post(url=self.url.with_path(path), headers=headers, data=data)
  93. print(f"{path} response: {await resp.text()}")
  94. if response_type is str or response_type is None:
  95. self._handle_response_headers(resp)
  96. if response_type is str:
  97. return await resp.text()
  98. return None
  99. json_data = await self._handle_response(resp)
  100. if response_type is not JSON:
  101. return response_type.deserialize(json_data)
  102. return json_data
  103. async def std_http_get(self, path: str, query: Optional[Dict[str, str]] = None,
  104. headers: Optional[Dict[str, str]] = None,
  105. response_type: Optional[Type[T]] = JSON) -> T:
  106. headers = {**self._headers, **headers} if headers else self._headers
  107. query = {k: v for k, v in (query or {}).items() if v is not None}
  108. resp = await self.http.get(url=self.url.with_path(path).with_query(query), headers=headers)
  109. print(f"{path} response: {await resp.text()}")
  110. if response_type is None:
  111. self._handle_response_headers(resp)
  112. return None
  113. json_data = await self._handle_response(resp)
  114. if response_type is not JSON:
  115. return response_type.deserialize(json_data)
  116. return json_data
  117. async def _handle_response(self, resp: ClientResponse) -> JSON:
  118. self._handle_response_headers(resp)
  119. body = await resp.json()
  120. if body["status"] == "ok":
  121. return body
  122. else:
  123. await self._raise_response_error(resp)
  124. async def _raise_response_error(self, resp: ClientResponse) -> None:
  125. try:
  126. data = await resp.json()
  127. except json.JSONDecodeError:
  128. data = {}
  129. if data.get("spam", False):
  130. raise IGActionSpamError(resp, data)
  131. elif data.get("two_factor_required", False):
  132. raise IGLoginTwoFactorRequiredError(resp, data)
  133. elif resp.status == 404:
  134. raise IGNotFoundError(resp, data)
  135. elif resp.status == 429:
  136. raise IGRateLimitError(resp, data)
  137. message = data.get("message")
  138. if isinstance(message, str):
  139. if message == "challenge_required":
  140. err = IGCheckpointError(resp, data)
  141. self.state.challenge_path = err.url
  142. raise err
  143. elif message == "user_has_logged_out":
  144. raise IGUserHasLoggedOutError(resp, data)
  145. elif message == "login_required":
  146. raise IGLoginRequiredError(resp, data)
  147. elif message.lower() == "not authorized to view user":
  148. raise IGPrivateUserError(resp, data)
  149. error_type = data.get("error_type")
  150. if error_type == "sentry_block":
  151. raise IGSentryBlockError(resp, data)
  152. elif error_type == "inactive_user":
  153. raise IGInactiveUserError(resp, data)
  154. elif error_type == "bad_password":
  155. raise IGLoginBadPasswordError(resp, data)
  156. elif error_type == "invalid_user":
  157. raise IGLoginInvalidUserError(resp, data)
  158. elif error_type == "sms_code_validation_code_invalid":
  159. raise IGBad2FACodeError(resp, data)
  160. raise IGResponseError(resp, data)
  161. def _handle_response_headers(self, resp: ClientResponse) -> None:
  162. fields = {
  163. "x-ig-set-www-claim": "ig_www_claim",
  164. "ig-set-authorization": "authorization",
  165. "ig-set-password-encryption-key-id": "password_encryption_key_id",
  166. "ig-set-password-encryption-pub-key": "password_encryption_pubkey",
  167. "ig-set-ig-u-ig-direct-region-hint": "region_hint",
  168. "ig-set-ig-u-shbid": "shbid",
  169. "ig-set-ig-u-shbts": "shbts",
  170. "ig-set-ig-u-rur": "rur",
  171. "ig-set-ig-u-ds-user-id": "ds_user_id",
  172. }
  173. for header, field in fields.items():
  174. value = resp.headers.get(header)
  175. if value and (header != "IG-Set-Authorization" or not value.endswith(":")):
  176. setattr(self.state.session, field, value)