Skip to content

Commit 6c33409

Browse files
Refactor: redesign the authorization and authentication workflow
1 parent 537b2f9 commit 6c33409

19 files changed

+280
-753
lines changed

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ __pycache__/
33
.idea/
44
.vscode/
55
configfile/
6-
logfile/
6+
logfile/

CHANGELOG.md

-14
This file was deleted.

Pipfile

-21
This file was deleted.

Pipfile.lock

-625
This file was deleted.

Strava-Tool.bat

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@echo off
2+
cmd /k "cd /d G:\My Drive\sourcecode\pythonscripts\Strava-Tool\src & C:\Users\USER\miniconda3\etc\profile.d\conda.sh & conda activate Strava-Tool & python StravaUploadTool_Main.py"
3+
pause

StravaTool.bat

-3
This file was deleted.

credentials/config.yaml

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
STRAVA_CLIENT_ID: '44973'
2+
STRAVA_CLIENT_SECRET: '2ed9b35113cc71c7b53460dedae05ef2b142133d'
3+
LINE_CHANNEL_ACCESS_TOKEN: 'z24FeCXZX2E3bx/BfeGxRttiRMwwkutV1+Q4Sr6w8UInBLjCpmcVNmewMDLLAahezZNJQD73ogwgB9VEmVndAKNl8fzXFyRSLGj3gMubocMVbCnq8MGgM4VMnQ5Zd4hUHkf/io0YZdReOvyALa3RAwdB04t89/1O/w1cDnyilFU='
4+
LINE_CHANNEL_SECRET: '5796fa888d9fd7b505ac780ecf27c4ae'
5+
ZWIFT_ACTIVITY_DIR: 'C:\Users\USER\Documents\Zwift\Activities'
6+
GMAIL_USER_ID: 'huaming.huang.tw@gmail.com'
7+
GMAIL_PASSWORD: 'eomzmbjezezpcsnv'

credentials/tokens.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
STRAVA_ACCESS_TOKEN = 27d6b726341a906154e99e884e8d1339702a6bba
2+
STRAVA_REFRESH_TOKEN = 94f06d238645a184bdc3a5283d9badeb8d2e9b0b
3+
STRAVA_TOKEN_EXPIRY_TIME = 1664725248

environment.yaml

284 Bytes
Binary file not shown.

myfile.csv

-31
This file was deleted.

requirements.txt

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Flask
2+
line-bot-sdk
3+
pyyaml
4+
stravalib
5+
requests
6+
pandas
7+
seaborn
8+
matplotlib
9+
selenium
10+
pyautogui
11+
pyperclip
12+
alive-progress
13+
gunicorn
14+
psycopg2
15+

src/StravaAnalysisTool_Kernel.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def get_Latest_Activity_Data(access_token: str, numberOfActivities: str) -> list
2424
header = {'Authorization': 'Bearer ' + access_token}
2525
param = {'per_page': numberOfActivities, 'page': 1}
2626
r = requests.get(activites_url, headers=header, params=param)
27-
except requests.RequestException:
27+
except requests.exceptions.RequestException:
2828
return None
2929

3030
my_dataset = r.json()
@@ -49,7 +49,7 @@ def get_Timeinterval_Activity_Data(access_token: str, before: str, after: str) -
4949
header = {'Authorization': 'Bearer ' + access_token}
5050
param = {'before': before, 'after': after, 'per_page': per_page, 'page': page_id}
5151
r = requests.get(activites_url, headers=header, params=param)
52-
except requests.RequestException:
52+
except requests.exceptions.RequestException:
5353
return None
5454

5555
dataset = r.json()
@@ -78,7 +78,7 @@ def get_All_Activity_Data(access_token: str) -> list:
7878
header = {'Authorization': 'Bearer ' + access_token}
7979
param = {'per_page': per_page, 'page': page_id}
8080
r = requests.get(activites_url, headers=header, params=param)
81-
except requests.RequestException:
81+
except requests.exceptions.RequestException:
8282
return None
8383

8484
dataset = r.json()

src/StravaAnalysisTool_Main.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@
55
# ----------------------------------------------------------------------------------------------------------------------
66
#
77
# Step by step:
8-
# 1) Get authorization code from authorization page. This is a one-time, manual step.
8+
# (1) Get authorization code from authorization page. This is a one-time, manual step.
99
# Paste the below code in a browser, hit enter then grab the "code" part from the resulting url.
1010
#
1111
# https://www.strava.com/oauth/authorize?client_id=your_client_id&redirect_uri=http://localhost&response_type=code&scope=activity:read_all,activity:write
1212
#
13-
# 2) Make a POST request to Strava: exchange authorization code for access token & refresh token (This also only needs to be done once)
13+
# (2) Make a POST request to Strava: exchange authorization code for access token & refresh token (This also only needs to be done once)
1414
#
1515
# https://www.strava.com/oauth/token?client_id=your_client_id&client_secret=your_client_secret&code=your_code_from_previous_step&grant_type=authorization_code
1616
#
17-
# 3) View your activities using the access token just received from 2)
17+
# (3) View your activities using the access token just received from (2)
1818
#
1919
# https://www.strava.com/api/v3/athlete/activities?access_token=access_token_from_previous_step
2020
#
21-
# 4) Use refresh token to get new access tokens (i.e., getNewAccessTokens())
21+
# (4) Use refresh token to get new access tokens
2222
#
2323
# https://www.strava.com/oauth/token?client_id=your_client_id&client_secret=your_client_secret&refresh_token=your_refresh_token_from_previous_step&grant_type=refresh_token
2424
#

src/StravaUploadTool_Kernel.py

