__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import datetime
  2. import json
  3. import os
  4. import ssl
  5. import subprocess
  6. import sys
  7. import traceback
  8. import urllib.parse
  9. import urllib.request
  10. import tooncher.controls
  11. """
  12. official api documentation:
  13. https://github.com/ToontownRewritten/api-doc/blob/master/login.md
  14. https://github.com/ToontownRewritten/api-doc/blob/master/invasions.md
  15. """
  16. INVASIONS_API_URL = "https://www.toontownrewritten.com/api/invasions?format=json"
  17. LOGIN_API_URL = "https://www.toontownrewritten.com/api/login?format=json"
  18. if sys.platform == "darwin":
  19. TOONTOWN_LIBRARY_PATH = os.path.join(
  20. os.path.expanduser("~"), "Library", "Application Support", "Toontown Rewritten",
  21. )
  22. TOONTOWN_ENGINE_DEFAULT_PATH = os.path.join(
  23. TOONTOWN_LIBRARY_PATH, "Toontown Rewritten",
  24. )
  25. else:
  26. TOONTOWN_LIBRARY_PATH = None
  27. TOONTOWN_ENGINE_DEFAULT_PATH = None
  28. def start_engine(engine_path, gameserver, playcookie, **kwargs):
  29. env = {
  30. "TTR_GAMESERVER": gameserver,
  31. "TTR_PLAYCOOKIE": playcookie,
  32. }
  33. if sys.platform == "darwin":
  34. env["DYLD_LIBRARY_PATH"] = os.path.join(
  35. TOONTOWN_LIBRARY_PATH, "Libraries.bundle",
  36. )
  37. env["DYLD_FRAMEWORK_PATH"] = os.path.join(TOONTOWN_LIBRARY_PATH, "Frameworks",)
  38. elif sys.platform == "linux" and "XAUTHORITY" in os.environ:
  39. """
  40. Fix for TTREngine reporting:
  41. > :display:x11display(error): Could not open display ":0.0".
  42. > :ToonBase: Default graphics pipe is glxGraphicsPipe (OpenGL).
  43. > :ToonBase(warning): Unable to open 'onscreen' window.
  44. > Traceback (most recent call last):
  45. > File "<compiled '__voltorbmain__'>", line 0, in <module>
  46. > [...]
  47. > File "<compiled 'direct.vlt8f63e471.ShowBase'>", line 0, in vltf05fd21b
  48. > Exception: Could not open window.
  49. """
  50. env["XAUTHORITY"] = os.environ["XAUTHORITY"]
  51. return subprocess.Popen(
  52. args=[engine_path], cwd=os.path.dirname(engine_path), env=env, **kwargs,
  53. )
  54. def api_request(url, params=None, validate_ssl_cert=True):
  55. resp = urllib.request.urlopen(
  56. url=url,
  57. data=urllib.parse.urlencode(params).encode("ascii") if params else None,
  58. context=None if validate_ssl_cert else ssl._create_unverified_context(),
  59. )
  60. return json.loads(resp.read().decode("ascii"))
  61. class LoginSuccessful:
  62. def __init__(self, playcookie, gameserver):
  63. self.playcookie = playcookie
  64. self.gameserver = gameserver
  65. class LoginDelayed:
  66. def __init__(self, queue_token):
  67. self.queue_token = queue_token
  68. def login(username=None, password=None, queue_token=None, validate_ssl_cert=True):
  69. if username is not None and queue_token is None:
  70. assert password is not None
  71. req_params = {
  72. "username": username,
  73. "password": password,
  74. }
  75. elif username is None and queue_token is not None:
  76. req_params = {
  77. "queueToken": queue_token,
  78. }
  79. else:
  80. raise Exception("either specify username or queue token")
  81. resp_data = api_request(
  82. url=LOGIN_API_URL, params=req_params, validate_ssl_cert=validate_ssl_cert,
  83. )
  84. if resp_data["success"] == "true":
  85. return LoginSuccessful(
  86. playcookie=resp_data["cookie"], gameserver=resp_data["gameserver"],
  87. )
  88. elif resp_data["success"] == "delayed":
  89. return LoginDelayed(queue_token=resp_data["queueToken"],)
  90. else:
  91. raise Exception(repr(resp_data))
  92. def launch(engine_path, username, password, validate_ssl_certs=True,
  93. cpu_limit_percent=None, enable_extended_keyboard_controls=False,
  94. extended_keyboard_control_toggle_keysym_name=None,
  95. engine_window_name=None):
  96. if engine_window_name and not enable_extended_keyboard_controls:
  97. raise Exception(
  98. "Enable Extended Controls to change engine's window name",
  99. )
  100. result = login(
  101. username=username, password=password, validate_ssl_cert=validate_ssl_certs,
  102. )
  103. if isinstance(result, LoginDelayed):
  104. result = login(
  105. queue_token=result.queue_token, validate_ssl_cert=validate_ssl_certs,
  106. )
  107. if isinstance(result, LoginSuccessful):
  108. p = start_engine(
  109. engine_path=engine_path,
  110. gameserver=result.gameserver,
  111. playcookie=result.playcookie,
  112. )
  113. if cpu_limit_percent is not None:
  114. subprocess.Popen(args=[
  115. 'cpulimit',
  116. '--pid', str(p.pid),
  117. '--limit', str(cpu_limit_percent),
  118. # '--verbose',
  119. ])
  120. if enable_extended_keyboard_controls:
  121. try:
  122. tooncher.controls.ExtendedControls(
  123. primary_engine_pid=p.pid,
  124. primary_engine_window_name=engine_window_name,
  125. toggle_keysym_name=extended_keyboard_control_toggle_keysym_name,
  126. ).run()
  127. except Exception as e:
  128. if isinstance(e, KeyboardInterrupt):
  129. raise e
  130. else:
  131. traceback.print_exc()
  132. if p.poll() is None:
  133. p.wait()
  134. else:
  135. raise Exception(repr(result))
  136. class InvasionProgress:
  137. def __init__(self, district, date, cog_type, despawned_number, total_number):
  138. self.district = district
  139. self.date = date
  140. self.cog_type = cog_type
  141. self.despawned_number = despawned_number
  142. self.total_number = total_number
  143. @property
  144. def remaining_number(self):
  145. return self.total_number - self.despawned_number
  146. def request_active_invasions(validate_ssl_certs=True):
  147. resp_data = api_request(INVASIONS_API_URL)
  148. if resp_data["error"] is not None:
  149. raise Exception(resp_data["error"])
  150. else:
  151. invs = {}
  152. for district, inv_data in resp_data["invasions"].items():
  153. despawned_number, total_number = inv_data["progress"].split("/")
  154. invs[district] = InvasionProgress(
  155. district=district,
  156. date=datetime.datetime.utcfromtimestamp(inv_data["asOf"]),
  157. cog_type=inv_data["type"],
  158. despawned_number=int(despawned_number),
  159. total_number=int(total_number),
  160. )
  161. return invs