-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.py
99 lines (86 loc) · 2.87 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
import requests
import json
import time
import os
def init():
global tokens
global credentials
global localActivities
global config
config = json.load(open("config.json"))
tokens = json.load(open(config["tokenFile"]))
credentials = json.load(open(config["credentialsFile"]))
localActivities = []
if os.path.isfile(config["activitiesFile"]):
localActivities = json.load(open(config["activitiesFile"]))
def refreshTokens():
body = {
"client_id": credentials.get("client_id"),
"client_secret": credentials.get("client_secret"),
"grant_type": "refresh_token",
"refresh_token": tokens.get("refresh_token")
}
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
resp = requests.post("https://www.strava.com/oauth/token", data=json.dumps(body), headers=headers)
new_tokens = json.loads(resp.text)
return new_tokens
def getAccessToken():
global tokens
if tokens.get("expires_at") < (time.time()):
# REFRESH TOKENS
print("Token Expired. Requesting new Token.")
tokenResponse = refreshTokens()
if("access_token" not in tokenResponse):
print("ERROR: Could not refresh tokens")
return None
print("New Token: " + tokenResponse["access_token"])
json.dump(tokenResponse, open(config["tokenFile"], mode="w"))
tokens = tokenResponse
return tokens["access_token"]
else:
print("Using Token: " + tokens["access_token"])
return tokens["access_token"]
def fetchActivities(page, per_page=100):
accessToken = getAccessToken()
headers = {
'accept': 'application/json',
'authorization': "Bearer " + accessToken
}
resp = requests.get("https://www.strava.com/api/v3/athlete/activities?page="+str(page)+"&per_page="+str(per_page), headers=headers)
fetched = json.loads(resp.text)
return fetched
def updateLocalActivities():
init()
lastLocalID = 0
if len(localActivities) > 0:
lastLocalID = localActivities[0]["id"]
activitiesToAdd = []
page = 1
finished = False
while not finished:
batch = fetchActivities(page)
if len(batch) <= 0:
break
for b in batch:
if b["id"] == lastLocalID:
finished = True
break
else:
activitiesToAdd.insert(0,b)
page = page + 1
print("ADDING:")
for i in activitiesToAdd:
print(" -"+str(i["id"]))
localActivities.insert(0, i)
json.dump(localActivities, open(config["activitiesFile"], "w"))
print("DONE")
return localActivities
def removeLocalActivities(num):
init()
for i in range(num):
rem = localActivities.pop(0)
print(rem["id"])
json.dump(localActivities, open(config["activitiesFile"], "w"))