Private
Public Access
1
0

another batch of light comments

This commit is contained in:
Sander Roosendaal
2017-01-15 16:57:11 +01:00
parent e5810dbf62
commit 5f551528da
4 changed files with 127 additions and 86 deletions

View File

@@ -1,3 +1,8 @@
# The interactions with the Concept2 logbook API
# All C2 related functions should be defined here
# (There is still some stuff defined directly in views.py. Need to
# move that here.)
# Python
import oauth2 as oauth
import cgi
@@ -17,8 +22,7 @@ from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
# Project
# from .models import Profile
from rowingdata import rowingdata
import pandas as pd
import numpy as np
@@ -27,9 +31,9 @@ import sys
import urllib
from requests import Request, Session
from rowsandall_app.settings import C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET
# Custom error class - to raise a NoTokenError
class C2NoTokenError(Exception):
def __init__(self,value):
self.value=value
@@ -37,8 +41,8 @@ class C2NoTokenError(Exception):
def __str__(self):
return repr(self.value)
# Custom exception handler, returns a 401 HTTP message
# with exception details in the json data
def custom_exception_handler(exc,message):
response = {
@@ -56,7 +60,7 @@ def custom_exception_handler(exc,message):
return res
# Check if workout is owned by this user
def checkworkoutuser(user,workout):
try:
r = Rower.objects.get(user=user)
@@ -64,11 +68,12 @@ def checkworkoutuser(user,workout):
except Rower.DoesNotExist:
return(False)
# convert datetime object to seconds
def makeseconds(t):
seconds = t.hour*3600.+t.minute*60.+t.second+0.1*int(t.microsecond/1.e5)
return seconds
# convert our weight class code to Concept2 weight class code
def c2wc(weightclass):
if (weightclass=="lwt"):
res = "L"
@@ -77,7 +82,9 @@ def c2wc(weightclass):
return res
# Concept2 logbook sends over split data for each interval
# We use it here to generate a custom summary
# Some users complained about small differences
def summaryfromsplitdata(splitdata,data,filename,sep='|'):
totaldist = data['distance']
@@ -177,6 +184,8 @@ def summaryfromsplitdata(splitdata,data,filename,sep='|'):
return sums,sa,results
# Not used now. Could be used to add workout split data to Concept2
# logbook but needs to be reviewed.
def createc2workoutdata_as_splits(w):
filename = w.csvfilename
row = rowingdata(filename)
@@ -216,7 +225,6 @@ def createc2workoutdata_as_splits(w):
data = {
"type": w.workouttype,
# "date": str(w.date)+" "+str(w.starttime),
"date": w.startdatetime.isoformat(),
"distance": int(w.distance),
"time": int(10*makeseconds(durationstr)),
@@ -233,59 +241,8 @@ def createc2workoutdata_as_splits(w):
return data
def createc2workoutdata_grouped(w):
filename = w.csvfilename
row = rowingdata(filename)
# resize per minute
df = row.df.groupby(lambda x:x/10).mean()
averagehr = int(df[' HRCur (bpm)'].mean())
maxhr = int(df[' HRCur (bpm)'].max())
# adding diff, trying to see if this is valid
t = 10*df.ix[:,' ElapsedTime (sec)'].values
t[0] = t[1]
d = df.ix[:,' Horizontal (meters)'].values
d[0] = d[1]
p = 10*df.ix[:,' Stroke500mPace (sec/500m)'].values
t = t.astype(int)
d = d.astype(int)
p = p.astype(int)
spm = df[' Cadence (stokes/min)'].astype(int)
spm[0] = spm[1]
hr = df[' HRCur (bpm)'].astype(int)
stroke_data = []
for i in range(len(t)):
thisrecord = {"t":t[i],"d":d[i],"p":p[i],"spm":spm[i],"hr":hr[i]}
stroke_data.append(thisrecord)
try:
durationstr = datetime.strptime(str(w.duration),"%H:%M:%S.%f")
except ValueError:
durationstr = datetime.strptime(str(w.duration),"%H:%M:%S")
data = {
"type": w.workouttype,
# "date": str(w.date)+" "+str(w.starttime),
"date": w.startdatetime.isoformat(),
"distance": int(w.distance),
"time": int(10*makeseconds(durationstr)),
"weight_class": c2wc(w.weightcategory),
"timezone": "Etc/UTC",
"comments": w.notes,
"heart_rate": {
"average": averagehr,
"max": maxhr,
},
"stroke_data": stroke_data,
}
return data
# Create the Data object for the stroke data to be sent to Concept2 logbook
# API
def createc2workoutdata(w):
filename = w.csvfilename
row = rowingdata(filename)
@@ -318,7 +275,6 @@ def createc2workoutdata(w):
data = {
"type": w.workouttype,
# "date": str(w.date)+" "+str(w.starttime),
"date": w.startdatetime.isoformat(),
"timezone": "Etc/UTC",
"distance": int(w.distance),
@@ -335,6 +291,7 @@ def createc2workoutdata(w):
return data
# Refresh Concept2 authorization token
def do_refresh_token(refreshtoken):
scope = "results:write,user:read"
client_auth = requests.auth.HTTPBasicAuth(C2_CLIENT_ID, C2_CLIENT_SECRET)
@@ -347,10 +304,6 @@ def do_refresh_token(refreshtoken):
url = "https://log.concept2.com/oauth/access_token"
s = Session()
req = Request('POST',url, data=post_data, headers=headers)
# response = requests.post("https://log.concept2.com/oauth/access_token",
# data=post_data,
# data=post_data,
# headers=headers)
prepped = req.prepare()
prepped.body+="&scope="
@@ -374,13 +327,12 @@ def do_refresh_token(refreshtoken):
return [thetoken,expires_in,refresh_token]
# Exchange authorization code for authorization token
def get_token(code):
scope = "user:read,results:write"
client_auth = requests.auth.HTTPBasicAuth(C2_CLIENT_ID, C2_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
# "scope": scope,
"redirect_uri": C2_REDIRECT_URI,
"client_secret": C2_CLIENT_SECRET,
"client_id":C2_CLIENT_ID,
@@ -396,9 +348,6 @@ def get_token(code):
response = s.send(prepped)
# response = requests.post("https://log.concept2.com/oauth/access_token",
# data=post_data,
# headers=headers)
token_json = response.json()
thetoken = token_json['access_token']
expires_in = token_json['expires_in']
@@ -406,6 +355,7 @@ def get_token(code):
return [thetoken,expires_in,refresh_token]
# Make URL for authorization and load it
def make_authorization_url(request):
# Generate a random string for the state parameter
# Save it for use later to prevent xsrf attacks
@@ -421,6 +371,7 @@ def make_authorization_url(request):
return HttpResponseRedirect(url)
# Get workout from C2 ID
def get_c2_workout(user,c2id):
r = Rower.objects.get(user=user)
if (r.c2token == '') or (r.c2token is None):
@@ -440,6 +391,7 @@ def get_c2_workout(user,c2id):
return s
# Get stroke data belonging to C2 ID
def get_c2_workout_strokes(user,c2id):
r = Rower.objects.get(user=user)
if (r.c2token == '') or (r.c2token is None):
@@ -459,6 +411,8 @@ def get_c2_workout_strokes(user,c2id):
return s
# Get list of C2 workouts. We load only the first page,
# assuming that users don't want to import their old workouts
def get_c2_workout_list(user):
r = Rower.objects.get(user=user)
if (r.c2token == '') or (r.c2token is None):
@@ -479,7 +433,8 @@ def get_c2_workout_list(user):
return s
# Get username, having access token.
# Handy for checking if the API access is working
def get_username(access_token):
authorizationstring = str('Bearer ' + access_token)
headers = {'Authorization': authorizationstring,
@@ -495,6 +450,8 @@ def get_username(access_token):
return me_json['data']['username']
# Get user id, having access token
# Handy for checking if the API access is working
def get_userid(access_token):
authorizationstring = str('Bearer ' + access_token)
headers = {'Authorization': authorizationstring,
@@ -510,6 +467,7 @@ def get_userid(access_token):
return me_json['data']['id']
# For debugging purposes
def process_callback(request):
# need error handling
@@ -521,6 +479,7 @@ def process_callback(request):
return HttpResponse("got a user name: %s" % username)
# Uploading workout
def workout_c2_upload(user,w):
response = 'trying C2 upload'
r = Rower.objects.get(user=user)
@@ -535,8 +494,6 @@ def workout_c2_upload(user,w):
if (checkworkoutuser(user,w)):
c2userid = get_userid(r.c2token)
data = createc2workoutdata(w)
# if (w.workouttype=='water'):
# data = createc2workoutdata_as_splits(w)
authorizationstring = str('Bearer ' + r.c2token)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
@@ -554,6 +511,7 @@ def workout_c2_upload(user,w):
return response
# This is token refresh. Looks for tokens in our database, then refreshes
def rower_c2_token_refresh(user):
r = Rower.objects.get(user=user)
res = do_refresh_token(r.c2refreshtoken)