Ejemplo n.º 1
0
def MakeAPICall(InURL, AccToken, RefToken):
    #Start forming the request
    print_json('status', 'Making API call')
    req = Request(InURL)

    #Add the access token in the header
    req.add_header('Authorization', 'Bearer %s' % AccToken)

    #Fire off the request
    try:
        response = urlopen(req)
        #Read the response
        FullResponse = response.read()

        #Return values for successful request, tokens good, and the data recieved
        print_json('status', 'API call okay')
        return True, True, Authorised
    #Catch errors, e.g. A 401 error that signifies the need for a new access token
    except URLError as err:
        HTTPErrorMessage = err.read()
        print_json('error', err.code, json.loads(HTTPErrorMessage))
        #See what the error was
        if (err.code == 401) and (HTTPErrorMessage.find("expired_token") > 0):
            GetNewAccessToken(RefToken)
            print_json('status', 'Can run again')
            return False, True, TokenRefreshedOK
        if (err.code == 401) and (HTTPErrorMessage.find("invalid_token") > 0):
            return False, False, Reauthorise
        #Return that this didn't work, allowing the calling function to handle it
        print_json('status', 'API call failed')
        return False, False, ErrorInAPI
Ejemplo n.º 2
0
def MakeAPICall(InURL,AccToken,RefToken):
	#Start forming the request
	print_json('status', 'Making API call')
	req = urllib2.Request(InURL)
	
	#Add the access token in the header
	req.add_header('Authorization', 'Bearer %s' %AccToken)
	
	#Fire off the request
	try:
		response = urllib2.urlopen(req)
		#Read the response
		FullResponse = response.read()
		
		#Return values for successful request, tokens good, and the data recieved
		print_json('status', 'API call okay')
		return True, True, Authorised
	#Catch errors, e.g. A 401 error that signifies the need for a new access token
	except urllib2.URLError as err:
		HTTPErrorMessage = err.read()
		print_json('error', err.code, json.loads(HTTPErrorMessage))
		#See what the error was
		if (err.code == 401) and (HTTPErrorMessage.find("expired_token") > 0):
			GetNewAccessToken(RefToken)
			print_json('status', 'Can run again')
			return False, True, TokenRefreshedOK
		if (err.code == 401) and (HTTPErrorMessage.find("invalid_token") > 0):
			return False, False, Reauthorise
		#Return that this didn't work, allowing the calling function to handle it
		print_json('status', 'API call failed')
		return False, False, ErrorInAPI
Ejemplo n.º 3
0
def MeasureApi():
    measure_params = {
        "meastype": 1,
        "category": 2,  # to protect from CSRF
        "startdate": 20180601,
        "enddate":
        20180830  # we want to get access to user info, user metrics and user activity i.e. everything
        #"offset": "xx"
    }

    url = "&".join([MeasureUrl, urllib.urlencode(measure_params)])
    print_json('status', url)
    resp = MakeAPICall(url)
    return resp
Ejemplo n.º 4
0
def GetNewAccessToken(RefToken):
    print_json('status', 'Getting a new access token')

    #Form the data payload
    BodyText = {'grant_type': 'refresh_token', 'refresh_token': RefToken}
    #URL Encode it
    BodyURLEncoded = urllib.urlencode(BodyText)
    #print "Using this as the body when getting access token >>" + BodyURLEncoded

    #Start the request
    tokenreq = urllib2.Request(TokenURL, BodyURLEncoded)

    #Add the headers, first we base64 encode the client id and client secret with a : inbetween and create the authorisation header
    tokenreq.add_header(
        'Authorization',
        'Basic ' + base64.b64encode(client_id + ":" + client_secret))
    tokenreq.add_header('Content-Type', 'application/x-www-form-urlencoded')

    #Fire off the request
    try:
        tokenresponse = urllib2.urlopen(tokenreq)

        #See what we got back. If it's this part of the code it was OK
        FullResponse = tokenresponse.read()

        #Use JSON to extract tokens
        ResponseJSON = json.loads(FullResponse)

        #Read the access token as a string
        NewAccessToken = str(ResponseJSON['access_token'])
        NewRefreshToken = str(ResponseJSON['refresh_token'])
        #print ResponseJSON['expires_at']
        #Write the access token to the ini file
        WriteTokens(NewAccessToken, NewRefreshToken)

        print_json('status', 'Tokens refreshed')
    except urllib2.URLError as err:
        print_json('error', 'Error getting new access token')
        print_json('error', err.code, json.loads(err.read()))
        sys.exit(1)
Ejemplo n.º 5
0
def GetNewAccessToken(RefToken):
	print_json('status','Getting a new access token')
	
	#Form the data payload
	BodyText = {'grant_type' : 'refresh_token',
				'refresh_token' : RefToken}
	#URL Encode it
	BodyURLEncoded = urllib.urlencode(BodyText)
	#print "Using this as the body when getting access token >>" + BodyURLEncoded
	
	#Start the request
	tokenreq = urllib2.Request(TokenURL,BodyURLEncoded)
	
	#Add the headers, first we base64 encode the client id and client secret with a : inbetween and create the authorisation header
	tokenreq.add_header('Authorization', 'Basic ' + base64.b64encode(client_id + ":" + client_secret))
	tokenreq.add_header('Content-Type', 'application/x-www-form-urlencoded')
	
	#Fire off the request
	try:
		tokenresponse = urllib2.urlopen(tokenreq)
		
		#See what we got back. If it's this part of the code it was OK
		FullResponse = tokenresponse.read()
		
		#Use JSON to extract tokens
		ResponseJSON = json.loads(FullResponse)
		
		#Read the access token as a string
		NewAccessToken = str(ResponseJSON['access_token'])
		NewRefreshToken = str(ResponseJSON['refresh_token'])
		#print ResponseJSON['expires_at']
		#Write the access token to the ini file
		WriteTokens(NewAccessToken,NewRefreshToken)
		
		print_json('status', 'Tokens refreshed')
	except urllib2.URLError as err:
		print_json('error', 'Error getting new access token')
		print_json('error', err.code, json.loads(err.read()))
		sys.exit(1)
