base.py 11 KB

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