base.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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
  17. import random
  18. import time
  19. from aiohttp import ClientSession, ClientResponse
  20. from yarl import URL
  21. from mautrix.types import JSON
  22. from ..state import AndroidState
  23. class BaseAndroidAPI:
  24. url = URL("https://i.instagram.com")
  25. http: ClientSession
  26. state: AndroidState
  27. def __init__(self, state: AndroidState) -> None:
  28. self.http = ClientSession(cookie_jar=state.cookies.jar)
  29. self.state = state
  30. @property
  31. def headers(self) -> Dict[str, str]:
  32. headers = {
  33. "User-Agent": self.state.user_agent,
  34. "X-Ads-Opt-Out": str(int(self.state.session.ads_opt_out)),
  35. #"X-DEVICE--ID": self.state.device.uuid,
  36. "X-CM-Bandwidth-KBPS": "-1.000",
  37. "X-CM-Latency": "-1.000",
  38. "X-IG-App-Locale": self.state.device.language,
  39. "X-IG-Device-Locale": self.state.device.language,
  40. "X-Pigeon-Session-Id": self.state.pigeon_session_id,
  41. "X-Pigeon-Rawclienttime": str(round(time.time(), 3)),
  42. "X-IG-Connection-Speed": f"{random.randint(1000, 3700)}kbps",
  43. "X-IG-Bandwidth-Speed-KBPS": "-1.000",
  44. "X-IG-Bandwidth-TotalBytes-B": "0",
  45. "X-IG-Bandwidth-TotalTime-MS": "0",
  46. "X-IG-EU-DC-ENABLED": (str(self.state.session.eu_dc_enabled).lower()
  47. if self.state.session.eu_dc_enabled else None),
  48. "X-IG-Extended-CDN-Thumbnail-Cache-Busting-Value":
  49. str(self.state.session.thumbnail_cache_busting_value),
  50. "X-Bloks-Version-Id": self.state.application.BLOKS_VERSION_ID,
  51. "X-MID": self.state.cookies.get_value("mid"),
  52. "X-IG-WWW-Claim": self.state.session.ig_www_claim or "0",
  53. "X-Bloks-Is-Layout-RTL": str(self.state.device.is_layout_rtl).lower(),
  54. "X-IG-Connection-Type": self.state.device.connection_type,
  55. "X-Ig-Capabilities": self.state.application.CAPABILITIES,
  56. "X-IG-App-Id": self.state.application.FACEBOOK_ANALYTICS_APPLICATION_ID,
  57. "X-IG-Device-ID": self.state.device.uuid,
  58. "X-IG-Android-ID": self.state.device.id,
  59. "Accept-Language": self.state.device.language.replace("_", "-"),
  60. "X-FB-HTTP-Engine": "Liger",
  61. "Authorization": self.state.session.authorization,
  62. "Accept-Encoding": "gzip",
  63. "Connection": "close",
  64. }
  65. return {k: v for k, v in headers.items() if v is not None}
  66. async def handle_response(self, resp: ClientResponse) -> JSON:
  67. self._handle_response_headers(resp)
  68. body = await resp.json()
  69. if body["status"] == "ok":
  70. return body
  71. else:
  72. await self._raise_response_error(resp)
  73. async def _raise_response_error(self, resp: ClientResponse) -> None:
  74. # TODO handle all errors
  75. print("Error:", resp.status)
  76. print(await resp.json())
  77. raise Exception("oh noes")
  78. def _handle_response_headers(self, resp: ClientResponse) -> None:
  79. fields = {
  80. "X-IG-Set-WWW-Claim": "ig_www_claim",
  81. "IG-Set-Authorization": "authorization",
  82. "IG-Set-Password-Encryption-Key-ID": "password_encryption_key_id",
  83. "IG-Set-Password-Encryption-Pub-Key": "password_encryption_pubkey",
  84. "IG-Set-IG-U-IG-Direct-Region-Hint": "region_hint"
  85. }
  86. for header, field in fields.items():
  87. try:
  88. value = resp.headers[header]
  89. except KeyError:
  90. pass
  91. else:
  92. if value:
  93. setattr(self.state.session, field, value)