base.py 10 KB

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