-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.py
199 lines (168 loc) · 8.43 KB
/
fetch.py
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
import json
from urllib.parse import urlparse
import click
from flask import Blueprint, current_app, jsonify, render_template, redirect, url_for
from requests import get, post, put
from requests.auth import AuthBase, HTTPBasicAuth
fetch = Blueprint('fetch', __name__, cli_group=None)
class BearerAuth(AuthBase):
token = None
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['authorization'] = 'Bearer ' + self.token
r.headers['accept'] = 'application/json'
r.headers['content-type'] = 'application/json; charset=utf-8'
return r
@fetch.route("/notifications")
def get_notifications():
r = get(current_app.config['BASE_URL'] + '/v3/notifications', auth=HTTPBasicAuth(current_app.config['CLIENT_ID'], current_app.config['CLIENT_SECRET']))
if r.status_code == 200:
return jsonify(r.json())
elif r.status_code == 204:
current_app.logger.info('No new data available')
return redirect(url_for('fetch.get_user_info', user_id=current_app.config['USER_ID']))
@fetch.cli.command('fetch')
@click.option('-t', '--token', envvar='ACCESS_TOKEN', help='OAuth2 Access Token.')
@click.option('-u', '--user-id', envvar='USER_ID', help='Polar user id.')
def fetch_command(token, user_id):
get_activities_list(token=token, user_id=user_id)
@fetch.route("/users/<int:user_id>/activity-transactions")
def get_activities_list(token=None, user_id=None):
"""
:param token: OAuth2 access token
:param user_id: Polar user id
"""
if not token:
token = current_app.config['ACCESS_TOKEN']
current_app.logger.debug("Starting an activity transaction")
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/activity-transactions'
r = post(url=url, auth=BearerAuth(token=token))
if r.status_code == 201:
j = r.json()
get_activities(token=token, user_id=user_id, transaction_id=j[u'transaction-id'])
return redirect(url_for('fetch.get_notifications'))
if r.status_code == 204:
current_app.logger.info('No new data available')
return redirect(url_for('fetch.get_notifications'))
def get_activities(token=None, user_id=None, transaction_id=None):
""" Fetches all of available activity summaries
Makes one call to the API, fetching a list of all available daily summaries
then calls get_activity_summary() to effectively download the data.
:param token: OAuth2 access token
:param user_id: Polar user id
:param transaction_id: The initiated transaction
"""
if not token:
token = current_app.config['ACCESS_TOKEN']
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/activity-transactions/' + str(transaction_id)
r = get(url=url, auth=BearerAuth(token=token))
if r.status_code == 200:
j = r.json()
for i in j[u'activity-log']:
activity_id = i.split('/')[-1]
r = get(current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/activity-transactions/' + str(transaction_id) + "/activities/" + str(activity_id), auth=BearerAuth(token=token))
if r.status_code == 200:
j = r.json()
current_app.logger.info('Fetching activity summary of ' + j['date'])
with open('daily-summary-' + str(j['id']) + '.json', 'w') as f:
json.dump(j, f, indent=2)
current_app.logger.debug("Closing an activity transaction")
r = put(url=url, auth=BearerAuth(token=token))
if r.status_code == 200:
current_app.logger.info("All activity information was successfully downloaded")
elif r.status_code == 404:
current_app.logger.error("Activity not found")
return render_template('404.html')
@fetch.route("/users/<int:user_id>/exercise-transactions")
def get_exercise_list(token=None, user_id=None):
"""
:param token: OAuth2 access token
:param user_id: Polar user id
"""
if not token:
token = current_app.config['ACCESS_TOKEN']
current_app.logger.debug("Starting an exercise transaction")
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/exercise-transactions'
r = post(url=url, auth=BearerAuth(token=token))
if r.status_code == 201:
j = r.json()
get_exercises(token=token, user_id=user_id, transaction_id=j[u'transaction-id'])
elif r.status_code == 204:
current_app.logger.info('No new data available')
return render_template('204.html')
@fetch.route("/users/<int:user_id>/exercise-transactions/<int:transaction_id>")
def get_exercises(token=None, user_id=None, transaction_id=None):
if not token:
token = current_app.config['ACCESS_TOKEN']
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/exercise-transactions/' + str(transaction_id)
r = get(url=url, auth=BearerAuth(token=token))
if r.status_code == 200:
j = r.json()
for i in j[u'exercises']:
exercise_id = urlparse(i)[2].rpartition('/')[2]
s = get(url=i, auth=BearerAuth(token=token))
if s.status_code == 200:
k = s.json()
current_app.logger.info('Fetching exercise from ' + exercise_id)
with open('exercise-' + exercise_id + '.json', 'a') as f:
json.dump(k, f, indent=2)
s = get(url=i + '/heart-rate-zones', auth=BearerAuth(token=token))
if s.status_code == 200:
k = s.json()
current_app.logger.info('Fetching heart rate zones from exercise ' + exercise_id)
with open('exercise-' + exercise_id + '.json', 'a') as f:
json.dump(k, f, indent=2)
r = put(url=url, auth=BearerAuth(token=token))
if r.status_code == 200:
current_app.logger.info('All exercise information was successfully downloaded')
return redirect(url_for('fetch.get_notifications'))
elif r.status_code == 204:
current_app.logger.info('No new data available')
return render_template('204.html')
@fetch.route("/users/<int:user_id>/physical-information-transactions/<int:transaction_id>")
def list_user_physical_info(user_id, transaction_id):
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/physical-information-transactions/' + str(transaction_id)
r = get(url=url, auth=BearerAuth(token=current_app.config['ACCESS_TOKEN']))
if r.status_code == 200:
j = r.json()
for i in j[u'physical-informations']:
s = get(url=i, auth=BearerAuth(token=current_app.config['ACCESS_TOKEN']))
k = s.json()
current_app.logger.info('Fetching physical information of ' + k['created'])
with open('physical-information-' + str(k['id']) + '.json', 'w') as f:
json.dump(k, f, indent=2)
r = put(url=url, auth=BearerAuth(token=current_app.config['ACCESS_TOKEN']))
if r.status_code == 200:
current_app.logger.info('All physical information was successfully downloaded')
return redirect(url_for('fetch.get_notifications'))
elif r.status_code == 204:
current_app.logger.info('No new data available')
return render_template('204.html')
elif r.status_code == 404:
return render_template('404.html')
@fetch.route("/users/<int:user_id>/physical-information-transactions")
def get_user_physical_info(user_id):
""" Request physical information on the user
:param user_id: Polar user id
:return: User information in a JSON format
"""
url = current_app.config['BASE_URL'] + '/v3/users/' + str(user_id) + '/physical-information-transactions'
r = post(url=url, auth=BearerAuth(token=current_app.config['ACCESS_TOKEN']))
if r.status_code == 201:
j = r.json()
return redirect(url_for('fetch.list_user_physical_info', user_id=user_id, transaction_id=j['transaction-id']))
elif r.status_code == 204:
current_app.logger.info('No new data available')
return render_template('204.html')
elif r.status_code == 404:
return render_template('404.html')
@fetch.route("/users/<int:user_id>")
def get_user_info(user_id):
""" Request profile information on the user
:param user_id: Polar user id
:return: User information in a JSON format
"""
r = get(current_app.config['BASE_URL'] + '/v3/users/' + str(user_id), auth=BearerAuth(token=current_app.config['ACCESS_TOKEN']))
if r.status_code == 200:
return jsonify(r.json())