Guest User

Untitled

a guest
Apr 18th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.96 KB | None | 0 0
  1. import cherrypy
  2. import os
  3. import sys
  4. import time
  5. import threading
  6. import traceback
  7. import webbrowser
  8. from datetime import datetime, timedelta
  9.  
  10. from selenium import webdriver
  11. from selenium.webdriver.firefox.options import Options
  12.  
  13. from base64 import b64encode
  14. from fitbit.api import Fitbit
  15. from oauthlib.oauth2.rfc6749.errors import MismatchingStateError, MissingTokenError
  16.  
  17. #Fitbit details
  18. client_id = ""
  19. client_secret = ""
  20.  
  21. #TR Details
  22. tr_username = ""
  23. tr_passwd = ""
  24.  
  25. class OAuth2Server:
  26.     def __init__(self, client_id, client_secret,
  27.                  redirect_uri='http://127.0.0.1:8080/'):
  28.         """ Initialize the FitbitOauth2Client """
  29.         self.success_html = """
  30.            <h1>You are now authorized to access the Fitbit API!</h1>
  31.            <br/><h3>You can close this window</h3>"""
  32.         self.failure_html = """
  33.            <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s"""
  34.  
  35.         self.fitbit = Fitbit(
  36.             client_id,
  37.             client_secret,
  38.             redirect_uri=redirect_uri,
  39.             timeout=10,
  40.         )
  41.  
  42.     def browser_authorize(self):
  43.         """
  44.        Open a browser to the authorization url and spool up a CherryPy
  45.        server to accept the response
  46.        """
  47.         url, _ = self.fitbit.client.authorize_token_url()
  48.         # Open the web browser in a new thread for command-line browser support
  49.         threading.Timer(1, webbrowser.open, args=(url,)).start()
  50.         cherrypy.quickstart(self)
  51.  
  52.     @cherrypy.expose
  53.     def index(self, state, code=None, error=None):
  54.         """
  55.        Receive a Fitbit response containing a verification code. Use the code
  56.        to fetch the access_token.
  57.        """
  58.         error = None
  59.         if code:
  60.             try:
  61.                 self.fitbit.client.fetch_access_token(code)
  62.             except MissingTokenError:
  63.                 error = self._fmt_failure(
  64.                     'Missing access token parameter.</br>Please check that '
  65.                     'you are using the correct client_secret')
  66.             except MismatchingStateError:
  67.                 error = self._fmt_failure('CSRF Warning! Mismatching state')
  68.         else:
  69.             error = self._fmt_failure('Unknown error while authenticating')
  70.         # Use a thread to shutdown cherrypy so we can return HTML first
  71.         self._shutdown_cherrypy()
  72.         return error if error else self.success_html
  73.  
  74.     def _fmt_failure(self, message):
  75.         tb = traceback.format_tb(sys.exc_info()[2])
  76.         tb_html = '<pre>%s</pre>' % ('\n'.join(tb)) if tb else ''
  77.         return self.failure_html % (message, tb_html)
  78.  
  79.     def _shutdown_cherrypy(self):
  80.         """ Shutdown cherrypy in one second, if it's running """
  81.         if cherrypy.engine.state == cherrypy.engine.states.STARTED:
  82.             threading.Timer(1, cherrypy.engine.exit).start()
  83.  
  84.  
  85. def get_weight(key, value):
  86.    
  87.     authd_client = Fitbit(client_id, client_secret, access_token=key, refresh_token=value, system='en_AU')
  88.    
  89.     base = datetime.today()
  90.     date_list = [base - timedelta(days=x) for x in range(0, 20)]
  91.    
  92.     for date in date_list:
  93.         try:
  94.             date = date.strftime('%Y-%m-%d')
  95.             return_dict = authd_client.get_bodyweight(user_id='-', base_date=date)
  96.             for x in return_dict['weight']:
  97.                 weight = float(x['weight'])
  98.             if weight > 0:
  99.                 break
  100.         except:
  101.             continue
  102.        
  103.     return weight
  104.  
  105.  
  106. def update_weight(username, passwd, weight):
  107.     #headless firefox
  108.     options = Options()
  109.     options.headless = True
  110.     driver = webdriver.Firefox(options=options)
  111.    
  112.     #load page
  113.     driver.get('https://www.trainerroad.com/login?ReturnUrl=%2fprofile%2frider-information')
  114.    
  115.     #login username
  116.     user_input = driver.find_element_by_xpath('//*[@id="Username"]')
  117.     user_input.send_keys(username)
  118.    
  119.     #login password
  120.     pw_input = driver.find_element_by_xpath('//*[@id="Password"]')
  121.     pw_input.send_keys(passwd)
  122.    
  123.     #click login button
  124.     driver.find_element_by_xpath('/html/body/div/div[1]/div[2]/div/div[2]/form/button').click()
  125.    
  126.     #update weight
  127.     weight_input = driver.find_element_by_xpath('//*[@id="Weight"]')
  128.     weight_input.clear()
  129.     weight_input.send_keys(weight)
  130.    
  131.     #click update button
  132.     driver.find_element_by_xpath('//*[@id="UpdateInformationId"]').click()
  133.    
  134.     #close driver
  135.     driver.quit()
  136.    
  137.  
  138. if __name__ == '__main__':
  139.     server = OAuth2Server(client_id, client_secret)
  140.     server.browser_authorize()
  141.    
  142.     profile = server.fitbit.user_profile_get()
  143.    
  144.     for idx, (key, value) in enumerate(server.fitbit.client.session.token.items(), start=0):
  145.         if idx == 0:
  146.             acccess = value
  147.         elif idx == 2:
  148.             refresh = value
  149.            
  150.     #get weight details from fitbit
  151.     weight = str(get_weight(acccess, refresh))
  152.    
  153.     #log weight in tr
  154.     update_weight(tr_username, tr_passwd, weight)
Add Comment
Please, Sign In to add comment