Private
Public Access
1
0
This commit is contained in:
Sander Roosendaal
2022-02-15 08:05:12 +01:00
parent 5b3d7fcf2c
commit 8af7ac8af4
71 changed files with 19992 additions and 19476 deletions

View File

@@ -17,13 +17,13 @@ import numpy as np
from dateutil import parser
import time
import math
from math import sin,cos,atan2,sqrt
from math import sin, cos, atan2, sqrt
import urllib
import rowers.c2stuff as c2stuff
# Django
from django.http import HttpResponseRedirect, HttpResponse,JsonResponse
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
@@ -33,7 +33,7 @@ from django.contrib.auth.decorators import login_required
# from .models import Profile
from rowingdata import rowingdata
import pandas as pd
from rowers.models import Rower,Workout
from rowers.models import Rower, Workout
from rowsandall_app.settings import C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET, STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI, STRAVA_CLIENT_SECRET, SPORTTRACKS_CLIENT_SECRET, SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI
@@ -42,16 +42,17 @@ TEST_CLIENT_SECRET = "aapnootmies"
TEST_REDIRECT_URI = "http://localhost:8000/rowers/test_callback"
def custom_exception_handler(exc,message): # pragma: no cover
def custom_exception_handler(exc, message): # pragma: no cover
response = {
"errors": [
{
"code": str(exc),
"detail": message,
}
]
}
}
]
}
res = HttpResponse(message)
res.status_code = 401
@@ -59,11 +60,13 @@ def custom_exception_handler(exc,message): # pragma: no cover
return res
def do_refresh_token(refreshtoken): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
def do_refresh_token(refreshtoken): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth(
TEST_CLIENT_ID, TEST_CLIENT_SECRET)
post_data = {"grant_type": "refresh_token",
"client_secret": TEST_CLIENT_SECRET,
"client_id":TEST_CLIENT_ID,
"client_id": TEST_CLIENT_ID,
"refresh_token": refreshtoken,
}
headers = {'user-agent': 'sanderroosendaal',
@@ -84,23 +87,23 @@ def do_refresh_token(refreshtoken): # pragma: no cover
except KeyError:
refresh_token = refreshtoken
return [thetoken,expires_in,refresh_token]
return [thetoken, expires_in, refresh_token]
def get_token(code): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
def get_token(code): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth(
TEST_CLIENT_ID, TEST_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://localhost:8000/rowers/test_callback",
"client_secret": "aapnootmies",
"client_id":1,
"client_id": 1,
}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
url = "http://localhost:8000/rowers/o/token/"
response = requests.post(url,
data=json.dumps(post_data),
headers=headers)
@@ -110,10 +113,10 @@ def get_token(code): # pragma: no cover
expires_in = token_json['expires_in']
refresh_token = token_json['refresh_token']
return [thetoken, expires_in, refresh_token]
return [thetoken,expires_in,refresh_token]
def make_authorization_url(request): # pragma: no cover
def make_authorization_url(request): # pragma: no cover
# Generate a random string for the state parameter
# Save it for use later to prevent xsrf attacks
from uuid import uuid4
@@ -122,17 +125,17 @@ def make_authorization_url(request): # pragma: no cover
params = {"client_id": TEST_CLIENT_ID,
"response_type": "code",
"redirect_uri": TEST_REDIRECT_URI,
"scope":"write",
"state":state}
"scope": "write",
"state": state}
import urllib
url = "http://localhost:8000/rowers/o/authorize" +urllib.parse.urlencode(params)
url = "http://localhost:8000/rowers/o/authorize" + \
urllib.parse.urlencode(params)
return HttpResponseRedirect(url)
def rower_ownapi_token_refresh(user): # pragma: no cover
def rower_ownapi_token_refresh(user): # pragma: no cover
r = Rower.objects.get(user=user)
res = do_refresh_token(r.ownapirefreshtoken)
access_token = res[0]
@@ -148,14 +151,15 @@ def rower_ownapi_token_refresh(user): # pragma: no cover
r.save()
return r.ownapitoken
def get_ownapi_workout_list(user): # pragma: no cover
def get_ownapi_workout_list(user): # pragma: no cover
r = Rower.objects.get(user=user)
if (r.ownapitoken == '') or (r.ownapitoken is None):
s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401,s)
elif (timezone.now()>r.ownapitokenexpirydate):
return custom_exception_handler(401, s)
elif (timezone.now() > r.ownapitokenexpirydate):
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
return custom_exception_handler(401, s)
else:
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.ownapitoken)
@@ -163,19 +167,19 @@ def get_ownapi_workout_list(user): # pragma: no cover
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.ownapi.mobi/api/v2/fitnessActivities"
s = requests.get(url,headers=headers)
s = requests.get(url, headers=headers)
return s
def get_ownapi_workout(user,ownapiid): # pragma: no cover
def get_ownapi_workout(user, ownapiid): # pragma: no cover
r = Rower.objects.get(user=user)
if (r.ownapitoken == '') or (r.ownapitoken is None):
return custom_exception_handler(401,s)
return custom_exception_handler(401, s)
s = "Token doesn't exist. Need to authorize"
elif (timezone.now()>r.ownapitokenexpirydate):
elif (timezone.now() > r.ownapitokenexpirydate):
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
return custom_exception_handler(401, s)
else:
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.ownapitoken)
@@ -183,20 +187,22 @@ def get_ownapi_workout(user,ownapiid): # pragma: no cover
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.ownapi.mobi/api/v2/fitnessActivities/"+str(ownapiid)
s = requests.get(url,headers=headers)
s = requests.get(url, headers=headers)
return s
def createownapiworkoutdata(w): # pragma: no cover
def createownapiworkoutdata(w): # pragma: no cover
filename = w.csvfilename
row = rowingdata(csvfile=filename)
averagehr = int(row.df[' HRCur (bpm)'].mean())
maxhr = int(row.df[' HRCur (bpm)'].max())
# adding diff, trying to see if this is valid
t = row.df.ix[:,'TimeStamp (sec)'].values-10*row.df.ix[0,'TimeStamp (sec)']
t = row.df.ix[:, 'TimeStamp (sec)'].values - \
10*row.df.ix[0, 'TimeStamp (sec)']
t[0] = t[1]
d = row.df.ix[:,'cum_dist'].values
d = row.df.ix[:, 'cum_dist'].values
d[0] = d[1]
t = t.astype(int)
d = d.astype(int)
@@ -204,7 +210,7 @@ def createownapiworkoutdata(w): # pragma: no cover
spm[0] = spm[1]
hr = row.df[' HRCur (bpm)'].astype(int)
haslatlon=1
haslatlon = 1
try:
lat = row.df[' latitude'].values
@@ -219,7 +225,7 @@ def createownapiworkoutdata(w): # pragma: no cover
haspower = 0
locdata = []
hrdata = []
hrdata = []
spmdata = []
distancedata = []
powerdata = []
@@ -233,17 +239,16 @@ def createownapiworkoutdata(w): # pragma: no cover
spmdata.append(spm[i])
if haslatlon:
locdata.append(t[i])
locdata.append([lat[i],lon[i]])
locdata.append([lat[i], lon[i]])
if haspower:
powerdata.append(t[i])
powerdata.append(power[i])
if haslatlon:
data = {
"type": "Rowing",
"name": w.name,
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
"start_time": w.startdatetime.isoformat(),
"total_distance": int(w.distance),
"duration": int(max(t)),
@@ -254,12 +259,12 @@ def createownapiworkoutdata(w): # pragma: no cover
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
}
else:
data = {
"type": "Rowing",
"name": w.name,
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
"start_time": w.startdatetime.isoformat(),
"total_distance": int(w.distance),
"duration": int(max(t)),
@@ -269,14 +274,15 @@ def createownapiworkoutdata(w): # pragma: no cover
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
}
if haspower:
data['power'] = powerdata
return data
def getidfromresponse(response): # pragma: no cover
def getidfromresponse(response): # pragma: no cover
t = json.loads(response.text)
uri = t['uris'][0]
id = uri[len(uri)-13:len(uri)-5]