base.py 9.6 KB

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