Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cherrypy
- import os
- import sys
- import time
- import threading
- import traceback
- import webbrowser
- from datetime import datetime, timedelta
- from selenium import webdriver
- from selenium.webdriver.firefox.options import Options
- from base64 import b64encode
- from fitbit.api import Fitbit
- from oauthlib.oauth2.rfc6749.errors import MismatchingStateError, MissingTokenError
- #Fitbit details
- client_id = ""
- client_secret = ""
- #TR Details
- tr_username = ""
- tr_passwd = ""
- class OAuth2Server:
- def __init__(self, client_id, client_secret,
- redirect_uri='http://127.0.0.1:8080/'):
- """ Initialize the FitbitOauth2Client """
- self.success_html = """
- <h1>You are now authorized to access the Fitbit API!</h1>
- <br/><h3>You can close this window</h3>"""
- self.failure_html = """
- <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s"""
- self.fitbit = Fitbit(
- client_id,
- client_secret,
- redirect_uri=redirect_uri,
- timeout=10,
- )
- def browser_authorize(self):
- """
- Open a browser to the authorization url and spool up a CherryPy
- server to accept the response
- """
- url, _ = self.fitbit.client.authorize_token_url()
- # Open the web browser in a new thread for command-line browser support
- threading.Timer(1, webbrowser.open, args=(url,)).start()
- cherrypy.quickstart(self)
- @cherrypy.expose
- def index(self, state, code=None, error=None):
- """
- Receive a Fitbit response containing a verification code. Use the code
- to fetch the access_token.
- """
- error = None
- if code:
- try:
- self.fitbit.client.fetch_access_token(code)
- except MissingTokenError:
- error = self._fmt_failure(
- 'Missing access token parameter.</br>Please check that '
- 'you are using the correct client_secret')
- except MismatchingStateError:
- error = self._fmt_failure('CSRF Warning! Mismatching state')
- else:
- error = self._fmt_failure('Unknown error while authenticating')
- # Use a thread to shutdown cherrypy so we can return HTML first
- self._shutdown_cherrypy()
- return error if error else self.success_html
- def _fmt_failure(self, message):
- tb = traceback.format_tb(sys.exc_info()[2])
- tb_html = '<pre>%s</pre>' % ('\n'.join(tb)) if tb else ''
- return self.failure_html % (message, tb_html)
- def _shutdown_cherrypy(self):
- """ Shutdown cherrypy in one second, if it's running """
- if cherrypy.engine.state == cherrypy.engine.states.STARTED:
- threading.Timer(1, cherrypy.engine.exit).start()
- def get_weight(key, value):
- authd_client = Fitbit(client_id, client_secret, access_token=key, refresh_token=value, system='en_AU')
- base = datetime.today()
- date_list = [base - timedelta(days=x) for x in range(0, 20)]
- for date in date_list:
- try:
- date = date.strftime('%Y-%m-%d')
- return_dict = authd_client.get_bodyweight(user_id='-', base_date=date)
- for x in return_dict['weight']:
- weight = float(x['weight'])
- if weight > 0:
- break
- except:
- continue
- return weight
- def update_weight(username, passwd, weight):
- #headless firefox
- options = Options()
- options.headless = True
- driver = webdriver.Firefox(options=options)
- #load page
- driver.get('https://www.trainerroad.com/login?ReturnUrl=%2fprofile%2frider-information')
- #login username
- user_input = driver.find_element_by_xpath('//*[@id="Username"]')
- user_input.send_keys(username)
- #login password
- pw_input = driver.find_element_by_xpath('//*[@id="Password"]')
- pw_input.send_keys(passwd)
- #click login button
- driver.find_element_by_xpath('/html/body/div/div[1]/div[2]/div/div[2]/form/button').click()
- #update weight
- weight_input = driver.find_element_by_xpath('//*[@id="Weight"]')
- weight_input.clear()
- weight_input.send_keys(weight)
- #click update button
- driver.find_element_by_xpath('//*[@id="UpdateInformationId"]').click()
- #close driver
- driver.quit()
- if __name__ == '__main__':
- server = OAuth2Server(client_id, client_secret)
- server.browser_authorize()
- profile = server.fitbit.user_profile_get()
- for idx, (key, value) in enumerate(server.fitbit.client.session.token.items(), start=0):
- if idx == 0:
- acccess = value
- elif idx == 2:
- refresh = value
- #get weight details from fitbit
- weight = str(get_weight(acccess, refresh))
- #log weight in tr
- update_weight(tr_username, tr_passwd, weight)
Add Comment
Please, Sign In to add comment