forked from magnific0/nokia-weight-sync
-
Notifications
You must be signed in to change notification settings - Fork 1
/
smashrun.py
279 lines (219 loc) · 8.87 KB
/
smashrun.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
""" This module contains main user-facing Smashrun interface.
"""
from __future__ import division
import json
import datetime
from itertools import islice
from requests_oauthlib import OAuth2Session
auth_url = "https://secure.smashrun.com/oauth2/authenticate"
token_url = "https://secure.smashrun.com/oauth2/token"
class Smashrun(object):
def __init__(self, client_id=None, client_secret=None, client=None,
auto_refresh_url=None, auto_refresh_kwargs=None, scope=None,
redirect_uri=None, token=None, state=None, token_updater=None,
**kwargs):
self.session = OAuth2Session(
client_id=client_id,
client=client,
auto_refresh_url=token_url,
scope=scope,
redirect_uri=redirect_uri,
token=token,
state=state,
token_updater=token_updater,
**kwargs
)
self.client_secret = client_secret
self.base_url = "https://api.smashrun.com/v1"
@property
def client_id(self):
return self.session.client_id
def get_auth_url(self):
return self.session.authorization_url(
auth_url, client_secret=self.client_secret)
def fetch_token(self, **kwargs):
"""Fetch a new token using the supplied code.
:param str code: A previously obtained auth code.
"""
if 'client_secret' not in kwargs:
kwargs.update(client_secret=self.client_secret)
return self.session.fetch_token(token_url, **kwargs)
def refresh_token(self, **kwargs):
"""Refresh the authentication token.
:param str refresh_token: The refresh token to use. May be empty if
retrieved with ``fetch_token``.
"""
if 'client_secret' not in kwargs:
kwargs.update(client_secret=self.client_secret)
if 'client_id' not in kwargs:
kwargs.update(client_id=self.client_id)
return self.session.refresh_token(token_url, **kwargs)
def get_activity(self, id_num):
"""Return the activity with the given id.
Note that this contains more detailed information than returned
by `get_activities`.
"""
url = self._build_url('my', 'activities', id_num)
return self._json(url)
def get_activities(self, count=10, since=None, style='summary',
limit=None):
"""Iterate over all activities, from newest to oldest.
:param count: The number of results to retrieve per page.
:param since: Return only activities since this date. Can be either
a timestamp or a datetime object.
:param style: The type of records to return. May be one of
'summary', 'briefs', 'ids', or 'extended'.
:param limit: The maximum number of activities to return for the given
query.
"""
params = {}
if since:
params.update(fromDate=to_timestamp(since))
parts = ['my', 'activities', 'search']
if style != 'summary':
parts.append(style)
url = self._build_url(*parts)
# TODO: return an Activity (or ActivitySummary?) class that can do
# things like convert date and time fields to proper datetime objects
return islice(self._iter(url, count, **params), limit)
def get_badges(self):
"""Return all badges the user has earned."""
url = self._build_url('my', 'badges')
return self._json(url)
def get_notables(self, id_num):
"""Return the notables of the activity with the given id.
"""
url = self._build_url('my', 'activities', id_num, 'notables')
return self._json(url)
def get_polyline(self, id_num, style='google'):
"""Return the polyline of the activity with the given id.
:param style: The type of polyline to return. May be one of
'google', 'svg', or 'geojson'.
"""
parts = ['my', 'activities', id_num, 'polyline']
if style != 'google':
parts.append(style)
url = self._build_url(*parts)
return self._json(url)
def get_splits(self, id_num, unit='mi'):
"""Return the splits of the activity with the given id.
:param unit: The unit to use for splits. May be one of
'mi' or 'km'.
"""
url = self._build_url('my', 'activities', id_num, 'splits', unit)
return self._json(url)
def get_stats(self, year=None, month=None):
"""Return stats for the given year and month."""
parts = ['my', 'stats']
if month and not year:
raise ValueError("month cannot be specified without year")
if year:
parts.append(year)
if month:
parts.append(year)
url = self._build_url(*parts)
return self._json(url)
def get_current_weight(self):
"""Return the most recent weight recording."""
url = self._build_url('my', 'body', 'weight', 'latest')
return self._json(url)
def get_weight_history(self):
"""Return all weight recordings."""
url = self._build_url('my', 'body', 'weight')
return self._json(url)
def get_userinfo(self):
"""Return information about the current user."""
url = self._build_url('my', 'userinfo')
return self._json(url)
def create_weight(self, weight, date=None):
"""Submit a new weight record.
:param weight: The weight, in kilograms.
:param date: The date the weight was recorded. If not
specified, the current date will be used.
"""
url = self._build_url('my', 'body', 'weight')
data = {'weightInKilograms': weight}
if date:
if isinstance(date,str):
data.update(date=date)
else:
if not date.is_aware():
raise ValueError("provided date is not timezone aware")
data.update(date=date.isoformat())
headers = {'Content-Type': 'application/json; charset=utf8'}
r = self.session.post(url, data=json.dumps(data), headers=headers)
r.raise_for_status()
return r
def create_activity(self, data):
"""Create a new activity (run).
:param data: The data representing the activity you want to upload.
May be either JSON, GPX, or TCX.
"""
url = self._build_url('my', 'activities')
if isinstance(data, dict):
data = json.dumps(data)
r = self.session.post(url, data=data)
r.raise_for_status()
return r
def update_activity(self, id_num, data):
"""Update an existing activity (run).
:param id_num: The activity ID to update
:param data: The data representing the activity you want to upload.
May be either JSON, GPX, or TCX.
"""
url = self._build_url('my', 'activities')
if isinstance(data, dict):
data = json.dumps(data)
r = self.session.put(url, data=data)
r.raise_for_status()
return r
def delete_activity(self, id_num):
"""Delete an activity (run).
:param id_num: The activity ID to delete
"""
url = self._build_url('my', 'activities', id_num)
r = self.session.delete(url)
r.raise_for_status()
return r
def _iter(self, url, count, cls=None, **kwargs):
page = 0
while True:
kwargs.update(count=count, page=page)
r = self.session.get(url, params=kwargs)
r.raise_for_status()
data = r.json()
if not data:
break
for d in data:
if cls:
yield cls(d)
else:
yield d
page += 1
def _build_url(self, *args, **kwargs):
parts = [kwargs.get('base_url') or self.base_url]
parts.extend(args)
parts = [str(p) for p in parts]
return "/".join(parts)
def _json(self, url):
response = self.session.get(url)
response.raise_for_status()
return response.json()
def to_timestamp(dt):
"""Convert a datetime object to a unix timestamp.
Note that unlike a typical unix timestamp, this is seconds since 1970
*local time*, not UTC.
If the passed in object is already a timestamp, then that value is
simply returned unmodified.
"""
if isinstance(dt, int):
return dt
return int(total_seconds(dt.replace(tzinfo=None) -
datetime.datetime(1970, 1, 1)))
def total_seconds(delta):
if hasattr(delta, 'total_seconds'):
return delta.total_seconds()
return (delta.microseconds +
(delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6
def is_aware(d):
return d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None