upload_activity.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 activity_pb2
  34. import profile_pb2
  35. try:
  36. input = raw_input
  37. except NameError:
  38. pass
  39. global args
  40. def post_credentials(session, username, password):
  41. # Credentials POSTing and tokens retrieval
  42. # POST https://secure.zwift.com/auth/realms/zwift/tokens/access/codes
  43. try:
  44. response = session.post(
  45. url="https://secure.zwift.com/auth/realms/zwift/tokens/access/codes",
  46. headers={
  47. "Accept": "*/*",
  48. "Accept-Encoding": "gzip, deflate",
  49. "Connection": "keep-alive",
  50. "Content-Type": "application/x-www-form-urlencoded",
  51. "Host": "secure.zwift.com",
  52. "User-Agent": "Zwift/1.5 (iPhone; iOS 9.0.2; Scale/2.00)",
  53. "Accept-Language": "en-US;q=1",
  54. },
  55. data={
  56. "client_id": "Zwift_Mobile_Link",
  57. "username": username,
  58. "password": password,
  59. "grant_type": "password",
  60. },
  61. allow_redirects=False,
  62. verify=args.verifyCert,
  63. )
  64. if args.verbose:
  65. print('Response HTTP Status Code: {status_code}'.format(
  66. status_code=response.status_code))
  67. print('Response HTTP Response Body: {content}'.format(
  68. content=response.content))
  69. json_dict = json.loads(response.content)
  70. return (json_dict["access_token"], json_dict["refresh_token"], json_dict["expires_in"])
  71. except requests.exceptions.RequestException as e:
  72. print('HTTP Request failed: %s' % e)
  73. except KeyError as e:
  74. print('Invalid uname and/or password')
  75. sys.exit()
  76. def create_activity(session, access_token, activity):
  77. try:
  78. response = session.post(
  79. url="https://us-or-rly101.zwift.com/api/profiles/%s/activities" % activity.player_id,
  80. headers={
  81. "Content-Type": "application/x-protobuf-lite",
  82. "Accept": "application/json",
  83. "Connection": "keep-alive",
  84. "Host": "us-or-rly101.zwift.com",
  85. "User-Agent": "Zwift/115 CFNetwork/758.0.2 Darwin/15.0.0",
  86. "Authorization": "Bearer %s" % access_token,
  87. "Accept-Language": "en-us",
  88. },
  89. data=activity.SerializeToString(),
  90. verify=args.verifyCert,
  91. )
  92. if args.verbose:
  93. print('Response HTTP Status Code: {status_code}'.format(
  94. status_code=response.status_code))
  95. json_dict = json.loads(response.content)
  96. return json_dict["id"]
  97. except requests.exceptions.RequestException as e:
  98. print('HTTP Request failed: %s' % e)
  99. def upload_activity(session, access_token, activity):
  100. try:
  101. response = session.put(
  102. url="https://us-or-rly101.zwift.com/api/profiles/%s/activities/%s" % (activity.player_id, activity.id),
  103. headers={
  104. "Content-Type": "application/x-protobuf-lite",
  105. "Accept": "application/json",
  106. "Connection": "keep-alive",
  107. "Host": "us-or-rly101.zwift.com",
  108. "User-Agent": "Zwift/115 CFNetwork/758.0.2 Darwin/15.0.0",
  109. "Authorization": "Bearer %s" % access_token,
  110. "Accept-Language": "en-us",
  111. },
  112. data=activity.SerializeToString(),
  113. params={"upload-to-strava": "true"},
  114. verify=args.verifyCert,
  115. )
  116. if args.verbose:
  117. print('Response HTTP Status Code: {status_code}'.format(
  118. status_code=response.status_code))
  119. json_dict = json.loads(response.content)
  120. return json_dict["id"]
  121. except requests.exceptions.RequestException as e:
  122. print('HTTP Request failed: %s' % e)
  123. def get_player_id(session, access_token):
  124. try:
  125. response = session.get(
  126. url="https://us-or-rly101.zwift.com/api/profiles/me",
  127. headers={
  128. "Accept-Encoding": "gzip, deflate",
  129. "Accept": "application/x-protobuf-lite",
  130. "Connection": "keep-alive",
  131. "Host": "us-or-rly101.zwift.com",
  132. "User-Agent": "Zwift/115 CFNetwork/758.0.2 Darwin/15.0.0",
  133. "Authorization": "Bearer %s" % access_token,
  134. "Accept-Language": "en-us",
  135. },
  136. verify=args.verifyCert,
  137. )
  138. if args.verbose:
  139. print('Response HTTP Status Code: {status_code}'.format(
  140. status_code=response.status_code))
  141. profile = profile_pb2.PlayerProfile()
  142. profile.ParseFromString(response.content)
  143. return profile.id
  144. except requests.exceptions.RequestException as e:
  145. print('HTTP Request failed: %s' % e)
  146. def logout(session, refresh_token):
  147. # Logout
  148. # POST https://secure.zwift.com/auth/realms/zwift/tokens/logout
  149. try:
  150. response = session.post(
  151. url="https://secure.zwift.com/auth/realms/zwift/tokens/logout",
  152. headers={
  153. "Accept": "*/*",
  154. "Accept-Encoding": "gzip, deflate",
  155. "Connection": "keep-alive",
  156. "Content-Type": "application/x-www-form-urlencoded",
  157. "Host": "secure.zwift.com",
  158. "User-Agent": "Zwift/1.5 (iPhone; iOS 9.0.2; Scale/2.00)",
  159. "Accept-Language": "en-US;q=1",
  160. },
  161. data={
  162. "client_id": "Zwift_Mobile_Link",
  163. "refresh_token": refresh_token,
  164. },
  165. verify=args.verifyCert,
  166. )
  167. if args.verbose:
  168. print('Response HTTP Status Code: {status_code}'.format(
  169. status_code=response.status_code))
  170. print('Response HTTP Response Body: {content}'.format(
  171. content=response.content))
  172. except requests.exceptions.RequestException as e:
  173. print('HTTP Request failed: %s' % e)
  174. def login(session, user, password):
  175. access_token, refresh_token, expired_in = post_credentials(session, user, password)
  176. return access_token, refresh_token
  177. def main(argv):
  178. global args
  179. access_token = None
  180. cookies = None
  181. print('WARNING: remove zoffline IP from hosts file before running this script')
  182. parser = argparse.ArgumentParser(description='Zwift activity uploader')
  183. parser.add_argument('-v', '--verbose', action='store_true',
  184. help='Verbose output')
  185. parser.add_argument('--dont-check-certificates', action='store_false',
  186. dest='verifyCert', default=True)
  187. parser.add_argument('-u', '--user', help='Zwift user name')
  188. parser.add_argument('-a', '--activity', help='Activity file')
  189. args = parser.parse_args()
  190. activity = activity_pb2.Activity()
  191. if args.activity:
  192. activity_file = args.activity
  193. else:
  194. activity_file = input("Enter activity file: ")
  195. if not os.path.isfile(activity_file):
  196. print('Activity file not found')
  197. sys.exit()
  198. with open(activity_file, 'rb') as fd:
  199. try:
  200. activity.ParseFromString(fd.read())
  201. except:
  202. print('Could not parse activity file')
  203. sys.exit()
  204. if args.user:
  205. username = args.user
  206. else:
  207. username = input("Enter Zwift login (e-mail): ")
  208. if not sys.stdin.isatty(): # This terminal cannot support input without displaying text
  209. print('*WARNING* The current shell (%s) cannot support hidden text entry.' % os.name)
  210. print('Your password entry WILL BE VISIBLE.')
  211. print('If you are running a bash shell under windows, try executing this program via winpty:')
  212. print('>winpty python %s' % argv[0])
  213. password = input("Enter password (will be shown):")
  214. else:
  215. password = getpass.getpass("Enter password: ")
  216. session = requests.session()
  217. access_token, refresh_token = login(session, username, password)
  218. activity.player_id = get_player_id(session, access_token)
  219. new_activity = activity_pb2.Activity()
  220. new_activity.CopyFrom(activity)
  221. new_activity.ClearField('id')
  222. new_activity.ClearField('fit')
  223. activity.id = create_activity(session, access_token, new_activity)
  224. ret = upload_activity(session, access_token, activity)
  225. print(ret)
  226. logout(session, refresh_token)
  227. if __name__ == '__main__':
  228. try:
  229. main(sys.argv)
  230. except KeyboardInterrupt:
  231. pass