__init__.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import json
  2. import os
  3. import subprocess
  4. import urllib.parse
  5. import urllib.request
  6. """
  7. official api documentation:
  8. https://github.com/ToontownRewritten/api-doc/blob/master/login.md
  9. https://github.com/ToontownRewritten/api-doc/blob/master/invasions.md
  10. """
  11. INVASIONS_API_URL = 'https://www.toontownrewritten.com/api/invasions?format=json'
  12. LOGIN_API_URL = 'https://www.toontownrewritten.com/api/login?format=json'
  13. def start_engine(engine_path, gameserver, playcookie, **kwargs):
  14. return subprocess.Popen(
  15. args=[engine_path],
  16. cwd=os.path.dirname(engine_path),
  17. env={
  18. 'TTR_GAMESERVER': gameserver,
  19. 'TTR_PLAYCOOKIE': playcookie,
  20. },
  21. **kwargs,
  22. )
  23. def api_request(url, params=None):
  24. resp = urllib.request.urlopen(
  25. url=url,
  26. data=urllib.parse.urlencode(params).encode('ascii')
  27. if params else None,
  28. )
  29. return json.loads(resp.read().decode('ascii'))
  30. class LoginSuccessful:
  31. def __init__(self, playcookie, gameserver):
  32. self.playcookie = playcookie
  33. self.gameserver = gameserver
  34. class LoginDelayed:
  35. def __init__(self, queue_token):
  36. self.queue_token = queue_token
  37. def login(username=None, password=None, queue_token=None):
  38. if username is not None and queue_token is None:
  39. assert password is not None
  40. req_params = {
  41. 'username': username,
  42. 'password': password,
  43. }
  44. elif username is None and queue_token is not None:
  45. req_params = {
  46. 'queueToken': queue_token,
  47. }
  48. else:
  49. raise Exception('either specify username or queue token')
  50. resp_data = api_request(
  51. url=LOGIN_API_URL,
  52. params=req_params,
  53. )
  54. if resp_data['success'] == 'true':
  55. return LoginSuccessful(
  56. playcookie=resp_data['cookie'],
  57. gameserver=resp_data['gameserver'],
  58. )
  59. elif resp_data['success'] == 'delayed':
  60. return LoginDelayed(
  61. queue_token=resp_data['queueToken'],
  62. )
  63. else:
  64. raise Exception(repr(resp_data))
  65. def launch(engine_path, username, password):
  66. result = login(
  67. username=username,
  68. password=password,
  69. )
  70. if isinstance(result, LoginDelayed):
  71. result = login(queue_token=result.queue_token)
  72. if isinstance(result, LoginSuccessful):
  73. p = start_engine(
  74. engine_path=engine_path,
  75. gameserver=result.gameserver,
  76. playcookie=result.playcookie,
  77. )
  78. p.wait()
  79. else:
  80. raise Exception(repr(result))