-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetSleep.py
More file actions
200 lines (139 loc) · 5 KB
/
GetSleep.py
File metadata and controls
200 lines (139 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import urllib2
import urllib
import sys
import json
import os
from pprint import pprint
import datetime
import csv
'''
Todo:
- Create the CSV file if its not there
- Produce errors if the values entered don't match
'''
#messages to print out
ErrorInAPI = "Error when making API call that I couldn't handle"
#Authentication codes to get this to work
OAuthTwoClientID = "lolololol"
ClientOrConsumerSecret = "ok"
#Declares variables so that we can add them later
AccessToken = ""
RefreshToken = ""
def writeToCSV(startSleep, endSleep):
'''
Takes datetime objects for both when sleep started, and when
it ended, and then appends it to a CSV file in the directory
of the python file
'''
#Converts the text arguments into dateTime objects
startObject = datetime.datetime.strptime(startSleep, "%Y-%m-%dT%H:%M:%S.000")
endObject = datetime.datetime.strptime(endSleep, "%Y-%m-%dT%H:%M:%S.000")
#Strips the dateTime object's date values only, and converts them to strings
startDate = datetime.datetime.strftime(startObject, '%d/%m/%Y')
endDate = datetime.datetime.strftime(endObject, '%d/%m/%Y')
#Strips the dateTime obejct's time values only, and changes them to strings
startTime = datetime.datetime.strftime(startObject, '%I:%M %p')
endTime = datetime.datetime.strftime(endObject, '%I:%M %p')
#Opens a csv files in the directory and the values to it
with open(r'dates.csv', 'a') as fd:
a = csv.writer(fd);
data = ['Sleep', startDate, startTime, endDate,endTime];
a.writerow(data);
def GetTokens():
'''
Gets the authorization tokens from a tokens.txt file
in the same directory as the actual file
returns the access and refresh tokens
'''
#Open the file
file = open('tokens.txt','r')
#Read first two lines - first is the access token, second is the refresh token
AccToken = file.readline()
RefToken = file.readline()
#Close the file
file.close()
#See if the strings have newline characters on the end. If so, strip them
if (AccToken.find("\n") > 0):
AccToken = AccToken[:-1]
if (RefToken.find("\n") > 0):
RefToken = RefToken[:-1]
#Return values
return AccToken, RefToken
def MakeAPICall(InURL,AccToken,RefToken):
#Start the request
req = urllib2.Request(InURL)
#Add the access token in the header
req.add_header('Authorization', 'Bearer ' + AccToken)
#Fire off the request
try:
#Do the request
response = urllib2.urlopen(req)
#Read the response
FullResponse = response.read()
#Return values
return True, FullResponse
except urllib2.URLError as e:
print "Got this HTTP error: " + str(e.code)
HTTPErrorMessage = e.read()
print "This was in the HTTP error message: " + HTTPErrorMessage
#See what the error was
if (e.code == 401) and (HTTPErrorMessage.find("Access token invalid or expired") > 0):
print "Need a new token buddy"
#Return that this didn't work, allowing the calling function to handle it
return False, ErrorInAPI
def FindWakeTime(start, inBed):
'''
Takes the values of sleep start time, and minutes in bed
as text values, converts them into datetime objects,
adds the minutes value to the starttime value
and then converts that value into a string
and returns it
'''
dateobject = datetime.datetime.strptime(start, "%Y-%m-%dT%H:%M:%S.000")
end = dateobject + datetime.timedelta(minutes = int(inBed))
endTime = datetime.datetime.strftime(end, "%Y-%m-%dT%H:%M:%S.000")
return endTime
def checkIfFileExists(fileName):
'''
Uses the os.path to find out if fileName exists
'''
try:
check = os.stat(fileName)
except os.error:
return False
return True
tokenCheck = checkIfFileExists('tokens.txt')
if not tokenCheck:
sys.exit('No file for tokens exists')
#Asks the user for input on what dates to get sleeping data for
print "Enter Beginning date YYYY-MM-DD"
firstDateInput = raw_input()
print "Enter Final date YYYY-MM-DD"
lastDateInput = raw_input()
#Converts the text values into dateTime objects
firstDate = datetime.datetime.strptime(firstDateInput, '%Y-%m-%d')
lastDate = datetime.datetime.strptime(lastDateInput, '%Y-%m-%d')
#finds the number of days needed to increment later on
datesToGet = (lastDate - firstDate).days
#Get the tokens
AccessToken, RefreshToken = GetTokens()
while firstDate < lastDate:
currentDate = datetime.datetime.strftime(firstDate, '%Y-%m-%d')
FitbitURL = "https://api.fitbit.com/1/user/-/sleep/date/%s.json" % (currentDate)
print "Getting values for " + currentDate + " and fitbit url is " + FitbitURL
APICallOK, APIResponse = MakeAPICall(FitbitURL, AccessToken, RefreshToken)
if APICallOK:
j = json.loads(APIResponse)
x = j['summary']['totalSleepRecords']
if (x != 0):
starttime = j['sleep'][0]['startTime']
timeinbed = j['sleep'][0]['timeInBed']
end = FindWakeTime(starttime, timeinbed)
print "You went to sleep at " + starttime + " and woke up at " + end
writeToCSV(starttime, end)
else:
print "No data for that day, moving on"
print '\n\n'
firstDate = firstDate + datetime.timedelta(days = 1)
else:
print ErrorInAPI