-
Notifications
You must be signed in to change notification settings - Fork 1
/
nike.py
85 lines (66 loc) · 2.48 KB
/
nike.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
import os
import json, httplib, ssl, urllib2, subprocess
import datetime
import sys
baseurl = "https://api.nike.com/v1/me/sport/activities/"
# ------------------------------------------------------------------------
def get_access_token():
""" Fetch access token via curl. Unfortunately urrlib and requests don't do sslv3 in this version """
cmd = "curl 'https://developer.nike.com/services/login' --data-urlencode username='%s' --data-urlencode password='%s'"
cmd = cmd % (os.environ['Nike_user'], os.environ['Nike_pass'])
str = subprocess.check_output(cmd, shell=True)
js = json.loads(str)
return js['access_token']
# Store globally
accessToken = get_access_token()
# ------------------------------------------------------------------------
def jsonFromUrl(url):
req = urllib2.Request(url)
req.add_header("appid", "fuelband")
req.add_header("Accept", "application/json")
try:
handle = urllib2.urlopen(req)
except IOError, e:
print "Wrong token or other connectivity problems (e.g. missing gps data)!"
print e
return 0
js = json.load(handle)
return js
# Converts activityId strings to integers
# ------------------------------------------------------------------------
def listNikeRuns(max=2, count=2):
print "Retrieving list of runs on nike+ server..."
ids = []
for i in range(0, max/count):
offset = i*count + 1
print "Downloading ids " + str(offset) + " to " + str(offset + count - 1)
url = baseurl + "RUNNING?access_token=" + accessToken + "&count=" + str(count) + "&offset=" + str(offset)
js = jsonFromUrl(url)
idBatch = [str(act['activityId']) for act in js['data']]
#idBatch = [act['activityId'] for act in js['data']]
ids.extend(idBatch)
if(len(idBatch) < count):
break
return ids
# Assumes runId is an integer.
# Returns a dictionary with run data that can be inserted into mongodb.
# ------------------------------------------------------------------------
def getNikeRun(runId):
# Retrieve gps data
print "Retrieving run " + str(runId) + " from nike server..."
url = baseurl + str(runId) + "/gps?access_token=" + accessToken
jsGps = jsonFromUrl(url)
if jsGps:
run = {}
run["nid"] = str(runId)
run["gps"] = jsGps["waypoints"]
# Retrieve meta data
url = baseurl + str(runId) + "?access_token=" + accessToken
jsMeta = jsonFromUrl(url)
startTimeStr = jsMeta["startTime"]
startDateTime = datetime.datetime.strptime(startTimeStr, "%Y-%m-%dT%H:%M:%SZ")
run["date"] = startDateTime
return run
else:
print "Skipping run " + str(runId)
return 0