Ejemplo n.º 6
0
	ResourceTypes = ['steps', 'floors', 'caloriesOut']

	#This is the Fitbit URL to use for the API call
	FitbitURL = "https://api.fitbit.com/1/user/-/profile.json"

	#Get credentials
	ClientID, ClientSecret = ReadCredentials()

	APICallOK = False
	while not APICallOK:
		#Get tokens
		AccessToken, RefreshToken = ReadTokens()
		#Make the API call
		APICallOK, TokensOK, APIResponse = MakeAPICall(FitbitURL, AccessToken, RefreshToken)
		
		print_json('status',APIResponse)
		if not TokensOK:
			sys.exit(1)
	
	#Create authorised client and grab step count from one day of steps
	authdClient = fitbit.Fitbit(ClientID, ClientSecret, oauth2=True, access_token=AccessToken, refresh_token=RefreshToken)
	activityList = authdClient.activities()
	try:
		activitySummary = activityList['summary'] #Use for steps, floors, calories. Adapt for distance, active minutes
		activityGoals = activityList['goals'] #Goals for steps, floors, calories, distance, active minutes
		sleepSummary = authdClient.sleep()['summary']
		heartTimeSeries = authdClient.time_series('activities/heart',period='1d')
		totalMinutesAsleep = sleepSummary['totalMinutesAsleep']
		
		#Calculate active minutes
		activeMinutes = activitySummary['fairlyActiveMinutes'] + activitySummary['veryActiveMinutes']
Ejemplo n.º 7
0
if __name__ == "__main__":
	#This is the Fitbit URL to use for the API call
    FitbitURL = "https://api.fitbit.com/1/user/-/profile.json"

	#Get credentials
    ClientID, ClientSecret = ReadCredentials()

    APICallOK = False
    while not APICallOK:
		#Get tokens
        AccessToken, RefreshToken = ReadTokens()
		#Make the API call
        APICallOK, TokensOK, APIResponse = MakeAPICall(FitbitURL, AccessToken, RefreshToken)
		
        print_json('status',APIResponse)
        if not TokensOK:
            sys.exit(1)
            
try:
    Day, Month, Year = input('Enter From Date in format(Day-Month-Year): ').split('-')
    st = datetime.date(datetime(int(Year), int(Month), int(Day)))
    print('data from date : {}'.format(st))
except Exception as e:
    st = datetime.date((datetime.now() - timedelta(days=1)))
    print('data of date : {}'.format(st))
    
try:
    Dayx, Monthx, Yearx = input('Enter To Date in format(Day-Month-Year): ').split('-')
    stx = datetime.date(datetime(int(Yearx), int(Monthx), int(Dayx)))
    if stx >= datetime.date(datetime.now()):
Ejemplo n.º 8
0
def MakeAPICall(InURL):
    access_token, refresh_token = ReadTokens()
    #Start forming the request
    api_params = {
        'access_token': access_token,
    }
    url = "&".join([InURL, urllib.urlencode(api_params)])
    print_json('status', url)
    print_json('status', 'Making API call')

    #Fire off the request
    try:
        response = urllib2.urlopen(url)
        #Read the response
        FullResponse = response.read()
        print_json('status', FullResponse)
        #Return values for successful request, tokens good, and the data recieved
        print_json('status', 'API call okay')
        return True, True, Authorised
#Catch errors, e.g. A 401 error that signifies the need for a new access token
    except urllib2.HTTPError as err:
        HTTPErrorMessage = err.read()
        print_json('error', err, json.loads(HTTPErrorMessage))
        #See what the error was
        if (err.code == 401) and (HTTPErrorMessage.find("expired_token") > 0):
            GetNewAccessToken(refresh_token)
            print_json('status', 'Can run again')
            return False, True, TokenRefreshedOK
        if (err.code == 401) and (HTTPErrorMessage.find("invalid_token") > 0):
            return False, False, Reauthorise
        #Return that this didn't work, allowing the calling function to handle it
        print_json('status', 'API call failed')
        return False, False, ErrorInAPI
Ejemplo n.º 9
0

def MeasureApi():
    measure_params = {
        "meastype": 1,
        "category": 2,  # to protect from CSRF
        "startdate": 20180601,
        "enddate":
        20180830  # we want to get access to user info, user metrics and user activity i.e. everything
        #"offset": "xx"
    }

    url = "&".join([MeasureUrl, urllib.urlencode(measure_params)])
    print_json('status', url)
    resp = MakeAPICall(url)
    return resp


########
# SLEEP #
########


def SleepApi():
    resp = MakeAPICall(SleepUrl)
    return resp


resp = MeasureApi()
print_json("response", resp)