get_profile.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #!/usr/bin/env python
  2. #
  3. # Adapted from https://github.com/jlemon/zlogger/blob/master/get_riders.py
  4. #
  5. # The MIT License (MIT)
  6. #
  7. # Copyright (c) 2016 Jonathan Lemon
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a copy
  10. # of this software and associated documentation files (the "Software"), to deal
  11. # in the Software without restriction, including without limitation the rights
  12. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the Software is
  14. # furnished to do so, subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included in all
  17. # copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. # FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
  22. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. # SOFTWARE.
  26. import argparse
  27. import getpass
  28. import json
  29. import os
  30. import requests
  31. import sys
  32. sys.path.insert(0, '../protobuf')
  33. import login_pb2
  34. from google.protobuf.json_format import MessageToDict
  35. from random import randbytes
  36. if getattr(sys, 'frozen', False):
  37. # If we're running as a py installer bundle
  38. SCRIPT_DIR = os.path.dirname(sys.executable)
  39. else:
  40. SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
  41. try:
  42. input = raw_input
  43. except NameError:
  44. pass
  45. global args
  46. global dbh
  47. def post_credentials(session, username, password):
  48. # Credentials POSTing and tokens retrieval
  49. # POST https://secure.zwift.com/auth/realms/zwift/tokens/access/codes
  50. try:
  51. response = session.post(
  52. url="https://secure.zwift.com/auth/realms/zwift/tokens/access/codes",
  53. headers={
  54. "Accept": "*/*",
  55. "Accept-Encoding": "gzip, deflate",
  56. "Connection": "keep-alive",
  57. "Content-Type": "application/x-www-form-urlencoded",
  58. "Host": "secure.zwift.com",
  59. "User-Agent": "Zwift/1.5 (iPhone; iOS 9.0.2; Scale/2.00)",
  60. "Accept-Language": "en-US;q=1",
  61. },
  62. data={
  63. "client_id": "Zwift_Mobile_Link",
  64. "username": username,
  65. "password": password,
  66. "grant_type": "password",
  67. },
  68. allow_redirects=False,
  69. verify=args.verifyCert,
  70. )
  71. if args.verbose:
  72. print('Response HTTP Status Code: {status_code}'.format(
  73. status_code=response.status_code))
  74. print('Response HTTP Response Body: {content}'.format(
  75. content=response.content))
  76. json_dict = json.loads(response.content)
  77. return (json_dict["access_token"], json_dict["refresh_token"], json_dict["expires_in"])
  78. except requests.exceptions.RequestException as e:
  79. print('HTTP Request failed: %s' % e)
  80. except KeyError as e:
  81. print('Invalid uname and/or password')
  82. exit(-1)
  83. def query(session, access_token, route):
  84. try:
  85. response = session.get(
  86. url="https://us-or-rly101.zwift.com/%s" % route,
  87. headers={
  88. "Accept-Encoding": "gzip, deflate",
  89. "Accept": "application/x-protobuf-lite",
  90. "Connection": "keep-alive",
  91. "Host": "us-or-rly101.zwift.com",
  92. "User-Agent": "Zwift/115 CFNetwork/758.0.2 Darwin/15.0.0",
  93. "Authorization": "Bearer %s" % access_token,
  94. "Accept-Language": "en-us",
  95. },
  96. verify=args.verifyCert,
  97. )
  98. if args.verbose:
  99. print('Response HTTP Status Code: {status_code}'.format(
  100. status_code=response.status_code))
  101. return response.content
  102. except requests.exceptions.RequestException as e:
  103. print('HTTP Request failed: %s' % e)
  104. def api_login(session, access_token, login_request):
  105. try:
  106. response = session.post(
  107. url="https://us-or-rly101.zwift.com/api/users/login",
  108. headers={
  109. "Content-Type": "application/x-protobuf-lite",
  110. "Accept": "application/x-protobuf-lite",
  111. "Connection": "keep-alive",
  112. "Host": "us-or-rly101.zwift.com",
  113. "User-Agent": "Zwift/115 CFNetwork/758.0.2 Darwin/15.0.0",
  114. "Authorization": "Bearer %s" % access_token,
  115. "Accept-Language": "en-us",
  116. },
  117. data=login_request.SerializeToString(),
  118. verify=args.verifyCert,
  119. )
  120. if args.verbose:
  121. print('Response HTTP Status Code: {status_code}'.format(
  122. status_code=response.status_code))
  123. return response.content
  124. except requests.exceptions.RequestException as e:
  125. print('HTTP Request failed: %s' % e)
  126. def logout(session, refresh_token):
  127. # Logout
  128. # POST https://secure.zwift.com/auth/realms/zwift/tokens/logout
  129. try:
  130. response = session.post(
  131. url="https://secure.zwift.com/auth/realms/zwift/tokens/logout",
  132. headers={
  133. "Accept": "*/*",
  134. "Accept-Encoding": "gzip, deflate",
  135. "Connection": "keep-alive",
  136. "Content-Type": "application/x-www-form-urlencoded",
  137. "Host": "secure.zwift.com",
  138. "User-Agent": "Zwift/1.5 (iPhone; iOS 9.0.2; Scale/2.00)",
  139. "Accept-Language": "en-US;q=1",
  140. },
  141. data={
  142. "client_id": "Zwift_Mobile_Link",
  143. "refresh_token": refresh_token,
  144. },
  145. verify=args.verifyCert,
  146. )
  147. if args.verbose:
  148. print('Response HTTP Status Code: {status_code}'.format(
  149. status_code=response.status_code))
  150. print('Response HTTP Response Body: {content}'.format(
  151. content=response.content))
  152. except requests.exceptions.RequestException as e:
  153. print('HTTP Request failed: %s' % e)
  154. def login(session, user, password):
  155. access_token, refresh_token, expired_in = post_credentials(session, user, password)
  156. return access_token, refresh_token
  157. def main(argv):
  158. global args
  159. global dbh
  160. access_token = None
  161. cookies = None
  162. parser = argparse.ArgumentParser(description='Zwift Profile Fetcher')
  163. parser.add_argument('-v', '--verbose', action='store_true',
  164. help='Verbose output')
  165. parser.add_argument('--dont-check-certificates', action='store_false',
  166. dest='verifyCert', default=True)
  167. parser.add_argument('-u', '--user', help='Zwift user name')
  168. args = parser.parse_args()
  169. # if args.user:
  170. # password = getpass.getpass("Password for %s? " % args.user)
  171. # else:
  172. # file = os.environ['HOME'] + '/.zwift_cred.json'
  173. # with open(file) as f:
  174. # try:
  175. # cred = json.load(f)
  176. # except ValueError, se:
  177. # sys.exit('"%s": %s' % (args.output, se))
  178. # f.close
  179. # args.user = cred['user']
  180. # password = cred['pass']
  181. if args.user:
  182. username = args.user
  183. else:
  184. username = input("Enter Zwift login (e-mail): ")
  185. if not sys.stdin.isatty(): # This terminal cannot support input without displaying text
  186. print(f'*WARNING* The current shell ({os.name}) cannot support hidden text entry.')
  187. print(f'Your password entry WILL BE VISIBLE.')
  188. print(f'If you are running a bash shell under windows, try executing this program via winpty:')
  189. print(f'>winpty python {argv[0]}')
  190. password = input("Enter password (will be shown):")
  191. else:
  192. password = getpass.getpass("Enter password: ")
  193. session = requests.session()
  194. access_token, refresh_token = login(session, username, password)
  195. profile = query(session, access_token, "api/profiles/me")
  196. with open('%s/profile.bin' % SCRIPT_DIR, 'wb') as f:
  197. f.write(profile)
  198. achievements = query(session, access_token, "achievement/loadPlayerAchievements")
  199. with open('%s/achievements.bin' % SCRIPT_DIR, 'wb') as f:
  200. f.write(achievements)
  201. login_request = login_pb2.LoginRequest()
  202. login_request.key = randbytes(16)
  203. login_response = login_pb2.LoginResponse()
  204. login_response.ParseFromString(api_login(session, access_token, login_request))
  205. login_response_dict = MessageToDict(login_response, preserving_proto_field_name=True)
  206. if 'economy_config' in login_response_dict:
  207. with open('%s/economy_config.txt' % SCRIPT_DIR, 'w') as f:
  208. json.dump(login_response_dict['economy_config'], f, indent=2)
  209. logout(session, refresh_token)
  210. if __name__ == '__main__':
  211. try:
  212. main(sys.argv)
  213. except KeyboardInterrupt:
  214. pass
  215. except SystemExit as se:
  216. print("ERROR:", se)