har_file.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from __future__ import annotations
  2. import json
  3. import os
  4. import os.path
  5. import random
  6. import logging
  7. from ...requests import StreamSession, raise_for_status
  8. from ...cookies import get_cookies_dir
  9. from ...errors import MissingRequirementsError
  10. from ... import debug
  11. logger = logging.getLogger(__name__)
  12. class NoValidHarFileError(Exception):
  13. ...
  14. class arkReq:
  15. def __init__(self, arkURL, arkHeaders, arkBody, arkCookies, userAgent):
  16. self.arkURL = arkURL
  17. self.arkHeaders = arkHeaders
  18. self.arkBody = arkBody
  19. self.arkCookies = arkCookies
  20. self.userAgent = userAgent
  21. telemetry_url = "https://telemetry.stytch.com/submit"
  22. public_token = "public-token-live-507a52ad-7e69-496b-aee0-1c9863c7c819"
  23. chatArks: list = None
  24. def readHAR():
  25. harPath = []
  26. chatArks = []
  27. for root, dirs, files in os.walk(get_cookies_dir()):
  28. for file in files:
  29. if file.endswith(".har"):
  30. harPath.append(os.path.join(root, file))
  31. if harPath:
  32. break
  33. if not harPath:
  34. raise NoValidHarFileError("No .har file found")
  35. for path in harPath:
  36. with open(path, 'rb') as file:
  37. try:
  38. harFile = json.load(file)
  39. except json.JSONDecodeError:
  40. # Error: not a HAR file!
  41. continue
  42. for v in harFile['log']['entries']:
  43. if v['request']['url'] == telemetry_url:
  44. chatArks.append(parseHAREntry(v))
  45. if not chatArks:
  46. raise NoValidHarFileError("No telemetry in .har files found")
  47. return chatArks
  48. def parseHAREntry(entry) -> arkReq:
  49. tmpArk = arkReq(
  50. arkURL=entry['request']['url'],
  51. arkHeaders={h['name'].lower(): h['value'] for h in entry['request']['headers'] if h['name'].lower() not in ['content-length', 'cookie'] and not h['name'].startswith(':')},
  52. arkBody=entry['request']['postData']['text'],
  53. arkCookies={c['name']: c['value'] for c in entry['request']['cookies']},
  54. userAgent=""
  55. )
  56. tmpArk.userAgent = tmpArk.arkHeaders.get('user-agent', '')
  57. return tmpArk
  58. async def sendRequest(tmpArk: arkReq, proxy: str = None):
  59. async with StreamSession(headers=tmpArk.arkHeaders, cookies=tmpArk.arkCookies, proxy=proxy) as session:
  60. async with session.post(tmpArk.arkURL, data=tmpArk.arkBody) as response:
  61. await raise_for_status(response)
  62. return await response.text()
  63. async def create_telemetry_id(proxy: str = None):
  64. global chatArks
  65. if chatArks is None:
  66. chatArks = readHAR()
  67. return await sendRequest(random.choice(chatArks), proxy)
  68. async def get_telemetry_ids(proxy: str = None) -> list:
  69. try:
  70. return [await create_telemetry_id(proxy)]
  71. except NoValidHarFileError as e:
  72. if debug.logging:
  73. logger.error(e)
  74. try:
  75. from nodriver import start
  76. except ImportError:
  77. raise MissingRequirementsError('Add .har file from you.com or install "nodriver" package | pip install -U nodriver')
  78. if debug.logging:
  79. logger.error('Getting telemetry_id for you.com with nodriver')
  80. browser = page = None
  81. try:
  82. browser = await start(
  83. browser_args=None if proxy is None else [f"--proxy-server={proxy}"],
  84. )
  85. page = await browser.get("https://you.com")
  86. while not await page.evaluate('"GetTelemetryID" in this'):
  87. await page.sleep(1)
  88. async def get_telemetry_id():
  89. return await page.evaluate(
  90. f'this.GetTelemetryID("{public_token}", "{telemetry_url}");',
  91. await_promise=True
  92. )
  93. return [await get_telemetry_id()]
  94. finally:
  95. try:
  96. if page is not None:
  97. await page.close()
  98. if browser is not None:
  99. await browser.stop()
  100. except Exception as e:
  101. if debug.logging:
  102. logger.error(e)