base.py 9.4 KB

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