+19-13
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from authentication import *
22
from file_manipulation import *
3-
from alive_progress import alive_bar
4-
import requests, urllib3
5-
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6-
import sys, os, subprocess, glob, time, datetime
73
from typing import Any, Tuple
4+
from alive_progress import alive_bar
5+
import requests
6+
import sys, os, subprocess, glob
7+
import time, datetime
88
import imaplib, email
99
import re
1010

@@ -55,21 +55,22 @@ def upload_Fit_Activity_Files(access_token: str):
5555
os.chdir(os.path.join(ZWIFT_ACTIVITY_DIR, "FixedActivities"))
5656
fitfile_list = glob.glob("*.fit")
5757

58-
print("Start uploading activity files...\n")
58+
print("\nStart uploading activity files...\n")
5959

6060
with alive_bar(len(fitfile_list), title='Uploading FIT activity files', bar="blocks") as bar:
6161
for fitfile in fitfile_list:
6262
with open(fitfile, 'rb') as fit_file:
6363
try:
6464
uploads_url = "https://www.strava.com/api/v3/uploads"
65-
payload = {'client_id': CLIENT_ID, 'data_type': 'fit', 'trainer': 'Elite Turbo Muin Smart B+'}
65+
payload = { 'client_id': STRAVA_CLIENT_ID,
66+
'data_type': 'fit' }
6667
header = {'Authorization': 'Bearer ' + access_token}
6768
f = {'file': fit_file}
6869
r = requests.post(uploads_url,
6970
data=payload,
7071
headers=header,
7172
files=f)
72-
except requests.RequestException:
73+
except requests.exceptions.RequestException:
7374
return None
7475

7576
print("Uploading " + fitfile + "...")
@@ -92,10 +93,13 @@ def upload_Fit_Activity_Files(access_token: str):
9293
if (isError) or (activity_id is not None):
9394
fit_file.close()
9495
move_To_Uploaded_Or_Malformed_Activities_Folder(fitfile)
96+
97+
if (activity_id is not None):
98+
print("Activity ID:", activity_id)
9599

96100
# update progress bar
97101
bar()
98-
102+
99103
break
100104
print("")
101105

@@ -105,7 +109,7 @@ def check_Upload_Status(access_token: str, filename: str, upload_ID: str) -> Tup
105109
uploads_url = "https://www.strava.com/api/v3/uploads/" + upload_ID
106110
header = {'Authorization': 'Bearer ' + access_token}
107111
r = requests.get(uploads_url, headers=header)
108-
except requests.RequestException:
112+
except requests.exceptions.RequestException:
109113
return None
110114

111115
try:
@@ -116,20 +120,22 @@ def check_Upload_Status(access_token: str, filename: str, upload_ID: str) -> Tup
116120
return None
117121

118122
if (error_msg is None) and (activity_id is None): # Possibility 1: Your activity is still being processed.
119-
print(status + '.. ' + filename)
123+
print(status + '.. ')
120124
return (False, activity_id)
121125
elif (error_msg): # Possibility 2: There was an error processing your activity. (check for malformed data and duplicates)
122-
print(status + '.. ' + filename)
126+
print(status + '.. ')
123127
print("Reason: " + error_msg + '\n')
124128
if findWholeWord('malformed')(error_msg):
125129
print("Please check this file in the 'UploadedOrMalformedActivities' folder!\n")
126130
return (True, activity_id)
127-
else: # Possibility 3: Your activity is ready.
128-
print(status + ' (' + filename + ')' + '\n')
131+
else: # Possibility 3: Your activity is ready.
132+
print(status + '\n')
129133
return (False, activity_id)
130134

131135

136+
# ----------------
132137
# Helper functions
138+
# ----------------
133139
def wait(poll_interval: float):
134140
time.sleep(poll_interval)
135141

src/StravaUploadTool_Main.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,20 @@
66
# ----------------------------------------------------------------------------------------------------------------------
77
#
88
# Step by step:
9-
# 1) Get authorization code from authorization page. This is a one-time, manual step.
9+
# (1) Get authorization code from authorization page. This is a one-time, manual step.
1010
# Paste the below code in a browser, hit enter then grab the "code" part from the resulting url.
1111
#
1212
# https://www.strava.com/oauth/authorize?client_id=your_client_id&redirect_uri=http://localhost&response_type=code&scope=activity:read_all,activity:write
1313
#
14-
# 2) Make a POST request to Strava: exchange authorization code for access token & refresh token (This also only needs to be done once)
14+
# (2) Make a POST request to Strava: exchange authorization code for access token & refresh token (This also only needs to be done once)
1515
#
1616
# https://www.strava.com/oauth/token?client_id=your_client_id&client_secret=your_client_secret&code=your_code_from_previous_step&grant_type=authorization_code
1717
#
18-
# 3) View your activities using the access token just received from 2)
18+
# (3) View your activities using the access token just received from (2)
1919
#
2020
# https://www.strava.com/api/v3/athlete/activities?access_token=access_token_from_previous_step
2121
#
22-
# 4) Use refresh token to get new access tokens (i.e., getNewAccessTokens())
22+
# (4) Use refresh token to get new access tokens
2323
#
2424
# https://www.strava.com/oauth/token?client_id=your_client_id&client_secret=your_client_secret&refresh_token=your_refresh_token_from_previous_step&grant_type=refresh_token
2525
#
@@ -43,7 +43,9 @@ def main():
4343
""")
4444
preprocessing()
4545
fix_Fit_Activity_Files()
46-
upload_Fit_Activity_Files(get_New_Access_Tokens())
46+
TOKEN_FILE_PATH = Path('../credentials/tokens.txt')
47+
access_token = get_access_token(TOKEN_FILE_PATH)
48+
upload_Fit_Activity_Files(access_token)
4749

4850

4951
if __name__ == "__main__":

0 commit comments

Comments
 (0)