base.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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
  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,
  27. IGLoginBadPasswordError, IGLoginInvalidUserError,
  28. IGLoginTwoFactorRequiredError)
  29. class BaseAndroidAPI:
  30. url = URL("https://i.instagram.com")
  31. http: ClientSession
  32. state: AndroidState
  33. def __init__(self, state: AndroidState) -> None:
  34. self.http = ClientSession(cookie_jar=state.cookies.jar)
  35. self.state = state
  36. @staticmethod
  37. def sign(req: Any, filter_nulls: bool = False) -> Dict[str, str]:
  38. if isinstance(req, Serializable):
  39. req = req.serialize()
  40. if isinstance(req, dict):
  41. def remove_nulls(d: dict) -> dict:
  42. return {k: v for k, v in d.items() if v is not None}
  43. req = json.dumps(req, object_hook=remove_nulls if filter_nulls else None)
  44. return {"signed_body": f"SIGNATURE.{req}"}
  45. @property
  46. def headers(self) -> Dict[str, str]:
  47. headers = {
  48. "User-Agent": self.state.user_agent,
  49. "X-Ads-Opt-Out": str(int(self.state.session.ads_opt_out)),
  50. # "X-DEVICE--ID": self.state.device.uuid,
  51. "X-CM-Bandwidth-KBPS": "-1.000",
  52. "X-CM-Latency": "-1.000",
  53. "X-IG-App-Locale": self.state.device.language,
  54. "X-IG-Device-Locale": self.state.device.language,
  55. "X-Pigeon-Session-Id": self.state.pigeon_session_id,
  56. "X-Pigeon-Rawclienttime": str(round(time.time(), 3)),
  57. "X-IG-Connection-Speed": f"{random.randint(1000, 3700)}kbps",
  58. "X-IG-Bandwidth-Speed-KBPS": "-1.000",
  59. "X-IG-Bandwidth-TotalBytes-B": "0",
  60. "X-IG-Bandwidth-TotalTime-MS": "0",
  61. "X-IG-EU-DC-ENABLED": (str(self.state.session.eu_dc_enabled).lower()
  62. if self.state.session.eu_dc_enabled is not None else None),
  63. "X-IG-Extended-CDN-Thumbnail-Cache-Busting-Value":
  64. str(self.state.session.thumbnail_cache_busting_value),
  65. "X-Bloks-Version-Id": self.state.application.BLOKS_VERSION_ID,
  66. "X-MID": self.state.cookies.get_value("mid"),
  67. "X-IG-WWW-Claim": self.state.session.ig_www_claim or "0",
  68. "X-Bloks-Is-Layout-RTL": str(self.state.device.is_layout_rtl).lower(),
  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. "X-IG-Device-ID": self.state.device.uuid,
  73. "X-IG-Android-ID": self.state.device.id,
  74. "Accept-Language": self.state.device.language.replace("_", "-"),
  75. "X-FB-HTTP-Engine": "Liger",
  76. "Authorization": self.state.session.authorization,
  77. "Accept-Encoding": "gzip",
  78. "Connection": "close",
  79. }
  80. return {k: v for k, v in headers.items() if v is not None}
  81. async def handle_response(self, resp: ClientResponse) -> JSON:
  82. self._handle_response_headers(resp)
  83. body = await resp.json()
  84. if body["status"] == "ok":
  85. return body
  86. else:
  87. await self._raise_response_error(resp)
  88. async def _raise_response_error(self, resp: ClientResponse) -> None:
  89. try:
  90. data = await resp.json()
  91. except json.JSONDecodeError:
  92. data = {}
  93. if data.get("spam", False):
  94. raise IGActionSpamError(resp, data)
  95. elif data.get("two_factor_required", False):
  96. raise IGLoginTwoFactorRequiredError(resp, data)
  97. elif resp.status == 404:
  98. raise IGNotFoundError(resp, data)
  99. elif resp.status == 429:
  100. raise IGRateLimitError(resp, data)
  101. message = data.get("message")
  102. if isinstance(message, str):
  103. if message == "challenge_required":
  104. err = IGCheckpointError(resp, data)
  105. self.state.challenge_path = err.url
  106. raise err
  107. elif message == "user_has_logged_out":
  108. raise IGUserHasLoggedOutError(resp, data)
  109. elif message == "login_required":
  110. raise IGLoginRequiredError(resp, data)
  111. elif message.lower() == "not authorized to view user":
  112. raise IGPrivateUserError(resp, data)
  113. error_type = data.get("error_type")
  114. if error_type == "sentry_block":
  115. raise IGSentryBlockError(resp, data)
  116. elif error_type == "inactive_user":
  117. raise IGInactiveUserError(resp, data)
  118. elif error_type == "bad_password":
  119. raise IGLoginBadPasswordError(resp, data)
  120. elif error_type == "invalid_user":
  121. raise IGLoginInvalidUserError(resp, data)
  122. raise IGResponseError(resp, data)
  123. def _handle_response_headers(self, resp: ClientResponse) -> None:
  124. fields = {
  125. "X-IG-Set-WWW-Claim": "ig_www_claim",
  126. "IG-Set-Authorization": "authorization",
  127. "IG-Set-Password-Encryption-Key-ID": "password_encryption_key_id",
  128. "IG-Set-Password-Encryption-Pub-Key": "password_encryption_pubkey",
  129. "IG-Set-IG-U-IG-Direct-Region-Hint": "region_hint"
  130. }
  131. for header, field in fields.items():
  132. try:
  133. value = resp.headers[header]
  134. except KeyError:
  135. pass
  136. else:
  137. if value:
  138. setattr(self.state.session, field, value)