base.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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, Union
  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. def raw_http_get(self, url: Union[URL, str]):
  87. return self.http.get(url, headers={
  88. "user-agent": self.state.user_agent,
  89. "accept-language": self.state.device.language.replace("_", "-"),
  90. })
  91. async def std_http_post(self, path: str, data: Optional[JSON] = None, raw: bool = False,
  92. filter_nulls: bool = False, headers: Optional[Dict[str, str]] = None,
  93. response_type: Optional[Type[T]] = JSON) -> T:
  94. headers = {**self._headers, **headers} if headers else self._headers
  95. if not raw:
  96. data = self.sign(data, filter_nulls=filter_nulls)
  97. resp = await self.http.post(url=self.url.with_path(path), headers=headers, data=data)
  98. print(f"{path} response: {await resp.text()}")
  99. if response_type is str or response_type is None:
  100. self._handle_response_headers(resp)
  101. if response_type is str:
  102. return await resp.text()
  103. return None
  104. json_data = await self._handle_response(resp)
  105. if response_type is not JSON:
  106. return response_type.deserialize(json_data)
  107. return json_data
  108. async def std_http_get(self, path: str, query: Optional[Dict[str, str]] = None,
  109. headers: Optional[Dict[str, str]] = None,
  110. response_type: Optional[Type[T]] = JSON) -> T:
  111. headers = {**self._headers, **headers} if headers else self._headers
  112. query = {k: v for k, v in (query or {}).items() if v is not None}
  113. resp = await self.http.get(url=self.url.with_path(path).with_query(query), headers=headers)
  114. print(f"{path} response: {await resp.text()}")
  115. if response_type is None:
  116. self._handle_response_headers(resp)
  117. return None
  118. json_data = await self._handle_response(resp)
  119. if response_type is not JSON:
  120. return response_type.deserialize(json_data)
  121. return json_data
  122. async def _handle_response(self, resp: ClientResponse) -> JSON:
  123. self._handle_response_headers(resp)
  124. body = await resp.json()
  125. if body.get("status", "fail") == "ok":
  126. return body
  127. else:
  128. await self._raise_response_error(resp)
  129. async def _raise_response_error(self, resp: ClientResponse) -> None:
  130. try:
  131. data = await resp.json()
  132. except json.JSONDecodeError:
  133. data = {}
  134. if data.get("spam", False):
  135. raise IGActionSpamError(resp, data)
  136. elif data.get("two_factor_required", False):
  137. raise IGLoginTwoFactorRequiredError(resp, data)
  138. elif resp.status == 404:
  139. raise IGNotFoundError(resp, data)
  140. elif resp.status == 429:
  141. raise IGRateLimitError(resp, data)
  142. message = data.get("message")
  143. if isinstance(message, str):
  144. if message == "challenge_required":
  145. err = IGCheckpointError(resp, data)
  146. self.state.challenge_path = err.url
  147. raise err
  148. elif message == "user_has_logged_out":
  149. raise IGUserHasLoggedOutError(resp, data)
  150. elif message == "login_required":
  151. raise IGLoginRequiredError(resp, data)
  152. elif message.lower() == "not authorized to view user":
  153. raise IGPrivateUserError(resp, data)
  154. error_type = data.get("error_type")
  155. if error_type == "sentry_block":
  156. raise IGSentryBlockError(resp, data)
  157. elif error_type == "inactive_user":
  158. raise IGInactiveUserError(resp, data)
  159. elif error_type == "bad_password":
  160. raise IGLoginBadPasswordError(resp, data)
  161. elif error_type == "invalid_user":
  162. raise IGLoginInvalidUserError(resp, data)
  163. elif error_type == "sms_code_validation_code_invalid":
  164. raise IGBad2FACodeError(resp, data)
  165. raise IGResponseError(resp, data)
  166. def _handle_response_headers(self, resp: ClientResponse) -> None:
  167. fields = {
  168. "x-ig-set-www-claim": "ig_www_claim",
  169. "ig-set-authorization": "authorization",
  170. "ig-set-password-encryption-key-id": "password_encryption_key_id",
  171. "ig-set-password-encryption-pub-key": "password_encryption_pubkey",
  172. "ig-set-ig-u-ig-direct-region-hint": "region_hint",
  173. "ig-set-ig-u-shbid": "shbid",
  174. "ig-set-ig-u-shbts": "shbts",
  175. "ig-set-ig-u-rur": "rur",
  176. "ig-set-ig-u-ds-user-id": "ds_user_id",
  177. }
  178. for header, field in fields.items():
  179. value = resp.headers.get(header)
  180. if value and (header != "IG-Set-Authorization" or not value.endswith(":")):
  181. setattr(self.state.session, field, value)