passes checks in python3
This commit is contained in:
+69
-69
@@ -1,4 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# -*- Coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models
|
||||
@@ -18,86 +18,86 @@ class BoatCategory(models.Model):
|
||||
club = models.CharField(_("Club"),max_length=30)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("boat category")
|
||||
verbose_name_plural = _("boat categories")
|
||||
ordering = ['name']
|
||||
verbose_name = _("boat category")
|
||||
verbose_name_plural = _("boat categories")
|
||||
ordering = ['name']
|
||||
|
||||
def __str__(self):
|
||||
str = self.name
|
||||
str = self.name
|
||||
|
||||
return str
|
||||
return str
|
||||
|
||||
def __unicode__(self):
|
||||
str = self.name
|
||||
str = self.name
|
||||
|
||||
return str
|
||||
return str
|
||||
|
||||
class Member(models.Model):
|
||||
statuses = (
|
||||
("coach", _("coach")),
|
||||
("member", _("member")),
|
||||
("administrator", _("administrator")),
|
||||
)
|
||||
("coach", _("coach")),
|
||||
("member", _("member")),
|
||||
("administrator", _("administrator")),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("member")
|
||||
verbose_name_plural = _("members")
|
||||
ordering = ['user']
|
||||
verbose_name = _("member")
|
||||
verbose_name_plural = _("members")
|
||||
ordering = ['user']
|
||||
|
||||
user = models.OneToOneField(User)
|
||||
user = models.OneToOneField(User,on_delete=models.CASCADE)
|
||||
contributions = models.BooleanField(default=True)
|
||||
status = models.CharField(default="member",
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
categories = models.ManyToManyField(BoatCategory,
|
||||
verbose_name=_("Boat Categories"))
|
||||
verbose_name=_("Boat Categories"))
|
||||
club = models.CharField(_("Club"),max_length=30)
|
||||
hoursworked = models.FloatField(_("Hours Worked"))
|
||||
|
||||
def __str__(self):
|
||||
str = self.user.first_name+' '+self.user.last_name
|
||||
return str
|
||||
str = self.user.first_name+' '+self.user.last_name
|
||||
return str
|
||||
|
||||
def __unicode__(self):
|
||||
str = self.user.first_name+' '+self.user.last_name
|
||||
return str
|
||||
str = self.user.first_name+' '+self.user.last_name
|
||||
return str
|
||||
|
||||
class Boat(models.Model):
|
||||
class Meta:
|
||||
verbose_name = _("boat")
|
||||
verbose_name_plural = _("boats")
|
||||
ordering = ['boatcode']
|
||||
verbose_name = _("boat")
|
||||
verbose_name_plural = _("boats")
|
||||
ordering = ['boatcode']
|
||||
|
||||
boatname = models.CharField(_("Boat Name"),max_length=30)
|
||||
boatcode = models.CharField(_("Boat Code"),max_length=10)
|
||||
categories = models.ManyToManyField(BoatCategory)
|
||||
nrseats = models.IntegerField(_("Nr of Seats"))
|
||||
statuses = (
|
||||
("water",_("water")),
|
||||
("hangar",_("hangar")),
|
||||
("damaged",_("damaged")),
|
||||
("races",_("races")),
|
||||
)
|
||||
("water",_("water")),
|
||||
("hangar",_("hangar")),
|
||||
("damaged",_("damaged")),
|
||||
("races",_("races")),
|
||||
)
|
||||
status = models.CharField(default="hangar",
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
|
||||
comment = models.CharField(_("Comment"),blank=True,max_length=100)
|
||||
|
||||
def __str__(self):
|
||||
str = self.boatcode+' '+self.boatname
|
||||
str = self.boatcode+' '+self.boatname
|
||||
|
||||
return str
|
||||
return str
|
||||
|
||||
def __unicode__(self):
|
||||
str = self.boatcode+' '+self.boatname
|
||||
str = self.boatcode+' '+self.boatname
|
||||
|
||||
return str
|
||||
return str
|
||||
|
||||
class MemberWork(models.Model):
|
||||
class Meta:
|
||||
verbose_name = _("member work")
|
||||
verbose_name_plural = _("member work")
|
||||
verbose_name = _("member work")
|
||||
verbose_name_plural = _("member work")
|
||||
|
||||
date = models.DateField(_("Date"))
|
||||
hours = models.FloatField(_("Hours"))
|
||||
@@ -105,16 +105,16 @@ class MemberWork(models.Model):
|
||||
comment = models.CharField(_("Comment"),blank=True,max_length=100)
|
||||
worker = models.ManyToManyField(Member,_("Worker"))
|
||||
statuses = (
|
||||
("planned",_("planned")),
|
||||
("executed",_("executed"))
|
||||
)
|
||||
("planned",_("planned")),
|
||||
("executed",_("executed"))
|
||||
)
|
||||
status = models.CharField(default="planned",
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
class Races(models.Model):
|
||||
class Meta:
|
||||
verbose_name = _("race")
|
||||
verbose_name_plural = _("races")
|
||||
verbose_name = _("race")
|
||||
verbose_name_plural = _("races")
|
||||
|
||||
|
||||
name = models.CharField(max_length = 30)
|
||||
@@ -124,20 +124,20 @@ class Races(models.Model):
|
||||
transportboats = models.ManyToManyField(Boat)
|
||||
|
||||
def __str__(self):
|
||||
str = self.name
|
||||
str = str+' '+self.startdatetime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
str = self.name
|
||||
str = str+' '+self.startdatetime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
|
||||
def __unicode__(self):
|
||||
str = self.name
|
||||
str = str+' '+self.startdatetime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
str = self.name
|
||||
str = str+' '+self.startdatetime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
|
||||
|
||||
class Outing(models.Model):
|
||||
class Meta:
|
||||
verbose_name = _("outing")
|
||||
verbose_name_plural = _("outings")
|
||||
verbose_name = _("outing")
|
||||
verbose_name_plural = _("outings")
|
||||
|
||||
|
||||
starttime = models.DateTimeField(verbose_name = _("Start Time"),default=timezone.now)
|
||||
@@ -145,27 +145,27 @@ class Outing(models.Model):
|
||||
distance = models.FloatField(_("Distance (km)"),default=12)
|
||||
comment = models.CharField(_("Comment"),blank=True,max_length=100)
|
||||
statuses = (
|
||||
("reservation",_("reservation")),
|
||||
("active", _("active")),
|
||||
("completed", _("completed")),
|
||||
("race", _("race")),
|
||||
)
|
||||
boat = models.ForeignKey(Boat)
|
||||
rower = models.ForeignKey(Member)
|
||||
("reservation",_("reservation")),
|
||||
("active", _("active")),
|
||||
("completed", _("completed")),
|
||||
("race", _("race")),
|
||||
)
|
||||
boat = models.ForeignKey(Boat,on_delete=models.CASCADE)
|
||||
rower = models.ForeignKey(Member,on_delete=models.CASCADE)
|
||||
race = models.ManyToManyField(Races,blank=True)
|
||||
otherrowers = models.ManyToManyField(Member,related_name="otherrowers")
|
||||
status = models.CharField(_("Status"),default="active",
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
choices=statuses,
|
||||
max_length=30)
|
||||
|
||||
|
||||
def __str__(self):
|
||||
str = self.boat.boatcode
|
||||
str = str+' '+self.starttime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
str = self.boat.boatcode
|
||||
str = str+' '+self.starttime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
|
||||
def __unicode__(self):
|
||||
str = self.boat.boatcode
|
||||
str = str+' '+self.starttime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
str = self.boat.boatcode
|
||||
str = str+' '+self.starttime.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return str
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
from celery import Celery,app
|
||||
from .celery import Celery,app
|
||||
import os
|
||||
import time
|
||||
import gc
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
from .tasks import app as celery_app
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from rowers.celery import app as celery_app
|
||||
|
||||
__all__ = ('celery_app',)
|
||||
|
||||
+160
-159
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# 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
|
||||
@@ -6,7 +7,7 @@
|
||||
from rowers.imports import *
|
||||
import datetime
|
||||
from requests import Request, Session
|
||||
import mytypes
|
||||
import rowers.mytypes as mytypes
|
||||
from rowers.mytypes import otwtypes
|
||||
from iso8601 import ParseError
|
||||
|
||||
@@ -19,7 +20,7 @@ import django_rq
|
||||
queue = django_rq.get_queue('default')
|
||||
queuelow = django_rq.get_queue('low')
|
||||
queuehigh = django_rq.get_queue('low')
|
||||
from utils import myqueue
|
||||
from rowers.utils import myqueue
|
||||
|
||||
oauth_data = {
|
||||
'client_id': C2_CLIENT_ID,
|
||||
@@ -41,19 +42,19 @@ oauth_data = {
|
||||
def c2_open(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.c2token == '') or (r.c2token is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
raise NoTokenError("User has no token")
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
raise NoTokenError("User has no token")
|
||||
else:
|
||||
if (timezone.now()>r.tokenexpirydate):
|
||||
res = rower_c2_token_refresh(user)
|
||||
if (timezone.now()>r.tokenexpirydate):
|
||||
res = rower_c2_token_refresh(user)
|
||||
if res == None:
|
||||
raise NoTokenError("User has no token")
|
||||
if res[0] != None:
|
||||
thetoken = res[0]
|
||||
else:
|
||||
raise NoTokenError("User has no token")
|
||||
else:
|
||||
thetoken = r.c2token
|
||||
else:
|
||||
thetoken = r.c2token
|
||||
|
||||
return thetoken
|
||||
|
||||
@@ -61,11 +62,11 @@ def add_stroke_data(user,c2id,workoutid,startdatetime,csvfilename,
|
||||
workouttype='rower'):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.c2token == '') or (r.c2token is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.tokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
starttimeunix = arrow.get(startdatetime).timestamp
|
||||
|
||||
@@ -179,9 +180,9 @@ def makeseconds(t):
|
||||
# convert our weight class code to Concept2 weight class code
|
||||
def c2wc(weightclass):
|
||||
if (weightclass=="lwt"):
|
||||
res = "L"
|
||||
res = "L"
|
||||
else:
|
||||
res = "H"
|
||||
res = "H"
|
||||
|
||||
return res
|
||||
|
||||
@@ -343,17 +344,17 @@ def createc2workoutdata_as_splits(w):
|
||||
hr = df[' HRCur (bpm)'].astype(int)
|
||||
split_data = []
|
||||
for i in range(len(t)):
|
||||
thisrecord = {"time":t[i],"distance":d[i],"stroke_rate":spm[i],
|
||||
"heart_rate":{
|
||||
"average:":hr[i]
|
||||
}
|
||||
}
|
||||
split_data.append(thisrecord)
|
||||
thisrecord = {"time":t[i],"distance":d[i],"stroke_rate":spm[i],
|
||||
"heart_rate":{
|
||||
"average:":hr[i]
|
||||
}
|
||||
}
|
||||
split_data.append(thisrecord)
|
||||
|
||||
try:
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S.%f")
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S.%f")
|
||||
except ValueError:
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S")
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S")
|
||||
|
||||
try:
|
||||
newnotes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com'
|
||||
@@ -365,19 +366,19 @@ def createc2workoutdata_as_splits(w):
|
||||
wtype = 'water'
|
||||
|
||||
data = {
|
||||
"type": wtype,
|
||||
"date": w.startdatetime.isoformat(),
|
||||
"distance": int(w.distance),
|
||||
"time": int(10*makeseconds(durationstr)),
|
||||
"timezone": w.timezone,
|
||||
"weight_class": c2wc(w.weightcategory),
|
||||
"comments": newnotes,
|
||||
"heart_rate": {
|
||||
"average": averagehr,
|
||||
"max": maxhr,
|
||||
},
|
||||
"splits": split_data,
|
||||
}
|
||||
"type": wtype,
|
||||
"date": w.startdatetime.isoformat(),
|
||||
"distance": int(w.distance),
|
||||
"time": int(10*makeseconds(durationstr)),
|
||||
"timezone": w.timezone,
|
||||
"weight_class": c2wc(w.weightcategory),
|
||||
"comments": newnotes,
|
||||
"heart_rate": {
|
||||
"average": averagehr,
|
||||
"max": maxhr,
|
||||
},
|
||||
"splits": split_data,
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
@@ -418,13 +419,13 @@ def createc2workoutdata(w):
|
||||
hr = 0*d
|
||||
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)
|
||||
thisrecord = {"t":t[i],"d":d[i],"p":p[i],"spm":spm[i],"hr":hr[i]}
|
||||
stroke_data.append(thisrecord)
|
||||
|
||||
try:
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S.%f")
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S.%f")
|
||||
except ValueError:
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S")
|
||||
durationstr = datetime.datetime.strptime(str(w.duration),"%H:%M:%S")
|
||||
|
||||
workouttype = w.workouttype
|
||||
if workouttype in otwtypes:
|
||||
@@ -436,19 +437,19 @@ def createc2workoutdata(w):
|
||||
startdate = datetime.datetime.combine(w.date,datetime.time())
|
||||
|
||||
data = {
|
||||
"type": mytypes.c2mapping[workouttype],
|
||||
"date": w.startdatetime.isoformat(),
|
||||
"timezone": w.timezone,
|
||||
"distance": int(w.distance),
|
||||
"time": int(10*makeseconds(durationstr)),
|
||||
"weight_class": c2wc(w.weightcategory),
|
||||
"comments": w.notes,
|
||||
"heart_rate": {
|
||||
"average": averagehr,
|
||||
"max": maxhr,
|
||||
},
|
||||
"stroke_data": stroke_data,
|
||||
}
|
||||
"type": mytypes.c2mapping[workouttype],
|
||||
"date": w.startdatetime.isoformat(),
|
||||
"timezone": w.timezone,
|
||||
"distance": int(w.distance),
|
||||
"time": int(10*makeseconds(durationstr)),
|
||||
"weight_class": c2wc(w.weightcategory),
|
||||
"comments": w.notes,
|
||||
"heart_rate": {
|
||||
"average": averagehr,
|
||||
"max": maxhr,
|
||||
},
|
||||
"stroke_data": stroke_data,
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
@@ -458,10 +459,10 @@ def do_refresh_token(refreshtoken):
|
||||
scope = "results:write,user:read"
|
||||
client_auth = requests.auth.HTTPBasicAuth(C2_CLIENT_ID, C2_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "refresh_token",
|
||||
"client_secret": C2_CLIENT_SECRET,
|
||||
"client_id":C2_CLIENT_ID,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
"client_secret": C2_CLIENT_SECRET,
|
||||
"client_id":C2_CLIENT_ID,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal'}
|
||||
url = "https://log.concept2.com/oauth/access_token"
|
||||
s = Session()
|
||||
@@ -498,9 +499,9 @@ def get_token(code):
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": C2_REDIRECT_URI,
|
||||
"client_secret": C2_CLIENT_SECRET,
|
||||
"client_id":C2_CLIENT_ID,
|
||||
}
|
||||
"client_secret": C2_CLIENT_SECRET,
|
||||
"client_id":C2_CLIENT_ID,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal'}
|
||||
url = "https://log.concept2.com/oauth/access_token"
|
||||
s = Session()
|
||||
@@ -554,19 +555,19 @@ def make_authorization_url(request):
|
||||
def get_workout(user,c2id):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.c2token == '') or (r.c2token is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s) ,0
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s) ,0
|
||||
elif (timezone.now()>r.tokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s),0
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s),0
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results/"+str(c2id)
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results/"+str(c2id)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
|
||||
data = s.json()['data']
|
||||
@@ -583,9 +584,9 @@ def get_workout(user,c2id):
|
||||
# Check if workout has stroke data, and get the stroke data
|
||||
|
||||
if data['stroke_data']:
|
||||
res2 = get_c2_workout_strokes(user,c2id)
|
||||
if res2.status_code == 200:
|
||||
strokedata = pd.DataFrame.from_dict(res2.json()['data'])
|
||||
res2 = get_c2_workout_strokes(user,c2id)
|
||||
if res2.status_code == 200:
|
||||
strokedata = pd.DataFrame.from_dict(res2.json()['data'])
|
||||
else:
|
||||
strokedata = pd.DataFrame()
|
||||
else:
|
||||
@@ -597,19 +598,19 @@ def get_workout(user,c2id):
|
||||
def get_c2_workout_strokes(user,c2id):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.c2token == '') or (r.c2token is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.tokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results/"+str(c2id)+"/strokes"
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results/"+str(c2id)+"/strokes"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -618,21 +619,21 @@ def get_c2_workout_strokes(user,c2id):
|
||||
def get_c2_workout_list(user,page=1):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.c2token == '') or (r.c2token is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.tokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results"
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://log.concept2.com/api/users/me/results"
|
||||
url += "?page={page}".format(page=page)
|
||||
|
||||
s = requests.get(url,headers=headers)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -642,8 +643,8 @@ def get_c2_workout_list(user,page=1):
|
||||
def get_username(access_token):
|
||||
authorizationstring = str('Bearer ' + access_token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://log.concept2.com/api/users/me"
|
||||
response = requests.get(url,headers=headers)
|
||||
@@ -664,8 +665,8 @@ def get_username(access_token):
|
||||
def get_userid(access_token):
|
||||
authorizationstring = str('Bearer ' + access_token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://log.concept2.com/api/users/me"
|
||||
response = requests.get(url,headers=headers)
|
||||
@@ -706,40 +707,40 @@ def workout_c2_upload(user,w):
|
||||
|
||||
# ready to upload. Hurray
|
||||
if (checkworkoutuser(user,w)):
|
||||
c2userid = get_userid(r.c2token)
|
||||
c2userid = get_userid(r.c2token)
|
||||
if not c2userid:
|
||||
raise NoTokenError
|
||||
|
||||
data = createc2workoutdata(w)
|
||||
data = createc2workoutdata(w)
|
||||
if data == 0:
|
||||
return "Error: No data file. Contact info@rowsandall.com if the problem persists",0
|
||||
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://log.concept2.com/api/users/%s/results" % (c2userid)
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
authorizationstring = str('Bearer ' + r.c2token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://log.concept2.com/api/users/%s/results" % (c2userid)
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
if (response.status_code == 409 ):
|
||||
message = "Concept2 Duplicate error"
|
||||
w.uploadedtoc2 = -1
|
||||
message = "Concept2 Duplicate error"
|
||||
w.uploadedtoc2 = -1
|
||||
c2id = -1
|
||||
w.save()
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code == 200):
|
||||
try:
|
||||
# s= json.loads(response.text)
|
||||
# s= json.loads(response.text)
|
||||
s = response.json()
|
||||
c2id = s['data']['id']
|
||||
w.uploadedtoc2 = c2id
|
||||
w.save()
|
||||
c2id = s['data']['id']
|
||||
w.uploadedtoc2 = c2id
|
||||
w.save()
|
||||
message = "Upload to Concept2 was successful"
|
||||
except:
|
||||
message = "Something went wrong in workout_c2_upload_view. Response code 200/201 but C2 sync failed: "+response.text
|
||||
c2id = 0
|
||||
|
||||
else:
|
||||
else:
|
||||
message = "Something went wrong in workout_c2_upload_view. Response code 200/201 but C2 sync failed: "+response.text
|
||||
c2id = 0
|
||||
|
||||
@@ -776,41 +777,41 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
workouttype = 'rower'
|
||||
|
||||
if workouttype not in [x[0] for x in Workout.workouttypes]:
|
||||
workouttype = 'other'
|
||||
workouttype = 'other'
|
||||
try:
|
||||
comments = data['comments']
|
||||
comments = data['comments']
|
||||
except:
|
||||
comments = ' '
|
||||
comments = ' '
|
||||
|
||||
try:
|
||||
thetimezone = tz(data['timezone'])
|
||||
thetimezone = tz(data['timezone'])
|
||||
except:
|
||||
thetimezone = 'UTC'
|
||||
thetimezone = 'UTC'
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
except KeyError:
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
except ParseError:
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
|
||||
|
||||
|
||||
try:
|
||||
c2intervaltype = data['workout_type']
|
||||
|
||||
|
||||
except KeyError:
|
||||
c2intervaltype = ''
|
||||
|
||||
c2intervaltype = ''
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except KeyError:
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
|
||||
@@ -825,17 +826,17 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
nr_rows = len(unixtime)
|
||||
|
||||
try:
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
except:
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
|
||||
|
||||
try:
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
except:
|
||||
strokelength = np.zeros(nr_rows)
|
||||
strokelength = np.zeros(nr_rows)
|
||||
|
||||
dist2 = 0.1*strokedata.loc[:,'d']
|
||||
|
||||
@@ -862,27 +863,27 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
# save csv
|
||||
# Create data frame with all necessary data to write to csv
|
||||
df = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
|
||||
|
||||
+3
-2
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the Courses related methods
|
||||
|
||||
# Python
|
||||
@@ -28,7 +29,7 @@ import pandas as pd
|
||||
import numpy as np
|
||||
from timezonefinder import TimezoneFinder
|
||||
|
||||
import dataprep
|
||||
import rowers.dataprep as dataprep
|
||||
from rowers.utils import geo_distance
|
||||
|
||||
ns = {'opengis': 'http://www.opengis.net/kml/2.2'}
|
||||
@@ -47,7 +48,7 @@ from rowers.models import (
|
||||
polygon_to_path,coordinate_in_path
|
||||
)
|
||||
|
||||
from utils import geo_distance
|
||||
|
||||
from rowers.courseutils import coursetime_paths, coursetime_first,time_in_path
|
||||
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ def coordinate_in_path(latitude,longitude, p):
|
||||
|
||||
class InvalidTrajectoryError(Exception):
|
||||
def __init__(self,value):
|
||||
self.value=value
|
||||
self.value=value
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
return repr(self.value)
|
||||
|
||||
def time_in_path(df,p,maxmin='max',getall=False):
|
||||
|
||||
|
||||
+15
-14
@@ -1,5 +1,6 @@
|
||||
# All the data preparation, data cleaning and data mangling should
|
||||
# be defined here
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
from rowers.models import Workout, StrokeData,Team
|
||||
|
||||
import pytz
|
||||
@@ -55,7 +56,7 @@ import pandas as pd
|
||||
import numpy as np
|
||||
import itertools
|
||||
import math
|
||||
from tasks import (
|
||||
from rowers.tasks import (
|
||||
handle_sendemail_unrecognized, handle_sendemail_breakthrough,
|
||||
handle_sendemail_hard, handle_updatecp,handle_updateergcp,
|
||||
handle_calctrimp,
|
||||
@@ -65,9 +66,9 @@ from django.conf import settings
|
||||
from sqlalchemy import create_engine
|
||||
import sqlalchemy as sa
|
||||
import sys
|
||||
import utils
|
||||
import datautils
|
||||
from utils import lbstoN,myqueue,is_ranking_piece,wavg
|
||||
import rowers.utils as utils
|
||||
import rowers.datautils as datautils
|
||||
from rowers.utils import lbstoN,myqueue,is_ranking_piece,wavg
|
||||
|
||||
from timezonefinder import TimezoneFinder
|
||||
|
||||
@@ -638,7 +639,7 @@ def deletecpdata_sql(rower_id,table='cpdata'):
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database locked"
|
||||
print("Database locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
|
||||
@@ -855,7 +856,7 @@ def create_row_df(r,distance,duration,startdatetime,workouttype='rower',
|
||||
|
||||
return (id, message)
|
||||
|
||||
from utils import totaltime_sec_to_string
|
||||
from rowers.utils import totaltime_sec_to_string
|
||||
|
||||
# Processes painsled CSV file to database
|
||||
def save_workout_database(f2, r, dosmooth=True, workouttype='rower',
|
||||
@@ -1564,7 +1565,7 @@ def compare_data(id):
|
||||
res = conn.execute(query)
|
||||
l2 = res.fetchall()[0][0]
|
||||
except:
|
||||
print "Database Locked"
|
||||
print("Database Locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
lfile = l1
|
||||
@@ -1583,13 +1584,13 @@ def repair_data(verbose=False):
|
||||
test, ldb, lfile = compare_data(w.id)
|
||||
if not test:
|
||||
if verbose:
|
||||
print w.id, lfile, ldb
|
||||
print(w.id, lfile, ldb)
|
||||
try:
|
||||
rowdata = rdata(w.csvfilename)
|
||||
if rowdata and len(rowdata.df):
|
||||
update_strokedata(w.id, rowdata.df)
|
||||
|
||||
except IOError, AttributeError:
|
||||
except (IOError, AttributeError):
|
||||
pass
|
||||
|
||||
if lfile == 0:
|
||||
@@ -1618,10 +1619,10 @@ def repair_data(verbose=False):
|
||||
def rdata(file, rower=rrower()):
|
||||
try:
|
||||
res = rrdata(csvfile=file, rower=rower)
|
||||
except IOError, IndexError:
|
||||
except (IOError, IndexError):
|
||||
try:
|
||||
res = rrdata(csvfile=file + '.gz', rower=rower)
|
||||
except IOError, IndexError:
|
||||
except (IOError, IndexError):
|
||||
res = rrdata()
|
||||
except:
|
||||
res = rrdata()
|
||||
@@ -1640,7 +1641,7 @@ def delete_strokedata(id):
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database Locked"
|
||||
print("Database Locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
|
||||
@@ -1792,7 +1793,7 @@ def prepmultipledata(ids, verbose=False):
|
||||
for id in res:
|
||||
rowdata, row = getrowdata(id=id)
|
||||
if verbose:
|
||||
print id
|
||||
print(id)
|
||||
if rowdata and len(rowdata.df):
|
||||
data = dataprep(rowdata.df, id=id, bands=True,
|
||||
barchart=True, otwpower=True)
|
||||
@@ -2029,7 +2030,7 @@ def fix_newtons(id=0, limit=3000):
|
||||
peakforce = rowdata['peakforce']
|
||||
if peakforce.mean() > limit:
|
||||
w = Workout.objects.get(id=id)
|
||||
print "fixing ", id
|
||||
print("fixing ", id)
|
||||
rowdata = rdata(w.csvfilename)
|
||||
if rowdata and len(rowdata.df):
|
||||
update_strokedata(w.id, rowdata.df)
|
||||
|
||||
+146
-146
@@ -18,7 +18,7 @@ import sqlalchemy as sa
|
||||
from rowsandall_app.settings import DATABASES
|
||||
from rowsandall_app.settings_dev import DATABASES as DEV_DATABASES
|
||||
|
||||
from utils import lbstoN
|
||||
from rowers.utils import lbstoN
|
||||
|
||||
|
||||
try:
|
||||
@@ -83,33 +83,33 @@ import datetime
|
||||
def niceformat(values):
|
||||
out = []
|
||||
for v in values:
|
||||
formattedv = strfdelta(v)
|
||||
out.append(formattedv)
|
||||
|
||||
formattedv = strfdelta(v)
|
||||
out.append(formattedv)
|
||||
|
||||
return out
|
||||
|
||||
def strfdelta(tdelta):
|
||||
try:
|
||||
minutes,seconds = divmod(tdelta.seconds,60)
|
||||
tenths = int(tdelta.microseconds/1e5)
|
||||
minutes,seconds = divmod(tdelta.seconds,60)
|
||||
tenths = int(tdelta.microseconds/1e5)
|
||||
except AttributeError:
|
||||
minutes,seconds = divmod(tdelta.view(np.int64),60e9)
|
||||
seconds,rest = divmod(seconds,1e9)
|
||||
tenths = int(rest/1e8)
|
||||
minutes,seconds = divmod(tdelta.view(np.int64),60e9)
|
||||
seconds,rest = divmod(seconds,1e9)
|
||||
tenths = int(rest/1e8)
|
||||
res = "{minutes:0>2}:{seconds:0>2}.{tenths:0>1}".format(
|
||||
minutes=minutes,
|
||||
seconds=seconds,
|
||||
tenths=tenths,
|
||||
)
|
||||
minutes=minutes,
|
||||
seconds=seconds,
|
||||
tenths=tenths,
|
||||
)
|
||||
|
||||
return res
|
||||
|
||||
def nicepaceformat(values):
|
||||
out = []
|
||||
for v in values:
|
||||
formattedv = strfdelta(v)
|
||||
out.append(formattedv)
|
||||
|
||||
formattedv = strfdelta(v)
|
||||
out.append(formattedv)
|
||||
|
||||
|
||||
return out
|
||||
|
||||
@@ -124,16 +124,16 @@ def timedeltaconv(x):
|
||||
|
||||
def rdata(file,rower=rrower()):
|
||||
try:
|
||||
res = rrdata(file,rower=rower)
|
||||
res = rrdata(file,rower=rower)
|
||||
except IOError:
|
||||
try:
|
||||
res = rrdata(file+'.gz',rower=rower)
|
||||
except IOError:
|
||||
res = 0
|
||||
res = 0
|
||||
|
||||
return res
|
||||
|
||||
from utils import totaltime_sec_to_string
|
||||
from rowers.utils import totaltime_sec_to_string
|
||||
|
||||
|
||||
# Creates C2 stroke data
|
||||
@@ -175,22 +175,22 @@ def create_c2_stroke_data_db(
|
||||
|
||||
df = pd.DataFrame({
|
||||
'TimeStamp (sec)': unixtime,
|
||||
' Horizontal (meters)': d,
|
||||
' Horizontal (meters)': d,
|
||||
' Cadence (stokes/min)': spm,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' ElapsedTime (sec)':elapsed,
|
||||
' Power (watts)':power,
|
||||
' HRCur (bpm)':np.zeros(nr_strokes),
|
||||
' longitude':np.zeros(nr_strokes),
|
||||
' latitude':np.zeros(nr_strokes),
|
||||
' DragFactor':np.zeros(nr_strokes),
|
||||
' DriveLength (meters)':np.zeros(nr_strokes),
|
||||
' StrokeDistance (meters)':np.zeros(nr_strokes),
|
||||
' DriveTime (ms)':np.zeros(nr_strokes),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_strokes),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' lapIdx':np.zeros(nr_strokes),
|
||||
' HRCur (bpm)':np.zeros(nr_strokes),
|
||||
' longitude':np.zeros(nr_strokes),
|
||||
' latitude':np.zeros(nr_strokes),
|
||||
' DragFactor':np.zeros(nr_strokes),
|
||||
' DriveLength (meters)':np.zeros(nr_strokes),
|
||||
' StrokeDistance (meters)':np.zeros(nr_strokes),
|
||||
' DriveTime (ms)':np.zeros(nr_strokes),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_strokes),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' lapIdx':np.zeros(nr_strokes),
|
||||
'cum_dist': d
|
||||
})
|
||||
|
||||
@@ -220,17 +220,17 @@ def add_c2_stroke_data_db(strokedata,workoutid,starttimeunix,csvfilename,
|
||||
nr_rows = len(unixtime)
|
||||
|
||||
try:
|
||||
latcoord = strokedata.ix[:,'lat']
|
||||
loncoord = strokedata.ix[:,'lon']
|
||||
latcoord = strokedata.ix[:,'lat']
|
||||
loncoord = strokedata.ix[:,'lon']
|
||||
except:
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
|
||||
|
||||
try:
|
||||
strokelength = strokedata.ix[:,'strokelength']
|
||||
strokelength = strokedata.ix[:,'strokelength']
|
||||
except:
|
||||
strokelength = np.zeros(nr_rows)
|
||||
strokelength = np.zeros(nr_rows)
|
||||
|
||||
dist2 = 0.1*strokedata.ix[:,'d']
|
||||
|
||||
@@ -258,28 +258,28 @@ def add_c2_stroke_data_db(strokedata,workoutid,starttimeunix,csvfilename,
|
||||
# save csv
|
||||
# Create data frame with all necessary data to write to csv
|
||||
df = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds,
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds,
|
||||
'cum_dist': dist2
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
|
||||
@@ -312,8 +312,8 @@ def save_workout_database(f2,r,dosmooth=True,workouttype='rower',
|
||||
|
||||
# make workout and put in database
|
||||
rr = rrower(hrmax=r.max,hrut2=r.ut2,
|
||||
hrut1=r.ut1,hrat=r.at,
|
||||
hrtr=r.tr,hran=r.an,ftp=r.ftp,
|
||||
hrut1=r.ut1,hrat=r.at,
|
||||
hrtr=r.tr,hran=r.an,ftp=r.ftp,
|
||||
powerperc=powerperc,powerzones=r.powerzones)
|
||||
row = rdata(f2,rower=rr)
|
||||
|
||||
@@ -329,7 +329,7 @@ def save_workout_database(f2,r,dosmooth=True,workouttype='rower',
|
||||
|
||||
|
||||
if row == 0:
|
||||
return (0,'Error: CSV data file not found')
|
||||
return (0,'Error: CSV data file not found')
|
||||
|
||||
if dosmooth:
|
||||
# auto smoothing
|
||||
@@ -342,12 +342,12 @@ def save_workout_database(f2,r,dosmooth=True,workouttype='rower',
|
||||
else:
|
||||
windowsize = 1
|
||||
if not 'originalvelo' in row.df:
|
||||
row.df['originalvelo'] = velo
|
||||
row.df['originalvelo'] = velo
|
||||
|
||||
if windowsize > 3 and windowsize<len(velo):
|
||||
velo2 = savgol_filter(velo,windowsize,3)
|
||||
velo2 = savgol_filter(velo,windowsize,3)
|
||||
else:
|
||||
velo2 = velo
|
||||
velo2 = velo
|
||||
|
||||
velo3 = pd.Series(velo2)
|
||||
velo3 = velo3.replace([-np.inf,np.inf],np.nan)
|
||||
@@ -367,11 +367,11 @@ def save_workout_database(f2,r,dosmooth=True,workouttype='rower',
|
||||
|
||||
# recalculate power data
|
||||
if workouttype == 'rower' or workouttype == 'dynamic' or workouttype == 'slides':
|
||||
try:
|
||||
row.erg_recalculatepower()
|
||||
try:
|
||||
row.erg_recalculatepower()
|
||||
row.write_csv(f2,gzip=True)
|
||||
except:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
averagehr = row.df[' HRCur (bpm)'].mean()
|
||||
maxhr = row.df[' HRCur (bpm)'].max()
|
||||
@@ -425,22 +425,22 @@ def save_workout_database(f2,r,dosmooth=True,workouttype='rower',
|
||||
|
||||
# check for duplicate start times
|
||||
ws = Workout.objects.filter(startdatetime=workoutstartdatetime,
|
||||
user=r)
|
||||
user=r)
|
||||
if (len(ws) != 0):
|
||||
message = "Warning: This workout probably already exists in the database"
|
||||
message = "Warning: This workout probably already exists in the database"
|
||||
privacy = 'private'
|
||||
|
||||
|
||||
|
||||
w = Workout(user=r,name=title,date=workoutdate,
|
||||
workouttype=workouttype,
|
||||
workouttype=workouttype,
|
||||
workoutsource=workoutsource,
|
||||
duration=duration,distance=totaldist,
|
||||
weightcategory=r.weightcategory,
|
||||
starttime=workoutstarttime,
|
||||
csvfilename=f2,notes=notes,summary=summary,
|
||||
maxhr=maxhr,averagehr=averagehr,
|
||||
startdatetime=workoutstartdatetime,
|
||||
duration=duration,distance=totaldist,
|
||||
weightcategory=r.weightcategory,
|
||||
starttime=workoutstarttime,
|
||||
csvfilename=f2,notes=notes,summary=summary,
|
||||
maxhr=maxhr,averagehr=averagehr,
|
||||
startdatetime=workoutstartdatetime,
|
||||
inboard=inboard,oarlength=oarlength,
|
||||
privacy=privacy)
|
||||
|
||||
@@ -463,14 +463,14 @@ def handle_nonpainsled(f2,fileformat,summary=''):
|
||||
inboard = 0.88
|
||||
# handle RowPro:
|
||||
if (fileformat == 'rp'):
|
||||
row = RowProParser(f2)
|
||||
# handle TCX
|
||||
row = RowProParser(f2)
|
||||
# handle TCX
|
||||
if (fileformat == 'tcx'):
|
||||
row = TCXParser(f2)
|
||||
row = TCXParser(f2)
|
||||
|
||||
# handle Mystery
|
||||
if (fileformat == 'mystery'):
|
||||
row = MysteryParser(f2)
|
||||
row = MysteryParser(f2)
|
||||
|
||||
# handle RowPerfect
|
||||
if (fileformat == 'rowperfect3'):
|
||||
@@ -478,11 +478,11 @@ def handle_nonpainsled(f2,fileformat,summary=''):
|
||||
|
||||
# handle ErgData
|
||||
if (fileformat == 'ergdata'):
|
||||
row = ErgDataParser(f2)
|
||||
row = ErgDataParser(f2)
|
||||
|
||||
# handle CoxMate
|
||||
if (fileformat == 'coxmate'):
|
||||
row = CoxMateParser(f2)
|
||||
row = CoxMateParser(f2)
|
||||
|
||||
# handle Mike
|
||||
if (fileformat == 'bcmike'):
|
||||
@@ -494,19 +494,19 @@ def handle_nonpainsled(f2,fileformat,summary=''):
|
||||
|
||||
# handle BoatCoach
|
||||
if (fileformat == 'boatcoach'):
|
||||
row = BoatCoachParser(f2)
|
||||
row = BoatCoachParser(f2)
|
||||
|
||||
# handle painsled desktop
|
||||
if (fileformat == 'painsleddesktop'):
|
||||
row = painsledDesktopParser(f2)
|
||||
row = painsledDesktopParser(f2)
|
||||
|
||||
# handle speed coach GPS
|
||||
if (fileformat == 'speedcoach'):
|
||||
row = speedcoachParser(f2)
|
||||
row = speedcoachParser(f2)
|
||||
|
||||
# handle speed coach GPS 2
|
||||
if (fileformat == 'speedcoach2'):
|
||||
row = SpeedCoach2Parser(f2)
|
||||
row = SpeedCoach2Parser(f2)
|
||||
try:
|
||||
oarlength,inboard = get_empower_rigging(f2)
|
||||
summary = row.allstats()
|
||||
@@ -516,14 +516,14 @@ def handle_nonpainsled(f2,fileformat,summary=''):
|
||||
|
||||
# handle ErgStick
|
||||
if (fileformat == 'ergstick'):
|
||||
row = ErgStickParser(f2)
|
||||
|
||||
row = ErgStickParser(f2)
|
||||
|
||||
# handle FIT
|
||||
if (fileformat == 'fit'):
|
||||
row = FITParser(f2)
|
||||
s = fitsummarydata(f2)
|
||||
s.setsummary()
|
||||
summary = s.summarytext
|
||||
row = FITParser(f2)
|
||||
s = fitsummarydata(f2)
|
||||
s.setsummary()
|
||||
summary = s.summarytext
|
||||
|
||||
|
||||
f_to_be_deleted = f2
|
||||
@@ -533,7 +533,7 @@ def handle_nonpainsled(f2,fileformat,summary=''):
|
||||
|
||||
#os.remove(f2)
|
||||
try:
|
||||
os.remove(f_to_be_deleted)
|
||||
os.remove(f_to_be_deleted)
|
||||
except:
|
||||
os.remove(f_to_be_deleted+'.gz')
|
||||
|
||||
@@ -588,14 +588,14 @@ def new_workout_from_file(r,f2,
|
||||
# for me to check if it is a bug, or a new file type
|
||||
# worth supporting
|
||||
if fileformat == 'unknown':
|
||||
message = "We couldn't recognize the file type"
|
||||
if settings.DEBUG:
|
||||
res = handle_sendemail_unrecognized.delay(f2,
|
||||
r.user.email)
|
||||
message = "We couldn't recognize the file type"
|
||||
if settings.DEBUG:
|
||||
res = handle_sendemail_unrecognized.delay(f2,
|
||||
r.user.email)
|
||||
|
||||
else:
|
||||
res = queuehigh.enqueue(handle_sendemail_unrecognized,
|
||||
f2,r.user.email)
|
||||
else:
|
||||
res = queuehigh.enqueue(handle_sendemail_unrecognized,
|
||||
f2,r.user.email)
|
||||
return (0,message,f2)
|
||||
|
||||
# handle non-Painsled by converting it to painsled compatible CSV
|
||||
@@ -635,14 +635,14 @@ def delete_strokedata(id,debug=False):
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database Locked"
|
||||
print("Database Locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
|
||||
def update_strokedata(id,df,debug=False):
|
||||
delete_strokedata(id,debug=debug)
|
||||
if debug:
|
||||
print "updating ",id
|
||||
print("updating ",id)
|
||||
rowdata = dataprep(df,id=id,bands=True,barchart=True,otwpower=True,
|
||||
debug=debug)
|
||||
|
||||
@@ -676,11 +676,11 @@ def update_empower(id, inboard, oarlength, boattype, df, f1, debug=False):
|
||||
if success:
|
||||
delete_strokedata(id,debug=debug)
|
||||
if debug:
|
||||
print "updated ",id
|
||||
print "correction ",corr_factor
|
||||
print("updated ",id)
|
||||
print("correction ",corr_factor)
|
||||
else:
|
||||
if debug:
|
||||
print "not updated ",id
|
||||
print("not updated ",id)
|
||||
|
||||
|
||||
rowdata = dataprep(df,id=id,bands=True,barchart=True,otwpower=True,
|
||||
@@ -784,8 +784,8 @@ def read_cols_df_sql(ids,columns,debug=False):
|
||||
def read_df_sql(id,debug=False):
|
||||
if debug:
|
||||
engine = create_engine(database_url_debug, echo=False)
|
||||
print "read_df",id
|
||||
print database_url_debug
|
||||
print("read_df",id)
|
||||
print(database_url_debug)
|
||||
else:
|
||||
engine = create_engine(database_url, echo=False)
|
||||
|
||||
@@ -826,7 +826,7 @@ def deletecpdata_sql(rower_id,table='cpdata',debug=False):
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database locked"
|
||||
print("Database locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
|
||||
@@ -846,7 +846,7 @@ def delete_agegroup_db(age,sex,weightcategory,debug=False):
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database locked"
|
||||
print("Database locked")
|
||||
conn.close()
|
||||
engine.dispose()
|
||||
|
||||
@@ -956,11 +956,11 @@ def dataprep(rowdatadf,id=0,bands=True,barchart=True,otwpower=True,
|
||||
|
||||
if rowdatadf.empty:
|
||||
if debug:
|
||||
print "empty"
|
||||
print("empty")
|
||||
return 0
|
||||
|
||||
if debug:
|
||||
print "dataprep",id
|
||||
print("dataprep",id)
|
||||
|
||||
rowdatadf.set_index([range(len(rowdatadf))],inplace=True)
|
||||
t = rowdatadf.ix[:,'TimeStamp (sec)']
|
||||
@@ -1006,12 +1006,12 @@ def dataprep(rowdatadf,id=0,bands=True,barchart=True,otwpower=True,
|
||||
else:
|
||||
windowsize = 1
|
||||
if windowsize <= 3:
|
||||
windowsize = 5
|
||||
windowsize = 5
|
||||
|
||||
if windowsize > 3 and windowsize<len(hr):
|
||||
spm = savgol_filter(spm,windowsize,3)
|
||||
hr = savgol_filter(hr,windowsize,3)
|
||||
drivelength = savgol_filter(drivelength,windowsize,3)
|
||||
spm = savgol_filter(spm,windowsize,3)
|
||||
hr = savgol_filter(hr,windowsize,3)
|
||||
drivelength = savgol_filter(drivelength,windowsize,3)
|
||||
forceratio = savgol_filter(forceratio,windowsize,3)
|
||||
|
||||
try:
|
||||
@@ -1072,14 +1072,14 @@ def dataprep(rowdatadf,id=0,bands=True,barchart=True,otwpower=True,
|
||||
)
|
||||
|
||||
if bands:
|
||||
# HR bands
|
||||
data['hr_ut2'] = rowdatadf.ix[:,'hr_ut2']
|
||||
data['hr_ut1'] = rowdatadf.ix[:,'hr_ut1']
|
||||
data['hr_at'] = rowdatadf.ix[:,'hr_at']
|
||||
data['hr_tr'] = rowdatadf.ix[:,'hr_tr']
|
||||
data['hr_an'] = rowdatadf.ix[:,'hr_an']
|
||||
data['hr_max'] = rowdatadf.ix[:,'hr_max']
|
||||
data['hr_bottom'] = 0.0*data['hr']
|
||||
# HR bands
|
||||
data['hr_ut2'] = rowdatadf.ix[:,'hr_ut2']
|
||||
data['hr_ut1'] = rowdatadf.ix[:,'hr_ut1']
|
||||
data['hr_at'] = rowdatadf.ix[:,'hr_at']
|
||||
data['hr_tr'] = rowdatadf.ix[:,'hr_tr']
|
||||
data['hr_an'] = rowdatadf.ix[:,'hr_an']
|
||||
data['hr_max'] = rowdatadf.ix[:,'hr_max']
|
||||
data['hr_bottom'] = 0.0*data['hr']
|
||||
|
||||
|
||||
try:
|
||||
@@ -1088,13 +1088,13 @@ def dataprep(rowdatadf,id=0,bands=True,barchart=True,otwpower=True,
|
||||
rowdatadf[' ElapsedTime (sec)'] = rowdatadf['TimeStamp (sec)']
|
||||
|
||||
if barchart:
|
||||
# time increments for bar chart
|
||||
time_increments = rowdatadf.ix[:,' ElapsedTime (sec)'].diff()
|
||||
time_increments[0] = time_increments[1]
|
||||
time_increments = 0.5*time_increments+0.5*np.abs(time_increments)
|
||||
x_right = (t2+time_increments.apply(lambda x:timedeltaconv(x)))
|
||||
# time increments for bar chart
|
||||
time_increments = rowdatadf.ix[:,' ElapsedTime (sec)'].diff()
|
||||
time_increments[0] = time_increments[1]
|
||||
time_increments = 0.5*time_increments+0.5*np.abs(time_increments)
|
||||
x_right = (t2+time_increments.apply(lambda x:timedeltaconv(x)))
|
||||
|
||||
data['x_right'] = x_right
|
||||
data['x_right'] = x_right
|
||||
|
||||
if empower:
|
||||
try:
|
||||
@@ -1207,29 +1207,29 @@ def dataprep(rowdatadf,id=0,bands=True,barchart=True,otwpower=True,
|
||||
pass
|
||||
|
||||
if otwpower:
|
||||
try:
|
||||
nowindpace = rowdatadf.ix[:,'nowindpace']
|
||||
except KeyError:
|
||||
nowindpace = p
|
||||
try:
|
||||
equivergpower = rowdatadf.ix[:,'equivergpower']
|
||||
except KeyError:
|
||||
equivergpower = 0*p+50.
|
||||
|
||||
nowindpace2 = nowindpace.apply(lambda x: timedeltaconv(x))
|
||||
ergvelo = (equivergpower/2.8)**(1./3.)
|
||||
try:
|
||||
nowindpace = rowdatadf.ix[:,'nowindpace']
|
||||
except KeyError:
|
||||
nowindpace = p
|
||||
try:
|
||||
equivergpower = rowdatadf.ix[:,'equivergpower']
|
||||
except KeyError:
|
||||
equivergpower = 0*p+50.
|
||||
|
||||
nowindpace2 = nowindpace.apply(lambda x: timedeltaconv(x))
|
||||
ergvelo = (equivergpower/2.8)**(1./3.)
|
||||
|
||||
ergpace = 500./ergvelo
|
||||
ergpace[ergpace == np.inf] = 240.
|
||||
ergpace2 = ergpace.apply(lambda x: timedeltaconv(x))
|
||||
ergpace = 500./ergvelo
|
||||
ergpace[ergpace == np.inf] = 240.
|
||||
ergpace2 = ergpace.apply(lambda x: timedeltaconv(x))
|
||||
|
||||
|
||||
|
||||
data['ergpace'] = ergpace*1e3
|
||||
data['nowindpace'] = nowindpace*1e3
|
||||
data['equivergpower'] = equivergpower
|
||||
data['fergpace'] = nicepaceformat(ergpace2)
|
||||
data['fnowindpace'] = nicepaceformat(nowindpace2)
|
||||
data['ergpace'] = ergpace*1e3
|
||||
data['nowindpace'] = nowindpace*1e3
|
||||
data['equivergpower'] = equivergpower
|
||||
data['fergpace'] = nicepaceformat(ergpace2)
|
||||
data['fnowindpace'] = nicepaceformat(nowindpace2)
|
||||
data['efficiency'] = efficiency
|
||||
|
||||
data = data.replace([-np.inf,np.inf],np.nan)
|
||||
|
||||
+5
-5
@@ -49,14 +49,14 @@ def cpfit(powerdf):
|
||||
|
||||
if len(thesecs)>=4:
|
||||
try:
|
||||
p1, success = optimize.leastsq(errfunc, p0[:], args = (thesecs,theavpower))
|
||||
p1, success = optimize.leastsq(errfunc, p0[:], args = (thesecs,theavpower))
|
||||
except:
|
||||
factor = fitfunc(p0,thesecs.mean())/theavpower.mean()
|
||||
p1 = [p0[0]/factor,p0[1]/factor,p0[2],p0[3]]
|
||||
factor = fitfunc(p0,thesecs.mean())/theavpower.mean()
|
||||
p1 = [p0[0]/factor,p0[1]/factor,p0[2],p0[3]]
|
||||
|
||||
else:
|
||||
factor = fitfunc(p0,thesecs.mean())/theavpower.mean()
|
||||
p1 = [p0[0]/factor,p0[1]/factor,p0[2],p0[3]]
|
||||
factor = fitfunc(p0,thesecs.mean())/theavpower.mean()
|
||||
p1 = [p0[0]/factor,p0[1]/factor,p0[2],p0[3]]
|
||||
|
||||
|
||||
p1 = [abs(p) for p in p1]
|
||||
|
||||
+90
-88
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
from django import forms
|
||||
from django.contrib.admin.widgets import FilteredSelectMultiple
|
||||
from rowers.models import (
|
||||
@@ -9,15 +10,16 @@ from rowers.rows import validate_file_extension,must_be_csv,validate_image_exten
|
||||
from django.contrib.auth.forms import UserCreationForm
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.admin.widgets import AdminDateWidget
|
||||
from django.forms.extras.widgets import SelectDateWidget
|
||||
from django.forms.widgets import SelectDateWidget
|
||||
#from django.forms.extras.widgets import SelectDateWidget
|
||||
from django.utils import timezone,translation
|
||||
from django.forms import ModelForm, Select
|
||||
import dataprep
|
||||
import mytypes
|
||||
import rowers.dataprep as dataprep
|
||||
import rowers.mytypes as mytypes
|
||||
import datetime
|
||||
from django.forms import formset_factory
|
||||
from utils import landingpages
|
||||
from metrics import axes
|
||||
from rowers.utils import landingpages
|
||||
from rowers.metrics import axes
|
||||
|
||||
class FlexibleDecimalField(forms.DecimalField):
|
||||
|
||||
@@ -84,7 +86,7 @@ for key, value in disqualificationreasons:
|
||||
class DisqualificationForm(forms.Form):
|
||||
|
||||
reason = forms.ChoiceField(required=True,
|
||||
choices=disqualificationreasons,
|
||||
choices=disqualificationreasons,
|
||||
widget = forms.RadioSelect,)
|
||||
|
||||
message = forms.CharField(required=True,widget=forms.Textarea)
|
||||
@@ -139,10 +141,10 @@ class CourseForm(forms.Form):
|
||||
class DocumentsForm(forms.Form):
|
||||
title = forms.CharField(required=False)
|
||||
file = forms.FileField(required=False,
|
||||
validators=[validate_file_extension])
|
||||
validators=[validate_file_extension])
|
||||
|
||||
workouttype = forms.ChoiceField(required=True,
|
||||
choices=Workout.workouttypes)
|
||||
choices=Workout.workouttypes)
|
||||
|
||||
boattype = forms.ChoiceField(required=True,
|
||||
choices=mytypes.boattypes,
|
||||
@@ -150,19 +152,19 @@ class DocumentsForm(forms.Form):
|
||||
|
||||
|
||||
notes = forms.CharField(required=False,
|
||||
widget=forms.Textarea)
|
||||
widget=forms.Textarea)
|
||||
|
||||
offline = forms.BooleanField(initial=False,required=False,
|
||||
label='Process in Background')
|
||||
class Meta:
|
||||
fields = ['title','file','workouttype','boattype','fileformat','offline']
|
||||
fields = ['title','file','workouttype','boattype','fileformat','offline']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
from django.forms.widgets import HiddenInput
|
||||
super(DocumentsForm, self).__init__(*args, **kwargs)
|
||||
# self.fields['offline'].widget = HiddenInput()
|
||||
|
||||
from utils import (
|
||||
from rowers.utils import (
|
||||
workflowleftpanel,workflowmiddlepanel,
|
||||
defaultleft,defaultmiddle
|
||||
)
|
||||
@@ -267,14 +269,14 @@ class LandingPageForm(forms.Form):
|
||||
|
||||
class UploadOptionsForm(forms.Form):
|
||||
plotchoices = (
|
||||
('timeplot','Time Plot'),
|
||||
('distanceplot','Distance Plot'),
|
||||
('pieplot','Heart Rate Pie Chart'),
|
||||
)
|
||||
('timeplot','Time Plot'),
|
||||
('distanceplot','Distance Plot'),
|
||||
('pieplot','Heart Rate Pie Chart'),
|
||||
)
|
||||
make_plot = forms.BooleanField(initial=False,required=False)
|
||||
plottype = forms.ChoiceField(required=False,
|
||||
choices=plotchoices,
|
||||
initial='timeplot',
|
||||
choices=plotchoices,
|
||||
initial='timeplot',
|
||||
label='Plot Type')
|
||||
upload_to_C2 = forms.BooleanField(initial=False,required=False,
|
||||
label='Export to Concept2 logbook')
|
||||
@@ -303,7 +305,7 @@ class UploadOptionsForm(forms.Form):
|
||||
label='After Upload, go to')
|
||||
|
||||
class Meta:
|
||||
fields = ['make_plot','plottype','upload_toc2','makeprivate']
|
||||
fields = ['make_plot','plottype','upload_toc2','makeprivate']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.request = kwargs.pop('request',None)
|
||||
@@ -332,18 +334,18 @@ class UploadOptionsForm(forms.Form):
|
||||
# a team member
|
||||
class TeamUploadOptionsForm(forms.Form):
|
||||
plotchoices = (
|
||||
('timeplot','Time Plot'),
|
||||
('distanceplot','Distance Plot'),
|
||||
('pieplot','Pie Chart'),
|
||||
)
|
||||
('timeplot','Time Plot'),
|
||||
('distanceplot','Distance Plot'),
|
||||
('pieplot','Pie Chart'),
|
||||
)
|
||||
make_plot = forms.BooleanField(initial=False,required=False)
|
||||
plottype = forms.ChoiceField(required=False,
|
||||
choices=plotchoices,
|
||||
initial='timeplot',
|
||||
choices=plotchoices,
|
||||
initial='timeplot',
|
||||
label='Plot Type')
|
||||
|
||||
class Meta:
|
||||
fields = ['make_plot','plottype']
|
||||
fields = ['make_plot','plottype']
|
||||
|
||||
# This form is used on the Workout Split page
|
||||
class WorkoutSplitForm(forms.Form):
|
||||
@@ -392,9 +394,9 @@ class OteWorkoutTypeForm(forms.Form):
|
||||
|
||||
class PredictedPieceForm(forms.Form):
|
||||
unitchoices = (
|
||||
('t','minutes'),
|
||||
('d','meters'),
|
||||
)
|
||||
('t','minutes'),
|
||||
('d','meters'),
|
||||
)
|
||||
|
||||
rankingdistancechoices = []
|
||||
rankingdurationchoices = []
|
||||
@@ -422,10 +424,10 @@ class PredictedPieceForm(forms.Form):
|
||||
|
||||
value = forms.FloatField(initial=10,label='Free ranking piece (minutes)')
|
||||
pieceunit = forms.ChoiceField(required=True,choices=unitchoices,
|
||||
initial='t',label='Unit')
|
||||
initial='t',label='Unit')
|
||||
|
||||
class Meta:
|
||||
fields = ['value','pieceunit']
|
||||
fields = ['value','pieceunit']
|
||||
|
||||
class PredictedPieceFormNoDistance(forms.Form):
|
||||
|
||||
@@ -450,76 +452,76 @@ class PredictedPieceFormNoDistance(forms.Form):
|
||||
# On the Geeky side, to update stream information for river dwellers
|
||||
class UpdateStreamForm(forms.Form):
|
||||
unitchoices = (
|
||||
('m','m/s'),
|
||||
('f','foot/s'),
|
||||
('k','knots'),
|
||||
('p','pace difference (sec/500m)'),
|
||||
)
|
||||
('m','m/s'),
|
||||
('f','foot/s'),
|
||||
('k','knots'),
|
||||
('p','pace difference (sec/500m)'),
|
||||
)
|
||||
dist1 = forms.FloatField(initial=0,label = 'Distance 1')
|
||||
dist2 = forms.FloatField(initial=1000,label = 'Distance 2')
|
||||
stream1 = forms.FloatField(initial=0,label = 'Stream velocity 1')
|
||||
stream2 = forms.FloatField(initial=0,label = 'Stream velocity 2')
|
||||
streamunit = forms.ChoiceField(required=True,
|
||||
choices=unitchoices,
|
||||
initial='m',
|
||||
label='Unit')
|
||||
choices=unitchoices,
|
||||
initial='m',
|
||||
label='Unit')
|
||||
|
||||
class Meta:
|
||||
fields = ['dist1','dist2','stream1', 'stream2','streamunit']
|
||||
fields = ['dist1','dist2','stream1', 'stream2','streamunit']
|
||||
|
||||
# add wind information to your workout
|
||||
class UpdateWindForm(forms.Form):
|
||||
unitchoices = (
|
||||
('m','m/s'),
|
||||
('k','knots'),
|
||||
('b','beaufort'),
|
||||
('kmh','km/h'),
|
||||
('mph','miles/hour'),
|
||||
)
|
||||
('m','m/s'),
|
||||
('k','knots'),
|
||||
('b','beaufort'),
|
||||
('kmh','km/h'),
|
||||
('mph','miles/hour'),
|
||||
)
|
||||
dist1 = forms.FloatField(initial=0,label = 'Distance 1')
|
||||
dist2 = forms.FloatField(initial=1000,label = 'Distance 2')
|
||||
vwind1 = forms.FloatField(initial=0,required=False,label = 'Wind Speed 1')
|
||||
vwind2 = forms.FloatField(initial=0,required=False,label = 'Wind Speed 2')
|
||||
windunit = forms.ChoiceField(required=True,
|
||||
choices=unitchoices,
|
||||
initial='m',
|
||||
label='Unit')
|
||||
choices=unitchoices,
|
||||
initial='m',
|
||||
label='Unit')
|
||||
winddirection1 = forms.IntegerField(initial=0,required=False,
|
||||
label = 'Wind Direction 1')
|
||||
label = 'Wind Direction 1')
|
||||
winddirection2 = forms.IntegerField(initial=0,required=False,
|
||||
label = 'Wind Direction 2')
|
||||
label = 'Wind Direction 2')
|
||||
|
||||
class Meta:
|
||||
fields = ['dist1','dist2',
|
||||
'vwind1','vwind2',
|
||||
'windunit',
|
||||
'winddirection1','winddirection2']
|
||||
fields = ['dist1','dist2',
|
||||
'vwind1','vwind2',
|
||||
'windunit',
|
||||
'winddirection1','winddirection2']
|
||||
|
||||
# Form to select a data range to show workouts from a certain time period
|
||||
class DateRangeForm(forms.Form):
|
||||
startdate = forms.DateField(
|
||||
initial=timezone.now()-datetime.timedelta(days=365),
|
||||
# widget=SelectDateWidget(years=range(1990,2050)),
|
||||
# widget=SelectDateWidget(years=range(1990,2050)),
|
||||
widget=AdminDateWidget(),
|
||||
label='Start Date')
|
||||
label='Start Date')
|
||||
enddate = forms.DateField(
|
||||
initial=timezone.now(),
|
||||
widget=AdminDateWidget(),
|
||||
label='End Date')
|
||||
label='End Date')
|
||||
|
||||
class Meta:
|
||||
fields = ['startdate','enddate']
|
||||
fields = ['startdate','enddate']
|
||||
|
||||
class FitnessMetricForm(forms.Form):
|
||||
startdate = forms.DateField(
|
||||
initial=timezone.now()-datetime.timedelta(days=365),
|
||||
# widget=SelectDateWidget(years=range(1990,2050)),
|
||||
# widget=SelectDateWidget(years=range(1990,2050)),
|
||||
widget=AdminDateWidget(),
|
||||
label='Start Date')
|
||||
label='Start Date')
|
||||
enddate = forms.DateField(
|
||||
initial=timezone.now(),
|
||||
widget=AdminDateWidget(),
|
||||
label='End Date')
|
||||
label='End Date')
|
||||
|
||||
modechoices = (
|
||||
('rower','indoor rower'),
|
||||
@@ -533,7 +535,7 @@ class FitnessMetricForm(forms.Form):
|
||||
)
|
||||
|
||||
class Meta:
|
||||
fields = ['startdate','enddate','mode']
|
||||
fields = ['startdate','enddate','mode']
|
||||
|
||||
class SessionDateShiftForm(forms.Form):
|
||||
shiftstartdate = forms.DateField(
|
||||
@@ -599,7 +601,7 @@ class RegistrationFormSex(RegistrationFormUniqueEmail):
|
||||
|
||||
weightcategories = (
|
||||
('hwt','heavy-weight'),
|
||||
('lwt','light-weight'),
|
||||
('lwt','light-weight'),
|
||||
)
|
||||
|
||||
adaptivecategories = mytypes.adaptivetypes
|
||||
@@ -637,8 +639,8 @@ class RegistrationFormSex(RegistrationFormUniqueEmail):
|
||||
class MyTimeField(forms.TimeField):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(MyTimeField, self).__init__(*args, **kwargs)
|
||||
supports_microseconds = True
|
||||
super(MyTimeField, self).__init__(*args, **kwargs)
|
||||
supports_microseconds = True
|
||||
|
||||
# Form used to automatically define intervals by pace or power
|
||||
class PowerIntervalUpdateForm(forms.Form):
|
||||
@@ -660,28 +662,28 @@ class PowerIntervalUpdateForm(forms.Form):
|
||||
class IntervalUpdateForm(forms.Form):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
typechoices = (
|
||||
(1,'single time'),
|
||||
(2,'single distance'),
|
||||
(3,'rest (time based)'),
|
||||
(3,'rest (distance based)'),
|
||||
(4,'work (time based)'),
|
||||
(5,'work (distance based)'),
|
||||
)
|
||||
aantal = int(kwargs.pop('aantal'))
|
||||
super(IntervalUpdateForm, self).__init__(*args, **kwargs)
|
||||
typechoices = (
|
||||
(1,'single time'),
|
||||
(2,'single distance'),
|
||||
(3,'rest (time based)'),
|
||||
(3,'rest (distance based)'),
|
||||
(4,'work (time based)'),
|
||||
(5,'work (distance based)'),
|
||||
)
|
||||
aantal = int(kwargs.pop('aantal'))
|
||||
super(IntervalUpdateForm, self).__init__(*args, **kwargs)
|
||||
|
||||
for i in range(aantal):
|
||||
self.fields['intervalt_%s' % i] = forms.DurationField(label='Time '+str(i+1))
|
||||
self.fields['intervald_%s' % i] = forms.IntegerField(label='Distance '+str(i+1))
|
||||
self.fields['type_%s' % i] = forms.ChoiceField(choices=typechoices,
|
||||
required=True,
|
||||
initial=4,
|
||||
label = 'Type '+str(i+1))
|
||||
self.fields['intervalt_%s' % i].widget.attrs['style'] = 'width:76px; height: 16px;'
|
||||
self.fields['intervald_%s' % i].widget.attrs['style'] = 'width:76px; height: 16px;'
|
||||
self.fields['type_%s' % i].widget.attrs['style'] = 'width:156px; height: 22px;'
|
||||
self.fields['intervald_%s' % i].widget = forms.TimeInput(format='%H:%M:%S.%f')
|
||||
for i in range(aantal):
|
||||
self.fields['intervalt_%s' % i] = forms.DurationField(label='Time '+str(i+1))
|
||||
self.fields['intervald_%s' % i] = forms.IntegerField(label='Distance '+str(i+1))
|
||||
self.fields['type_%s' % i] = forms.ChoiceField(choices=typechoices,
|
||||
required=True,
|
||||
initial=4,
|
||||
label = 'Type '+str(i+1))
|
||||
self.fields['intervalt_%s' % i].widget.attrs['style'] = 'width:76px; height: 16px;'
|
||||
self.fields['intervald_%s' % i].widget.attrs['style'] = 'width:76px; height: 16px;'
|
||||
self.fields['type_%s' % i].widget.attrs['style'] = 'width:156px; height: 22px;'
|
||||
self.fields['intervald_%s' % i].widget = forms.TimeInput(format='%H:%M:%S.%f')
|
||||
|
||||
boattypes = mytypes.boattypes
|
||||
workouttypes = mytypes.workouttypes
|
||||
@@ -824,7 +826,7 @@ formaxlabelsmultiflex.pop('distance')
|
||||
formaxlabelsmultiflex['workoutid'] = 'Workout'
|
||||
parchoicesmultiflex = list(sorted(formaxlabelsmultiflex.items(), key = lambda x:x[1]))
|
||||
|
||||
from utils import palettes
|
||||
from rowers.utils import palettes
|
||||
|
||||
palettechoices = tuple((p,p) for p in palettes.keys())
|
||||
|
||||
@@ -950,7 +952,7 @@ class RaceResultFilterForm(forms.Form):
|
||||
|
||||
weightcategories = (
|
||||
('hwt','heavy-weight'),
|
||||
('lwt','light-weight'),
|
||||
('lwt','light-weight'),
|
||||
)
|
||||
|
||||
adaptivecategories = mytypes.adaptivetypes
|
||||
|
||||
+27
-27
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the functionality to connect to SportTracks
|
||||
|
||||
# Python
|
||||
@@ -16,7 +17,7 @@ from dateutil import parser
|
||||
import time
|
||||
from time import strftime
|
||||
|
||||
import dataprep
|
||||
import rowers.dataprep as dataprep
|
||||
import math
|
||||
from math import sin,cos,atan2,sqrt
|
||||
import os,sys
|
||||
@@ -38,7 +39,7 @@ from django.contrib.auth.decorators import login_required
|
||||
from rowingdata import rowingdata, make_cumvalues
|
||||
import pandas as pd
|
||||
from rowers.models import Rower,Workout,checkworkoutuser
|
||||
from rowers import mytypes
|
||||
import rowers.mytypes as mytypes
|
||||
from rowsandall_app.settings import (
|
||||
C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET,
|
||||
STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI,
|
||||
@@ -46,7 +47,7 @@ from rowsandall_app.settings import (
|
||||
SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI
|
||||
)
|
||||
|
||||
from utils import (
|
||||
from rowers.utils import (
|
||||
NoTokenError, custom_exception_handler, ewmovingaverage,
|
||||
geo_distance,isprorower,uniqify
|
||||
)
|
||||
@@ -59,9 +60,9 @@ def splitstdata(lijst):
|
||||
t = []
|
||||
latlong = []
|
||||
while len(lijst)>=2:
|
||||
t.append(lijst[0])
|
||||
latlong.append(lijst[1])
|
||||
lijst = lijst[2:]
|
||||
t.append(lijst[0])
|
||||
latlong.append(lijst[1])
|
||||
lijst = lijst[2:]
|
||||
|
||||
return [np.array(t),np.array(latlong)]
|
||||
|
||||
@@ -103,7 +104,6 @@ def imports_open(user,oauth_data):
|
||||
oauth_data,
|
||||
)
|
||||
elif tokenexpirydate is None and expirydatename is not None and 'strava' in expirydatename:
|
||||
print 'noot'
|
||||
token = imports_token_refresh(
|
||||
user,
|
||||
tokenname,
|
||||
@@ -124,13 +124,13 @@ def imports_do_refresh_token(refreshtoken,oauth_data,access_token=''):
|
||||
)
|
||||
|
||||
post_data = {"grant_type": "refresh_token",
|
||||
"client_secret": oauth_data['client_secret'],
|
||||
"client_id": oauth_data['client_id'],
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
"client_secret": oauth_data['client_secret'],
|
||||
"client_id": oauth_data['client_id'],
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': oauth_data['content_type']}
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': oauth_data['content_type']}
|
||||
|
||||
# for Strava
|
||||
if 'grant_type' in oauth_data:
|
||||
@@ -147,11 +147,11 @@ def imports_do_refresh_token(refreshtoken,oauth_data,access_token=''):
|
||||
if 'json' in oauth_data['content_type']:
|
||||
response = requests.post(baseurl,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
headers=headers)
|
||||
else:
|
||||
response = requests.post(baseurl,
|
||||
data=post_data,
|
||||
headers=headers)
|
||||
headers=headers)
|
||||
|
||||
|
||||
|
||||
@@ -174,9 +174,9 @@ def imports_do_refresh_token(refreshtoken,oauth_data,access_token=''):
|
||||
except KeyError:
|
||||
expires_in = 0
|
||||
try:
|
||||
refresh_token = token_json['refresh_token']
|
||||
refresh_token = token_json['refresh_token']
|
||||
except KeyError:
|
||||
refresh_token = refreshtoken
|
||||
refresh_token = refreshtoken
|
||||
try:
|
||||
expires_in = int(expires_in)
|
||||
except (TypeError,ValueError):
|
||||
@@ -204,16 +204,16 @@ def imports_get_token(
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": redirect_uri,
|
||||
"client_secret": client_secret,
|
||||
"client_id": client_id,
|
||||
}
|
||||
"client_secret": client_secret,
|
||||
"client_id": client_id,
|
||||
}
|
||||
|
||||
try:
|
||||
headers = oauth_data['headers']
|
||||
except KeyError:
|
||||
headers = {'Accept': 'application/json',
|
||||
'Api-Key': client_id,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'user-agent': 'sanderroosendaal'}
|
||||
|
||||
if 'grant_type' in oauth_data:
|
||||
@@ -229,12 +229,12 @@ def imports_get_token(
|
||||
response = requests.post(
|
||||
base_uri,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
headers=headers)
|
||||
else:
|
||||
response = requests.post(
|
||||
base_uri,
|
||||
data=post_data,
|
||||
headers=headers)
|
||||
headers=headers)
|
||||
|
||||
if response.status_code == 200 or response.status_code == 201:
|
||||
token_json = response.json()
|
||||
@@ -243,9 +243,9 @@ def imports_get_token(
|
||||
except KeyError:
|
||||
return [0,0,0]
|
||||
try:
|
||||
refresh_token = token_json['refresh_token']
|
||||
refresh_token = token_json['refresh_token']
|
||||
except KeyError:
|
||||
refresh_token = ''
|
||||
refresh_token = ''
|
||||
try:
|
||||
expires_in = token_json['expires_in']
|
||||
except KeyError:
|
||||
@@ -270,8 +270,8 @@ def imports_make_authorization_url(oauth_data):
|
||||
params = {"client_id": oauth_data['client_id'],
|
||||
"response_type": "code",
|
||||
"redirect_uri": oauth_data['redirect_uri'],
|
||||
"scope":oauth_data['scope'],
|
||||
"state":state}
|
||||
"scope":oauth_data['scope'],
|
||||
"state":state}
|
||||
|
||||
|
||||
import urllib
|
||||
|
||||
+649
-649
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -72,7 +72,7 @@ def longtask2(aantal,jobid=None,debug=False,secret=''):
|
||||
counter = 0
|
||||
progress = int(100.*i/aantal)
|
||||
if debug:
|
||||
print progress
|
||||
print(progress)
|
||||
if jobid != None:
|
||||
if debug:
|
||||
url = SITE_URL_DEV
|
||||
@@ -83,8 +83,8 @@ def longtask2(aantal,jobid=None,debug=False,secret=''):
|
||||
post_data = {"secret":secret}
|
||||
s = requests.post(url, data=post_data)
|
||||
if debug:
|
||||
print url
|
||||
print s
|
||||
print(url)
|
||||
print(s)
|
||||
|
||||
|
||||
return 1
|
||||
|
||||
@@ -92,7 +92,7 @@ def make_new_workout_from_email(rower, datafile, name, cntr=0,testing=False):
|
||||
fileformat = fileformat[2]
|
||||
|
||||
if testing:
|
||||
print 'Fileformat = ',fileformat
|
||||
print('Fileformat = ',fileformat)
|
||||
|
||||
if fileformat == 'unknown':
|
||||
# extension = datafilename[-4:].lower()
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
from utils import lbstoN
|
||||
from __future__ import absolute_import
|
||||
from rowers.utils import lbstoN
|
||||
import numpy as np
|
||||
from models import C2WorldClassAgePerformance
|
||||
from rowers.models import C2WorldClassAgePerformance
|
||||
import pandas as pd
|
||||
from scipy import optimize
|
||||
from django.utils import timezone
|
||||
|
||||
+236
-236
File diff suppressed because it is too large
Load Diff
+7
-5
@@ -1,3 +1,5 @@
|
||||
from six import iteritems
|
||||
|
||||
workouttypes = (
|
||||
('water','Standard Racing Shell'),
|
||||
('rower','Indoor Rower'),
|
||||
@@ -208,15 +210,15 @@ c2mapping = {
|
||||
|
||||
}
|
||||
|
||||
c2mappinginv = {value:key for key,value in c2mapping.iteritems() if value is not None}
|
||||
c2mappinginv = {value:key for key,value in iteritems(c2mapping) if value is not None}
|
||||
|
||||
stravamappinginv = {value:key for key,value in stravamapping.iteritems() if value is not None}
|
||||
stravamappinginv = {value:key for key,value in iteritems(stravamapping) if value is not None}
|
||||
|
||||
stmappinginv = {value:key for key,value in stmapping.iteritems() if value is not None}
|
||||
stmappinginv = {value:key for key,value in iteritems(stmapping) if value is not None}
|
||||
|
||||
rkmappinginv = {value:key for key,value in rkmapping.iteritems() if value is not None}
|
||||
rkmappinginv = {value:key for key,value in iteritems(rkmapping) if value is not None}
|
||||
|
||||
polarmappinginv = {value:key for key,value in polarmapping.iteritems() if value is not None}
|
||||
polarmappinginv = {value:key for key,value in iteritems(polarmapping) if value is not None}
|
||||
|
||||
otwtypes = (
|
||||
'water',
|
||||
|
||||
+94
-93
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# Interactions with Rowsandall.com API. Not fully complete.
|
||||
|
||||
# Python
|
||||
@@ -15,7 +16,7 @@ import math
|
||||
from math import sin,cos,atan2,sqrt
|
||||
|
||||
import urllib
|
||||
import c2stuff
|
||||
import rowers.c2stuff as c2stuff
|
||||
|
||||
# Django
|
||||
from django.shortcuts import render_to_response
|
||||
@@ -41,13 +42,13 @@ TEST_REDIRECT_URI = "http://localhost:8000/rowers/test_callback"
|
||||
def custom_exception_handler(exc,message):
|
||||
|
||||
response = {
|
||||
"errors": [
|
||||
{
|
||||
"code": str(exc),
|
||||
"detail": message,
|
||||
}
|
||||
]
|
||||
}
|
||||
"errors": [
|
||||
{
|
||||
"code": str(exc),
|
||||
"detail": message,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
res = HttpResponse(message)
|
||||
res.status_code = 401
|
||||
@@ -58,27 +59,27 @@ def custom_exception_handler(exc,message):
|
||||
def do_refresh_token(refreshtoken):
|
||||
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,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
"client_secret": TEST_CLIENT_SECRET,
|
||||
"client_id":TEST_CLIENT_ID,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
'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)
|
||||
headers=headers)
|
||||
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
try:
|
||||
refresh_token = token_json['refresh_token']
|
||||
refresh_token = token_json['refresh_token']
|
||||
except KeyError:
|
||||
refresh_token = refreshtoken
|
||||
refresh_token = refreshtoken
|
||||
|
||||
return [thetoken,expires_in,refresh_token]
|
||||
|
||||
@@ -88,18 +89,18 @@ def get_token(code):
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": "http://localhost:8000/rowers/test_callback",
|
||||
"client_secret": "aapnootmies",
|
||||
"client_id":1,
|
||||
}
|
||||
"client_secret": "aapnootmies",
|
||||
"client_id":1,
|
||||
}
|
||||
headers = {'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "http://localhost:8000/rowers/o/token/"
|
||||
|
||||
|
||||
response = requests.post(url,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
headers=headers)
|
||||
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
@@ -118,8 +119,8 @@ def make_authorization_url(request):
|
||||
params = {"client_id": TEST_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"redirect_uri": TEST_REDIRECT_URI,
|
||||
"scope":"write",
|
||||
"state":state}
|
||||
"scope":"write",
|
||||
"state":state}
|
||||
|
||||
|
||||
import urllib
|
||||
@@ -147,19 +148,19 @@ def rower_ownapi_token_refresh(user):
|
||||
def get_ownapi_workout_list(user):
|
||||
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)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -167,19 +168,19 @@ def get_ownapi_workout_list(user):
|
||||
def get_ownapi_workout(user,ownapiid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities/"+str(ownapiid)
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities/"+str(ownapiid)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -203,16 +204,16 @@ def createownapiworkoutdata(w):
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
haslatlon = 0
|
||||
|
||||
haspower = 1
|
||||
try:
|
||||
power = row.df[' Power (watts)'].values
|
||||
power = row.df[' Power (watts)'].values
|
||||
except KeyError:
|
||||
haspower = 0
|
||||
haspower = 0
|
||||
|
||||
locdata = []
|
||||
hrdata = []
|
||||
@@ -221,54 +222,54 @@ def createownapiworkoutdata(w):
|
||||
powerdata = []
|
||||
|
||||
for i in range(len(t)):
|
||||
hrdata.append(t[i])
|
||||
hrdata.append(hr[i])
|
||||
distancedata.append(t[i])
|
||||
distancedata.append(d[i])
|
||||
spmdata.append(t[i])
|
||||
spmdata.append(spm[i])
|
||||
if haslatlon:
|
||||
locdata.append(t[i])
|
||||
locdata.append([lat[i],lon[i]])
|
||||
if haspower:
|
||||
powerdata.append(t[i])
|
||||
powerdata.append(power[i])
|
||||
hrdata.append(t[i])
|
||||
hrdata.append(hr[i])
|
||||
distancedata.append(t[i])
|
||||
distancedata.append(d[i])
|
||||
spmdata.append(t[i])
|
||||
spmdata.append(spm[i])
|
||||
if haslatlon:
|
||||
locdata.append(t[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": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"location": locdata,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"location": locdata,
|
||||
"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": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
|
||||
if haspower:
|
||||
data['power'] = powerdata
|
||||
data['power'] = powerdata
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# Python
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
@@ -10,7 +11,7 @@ import uuid
|
||||
from django.conf import settings
|
||||
import pytz
|
||||
from dateutil import parser
|
||||
from utils import myqueue,calculate_age,totaltime_sec_to_string
|
||||
from rowers.utils import myqueue,calculate_age,totaltime_sec_to_string
|
||||
import re
|
||||
import django_rq
|
||||
queue = django_rq.get_queue('default')
|
||||
@@ -30,10 +31,10 @@ from rowers.emails import htmlstrip,htmlstripnobr
|
||||
|
||||
import rowers.mytypes as mytypes
|
||||
|
||||
import metrics
|
||||
import rowers.metrics as metrics
|
||||
import numpy as np
|
||||
import dataprep
|
||||
import courses
|
||||
import rowers.dataprep as dataprep
|
||||
import rowers.courses as courses
|
||||
import iso8601
|
||||
from iso8601 import ParseError
|
||||
from rowers.tasks import handle_check_race_course
|
||||
|
||||
+20
-20
@@ -2,14 +2,14 @@ from matplotlib.ticker import MultipleLocator,FuncFormatter,NullFormatter
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
import numpy as np
|
||||
from rows import format_pace_tick, format_pace, format_time, format_time_tick
|
||||
from rowers.rows import format_pace_tick, format_pace, format_time, format_time_tick
|
||||
|
||||
|
||||
# Formatting the distance tick marks
|
||||
#def format_dist_tick(x,pos=None):
|
||||
# km = x/1000.
|
||||
# template='%6.3f'
|
||||
# return template % (km)
|
||||
# km = x/1000.
|
||||
# template='%6.3f'
|
||||
# return template % (km)
|
||||
|
||||
|
||||
# Utility to select reasonable y axis range
|
||||
@@ -32,23 +32,23 @@ def y_axis_range(ydata,miny=0,padding=.1,ultimate=[-1e9,1e9]):
|
||||
|
||||
|
||||
if (yrange == 0):
|
||||
if ymin == 0:
|
||||
yrangemin = -padding
|
||||
else:
|
||||
yrangemin = ymin-ymin*padding
|
||||
if ymax == 0:
|
||||
yrangemax = padding
|
||||
else:
|
||||
yrangemax = ymax+ymax*padding
|
||||
if ymin == 0:
|
||||
yrangemin = -padding
|
||||
else:
|
||||
yrangemin = ymin-ymin*padding
|
||||
if ymax == 0:
|
||||
yrangemax = padding
|
||||
else:
|
||||
yrangemax = ymax+ymax*padding
|
||||
else:
|
||||
yrangemin = ymin-padding*yrange
|
||||
yrangemax = ymax+padding*yrange
|
||||
yrangemin = ymin-padding*yrange
|
||||
yrangemax = ymax+padding*yrange
|
||||
|
||||
if (yrangemin < ultimate[0]):
|
||||
yrangemin = ultimate[0]
|
||||
yrangemin = ultimate[0]
|
||||
|
||||
if (yrangemax > ultimate[1]):
|
||||
yrangemax = ultimate[1]
|
||||
yrangemax = ultimate[1]
|
||||
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ def mkplot(row,title):
|
||||
ax1.set_ylabel('(sec/500)')
|
||||
|
||||
yrange = y_axis_range(df.loc[:,' Stroke500mPace (sec/500m)'],
|
||||
ultimate = [85,190])
|
||||
ultimate = [85,190])
|
||||
plt.axis([0,end_time,yrange[1],yrange[0]])
|
||||
|
||||
ax1.set_xticks(range(1000,end_time,1000))
|
||||
@@ -80,11 +80,11 @@ def mkplot(row,title):
|
||||
majorFormatter = FuncFormatter(format_pace_tick)
|
||||
majorLocator = (5)
|
||||
timeTickFormatter = NullFormatter()
|
||||
|
||||
|
||||
ax1.yaxis.set_major_formatter(majorFormatter)
|
||||
|
||||
for tl in ax1.get_yticklabels():
|
||||
tl.set_color('b')
|
||||
tl.set_color('b')
|
||||
|
||||
ax2 = ax1.twinx()
|
||||
ax2.plot(t,hr,'r-')
|
||||
@@ -94,7 +94,7 @@ def mkplot(row,title):
|
||||
ax2.xaxis.set_major_formatter(majorTimeFormatter)
|
||||
ax2.patch.set_alpha(0.0)
|
||||
for tl in ax2.get_yticklabels():
|
||||
tl.set_color('r')
|
||||
tl.set_color('r')
|
||||
|
||||
plt.subplots_adjust(hspace=0)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the functionality needed to connect to Strava
|
||||
|
||||
# Python
|
||||
@@ -33,8 +34,8 @@ from rowingdata import rowingdata
|
||||
import pandas as pd
|
||||
from rowers.models import Rower,Workout
|
||||
from rowers.models import checkworkoutuser
|
||||
import dataprep
|
||||
from dataprep import columndict
|
||||
import rowers.dataprep as dataprep
|
||||
from rowers.dataprep import columndict
|
||||
|
||||
from io import StringIO
|
||||
|
||||
@@ -51,8 +52,8 @@ from rowsandall_app.settings import (
|
||||
baseurl = 'https://polaraccesslink.com/v3'
|
||||
|
||||
|
||||
from utils import NoTokenError, custom_exception_handler
|
||||
import mytypes
|
||||
from rowers.utils import NoTokenError, custom_exception_handler
|
||||
import rowers.mytypes as mytypes
|
||||
|
||||
# Exchange access code for long-lived access token
|
||||
def get_token(code):
|
||||
@@ -126,7 +127,7 @@ from rowers.utils import isprorower
|
||||
def get_all_new_workouts(available_data,testing=False):
|
||||
for record in available_data:
|
||||
if testing:
|
||||
print record
|
||||
print(record)
|
||||
if record['data-type'] == 'EXERCISE':
|
||||
try:
|
||||
r = Rower.objects.get(polaruserid=record['user-id'])
|
||||
@@ -134,7 +135,7 @@ def get_all_new_workouts(available_data,testing=False):
|
||||
if r.polar_auto_import and isprorower(r):
|
||||
exercise_list = get_polar_workouts(u)
|
||||
if testing:
|
||||
print exercise_list
|
||||
print(exercise_list)
|
||||
except Rower.DoesNotExist:
|
||||
pass
|
||||
|
||||
@@ -313,8 +314,6 @@ def get_polar_workout(user,id,transactionid):
|
||||
response = requests.get(url,headers = headers2)
|
||||
|
||||
if response.status_code == 200:
|
||||
print response.text
|
||||
|
||||
result = response.text
|
||||
# commit transaction
|
||||
response = requests.put(url,headers=headers)
|
||||
|
||||
+22
-22
@@ -6,29 +6,29 @@ from django.core.exceptions import ValidationError
|
||||
|
||||
def format_pace_tick(x,pos=None):
|
||||
minu=int(x/60)
|
||||
sec=int(x-minu*60.)
|
||||
sec_str=str(sec).zfill(2)
|
||||
template='%d:%s'
|
||||
return template % (minu,sec_str)
|
||||
sec=int(x-minu*60.)
|
||||
sec_str=str(sec).zfill(2)
|
||||
template='%d:%s'
|
||||
return template % (minu,sec_str)
|
||||
|
||||
def format_time_tick(x,pos=None):
|
||||
hour=int(x/3600)
|
||||
min=int((x-hour*3600.)/60)
|
||||
min_str=str(min).zfill(2)
|
||||
template='%d:%s'
|
||||
return template % (hour,min_str)
|
||||
hour=int(x/3600)
|
||||
min=int((x-hour*3600.)/60)
|
||||
min_str=str(min).zfill(2)
|
||||
template='%d:%s'
|
||||
return template % (hour,min_str)
|
||||
|
||||
def format_pace(x,pos=None):
|
||||
if isinf(x) or isnan(x):
|
||||
x=0
|
||||
|
||||
x=0
|
||||
|
||||
min=int(x/60)
|
||||
sec=(x-min*60.)
|
||||
|
||||
str1 = "{min:0>2}:{sec:0>4.1f}".format(
|
||||
min = min,
|
||||
sec = sec
|
||||
)
|
||||
min = min,
|
||||
sec = sec
|
||||
)
|
||||
|
||||
return str1
|
||||
|
||||
@@ -39,9 +39,9 @@ def format_time(x,pos=None):
|
||||
sec = int(x-min*60)
|
||||
|
||||
str1 = "{min:0>2}:{sec:0>4.1f}".format(
|
||||
min=min,
|
||||
sec=sec,
|
||||
)
|
||||
min=min,
|
||||
sec=sec,
|
||||
)
|
||||
|
||||
return str1
|
||||
|
||||
@@ -67,14 +67,14 @@ def must_be_csv(value):
|
||||
ext = os.path.splitext(value.name)[1]
|
||||
valid_extensions = ['.csv','.CSV']
|
||||
if not ext in valid_extensions:
|
||||
raise ValidationError(u'File not supported!')
|
||||
raise ValidationError(u'File not supported!')
|
||||
|
||||
def validate_kml(value):
|
||||
import os
|
||||
ext = os.path.splitext(value.name)[1]
|
||||
valid_extensions = ['.kml','.KML']
|
||||
if not ext in valid_extensions:
|
||||
raise ValidationError(u'File not supported!')
|
||||
raise ValidationError(u'File not supported!')
|
||||
|
||||
|
||||
def handle_uploaded_image(i):
|
||||
@@ -83,7 +83,7 @@ def handle_uploaded_image(i):
|
||||
import os
|
||||
from django.core.files import File
|
||||
image_str = ""
|
||||
for chunk in i.chunks():
|
||||
for chunk in i.chunks():
|
||||
image_str += chunk
|
||||
|
||||
imagefile = StringIO.StringIO(image_str)
|
||||
@@ -133,8 +133,8 @@ def handle_uploaded_file(f):
|
||||
fname = timestr+'-'+fname
|
||||
fname2 = 'media/'+fname
|
||||
with open(fname2,'wb+') as destination:
|
||||
for chunk in f.chunks():
|
||||
destination.write(chunk)
|
||||
for chunk in f.chunks():
|
||||
destination.write(chunk)
|
||||
|
||||
return fname,fname2
|
||||
|
||||
|
||||
+113
-112
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the functionality needed to connect to Runkeeper
|
||||
from rowers.imports import *
|
||||
import re
|
||||
@@ -61,16 +62,16 @@ def make_authorization_url(request):
|
||||
def get_runkeeper_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.runkeepertoken == '') or (r.runkeepertoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.runkeepertoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.runkeepertoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -78,16 +79,16 @@ def get_runkeeper_workout_list(user):
|
||||
def get_workout(user,runkeeperid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.runkeepertoken == '') or (r.runkeepertoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.runkeepertoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.runkeeper.com/fitnessActivities/"+str(runkeeperid)
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.runkeepertoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.runkeeper.com/fitnessActivities/"+str(runkeeperid)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
try:
|
||||
data = s.json()
|
||||
@@ -131,12 +132,12 @@ def createrunkeeperworkoutdata(w):
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
if not lat.std() and not lon.std():
|
||||
haslatlon = 0
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
haslatlon = 0
|
||||
|
||||
# path data
|
||||
if haslatlon:
|
||||
@@ -172,32 +173,32 @@ def createrunkeeperworkoutdata(w):
|
||||
newnotes = 'from '+w.workoutsource+' via rowsandall.com'
|
||||
|
||||
if haslatlon:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"start_time": start_time,
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": newnotes,
|
||||
"average_heart_rate": averagehr,
|
||||
"path": locdata,
|
||||
"distance": distancedata,
|
||||
"heart_rate": hrdata,
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"start_time": start_time,
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": newnotes,
|
||||
"average_heart_rate": averagehr,
|
||||
"path": locdata,
|
||||
"distance": distancedata,
|
||||
"heart_rate": hrdata,
|
||||
"post_to_twitter":"false",
|
||||
"post_to_facebook":"false",
|
||||
}
|
||||
}
|
||||
else:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"start_time": start_time,
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": newnotes,
|
||||
"avg_heartrate": averagehr,
|
||||
"distance": distancedata,
|
||||
"heart_rate": hrdata,
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"start_time": start_time,
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": newnotes,
|
||||
"avg_heartrate": averagehr,
|
||||
"distance": distancedata,
|
||||
"heart_rate": hrdata,
|
||||
"post_to_twitter":"false",
|
||||
"post_to_facebook":"false",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return data
|
||||
@@ -215,8 +216,8 @@ def getidfromresponse(response):
|
||||
def geturifromid(access_token,id):
|
||||
authorizationstring = str('Bearer ' + access_token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://api.runkeeper.com/fitnessActivities/"+str(id)
|
||||
response = requests.get(url,headers=headers)
|
||||
@@ -238,8 +239,8 @@ def geturifromid(access_token,id):
|
||||
def get_userid(access_token):
|
||||
authorizationstring = str('Bearer ' + access_token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://api.runkeeper.com/user"
|
||||
response = requests.get(url,headers=headers)
|
||||
@@ -269,42 +270,42 @@ def workout_runkeeper_upload(user,w):
|
||||
# ready to upload. Hurray
|
||||
|
||||
if (checkworkoutuser(user,w)):
|
||||
data = createrunkeeperworkoutdata(w)
|
||||
data = createrunkeeperworkoutdata(w)
|
||||
if not data:
|
||||
message = "Data error in Runkeeper Upload"
|
||||
rkid = 0
|
||||
return message, rkid
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
|
||||
'Content-Length':'nnn'}
|
||||
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtorunkeeper = -1
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtorunkeeper = -1
|
||||
rkid = -1
|
||||
w.save()
|
||||
w.save()
|
||||
return message, rkid
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
rkid = getidfromresponse(response)
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
rkid = getidfromresponse(response)
|
||||
rkuri = geturifromid(thetoken,rkid)
|
||||
w.uploadedtorunkeeper = rkid
|
||||
w.save()
|
||||
w.uploadedtorunkeeper = rkid
|
||||
w.save()
|
||||
return 'Successfully synchronized to Runkeeper',rkid
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_runkeeper_upload_view: %s - %s" % (s.reason,s.text)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_runkeeper_upload_view: %s - %s" % (s.reason,s.text)
|
||||
rkid = 0
|
||||
return message, rkid
|
||||
|
||||
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
rkid = 0
|
||||
return message, rkid
|
||||
|
||||
@@ -316,41 +317,41 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
||||
# To Do - add utcoffset to time
|
||||
workouttype = data['type']
|
||||
if workouttype not in [x[0] for x in Workout.workouttypes]:
|
||||
workouttype = 'other'
|
||||
workouttype = 'other'
|
||||
try:
|
||||
comments = data['notes']
|
||||
comments = data['notes']
|
||||
except:
|
||||
comments = ''
|
||||
comments = ''
|
||||
|
||||
try:
|
||||
utcoffset = tz(data['utcoffset'])
|
||||
utcoffset = tz(data['utcoffset'])
|
||||
except:
|
||||
utcoffset = 0
|
||||
utcoffset = 0
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['start_time'])
|
||||
rowdatetime = iso8601.parse_date(data['start_time'])
|
||||
except iso8601.ParseError:
|
||||
try:
|
||||
rowdatetime = datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except ValueError:
|
||||
try:
|
||||
rowdatetime = parser.parse(data['start_time'])
|
||||
#rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
try:
|
||||
rowdatetime = datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except ValueError:
|
||||
try:
|
||||
rowdatetime = parser.parse(data['start_time'])
|
||||
#rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
#starttimeunix = mktime(rowdatetime.utctimetuple())
|
||||
starttimeunix += utcoffset*3600
|
||||
|
||||
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except:
|
||||
title = "Imported data"
|
||||
title = "Imported data"
|
||||
|
||||
|
||||
|
||||
@@ -360,35 +361,35 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
||||
times_distance = res[0]
|
||||
|
||||
try:
|
||||
l = data['path']
|
||||
l = data['path']
|
||||
|
||||
res = splitrunkeeperlatlongdata(l,'timestamp','latitude','longitude')
|
||||
times_location = res[0]
|
||||
latcoord = res[1]
|
||||
loncoord = res[2]
|
||||
res = splitrunkeeperlatlongdata(l,'timestamp','latitude','longitude')
|
||||
times_location = res[0]
|
||||
latcoord = res[1]
|
||||
loncoord = res[2]
|
||||
|
||||
except:
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
if workouttype in types.otwtypes:
|
||||
workouttype = 'rower'
|
||||
|
||||
|
||||
try:
|
||||
res = splitrunkeeperdata(data['cadence'],'timestamp','cadence')
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
res = splitrunkeeperdata(data['cadence'],'timestamp','cadence')
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
except KeyError:
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
|
||||
try:
|
||||
res = splitrunkeeperdata(data['heart_rate'],'timestamp','heart_rate')
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
res = splitrunkeeperdata(data['heart_rate'],'timestamp','heart_rate')
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
except KeyError:
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
|
||||
|
||||
# create data series and remove duplicates
|
||||
@@ -417,12 +418,12 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
||||
|
||||
# Create dicts and big dataframe
|
||||
d = {
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -469,7 +470,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper',
|
||||
df = df.fillna(0)
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
# csvfilename ='media/Import_'+str(importid)+'.csv'
|
||||
|
||||
+14
-15
@@ -74,20 +74,20 @@ class WorkoutSerializer(serializers.ModelSerializer):
|
||||
t.second)
|
||||
w = Workout(user=r,
|
||||
name=validated_data['name'],
|
||||
date=validated_data['date'],
|
||||
date=validated_data['date'],
|
||||
workouttype=validated_data['workouttype'],
|
||||
duration=validated_data['duration'],
|
||||
duration=validated_data['duration'],
|
||||
distance=validated_data['distance'],
|
||||
weightcategory=r.weightcategory,
|
||||
adaptiveclass=r.adaptiveclass,
|
||||
starttime=validated_data['starttime'],
|
||||
csvfilename='',
|
||||
weightcategory=r.weightcategory,
|
||||
adaptiveclass=r.adaptiveclass,
|
||||
starttime=validated_data['starttime'],
|
||||
csvfilename='',
|
||||
notes=validated_data['notes'],
|
||||
uploadedtoc2=0,
|
||||
uploadedtoc2=0,
|
||||
summary=validated_data['summary'],
|
||||
averagehr=validated_data['averagehr'],
|
||||
averagehr=validated_data['averagehr'],
|
||||
maxhr=validated_data['maxhr'],
|
||||
startdatetime=rowdatetime,
|
||||
startdatetime=rowdatetime,
|
||||
timezone=validated_data['timezone'],
|
||||
forceunit=validated_data['forceunit'],
|
||||
inboard=validated_data['inboard'],
|
||||
@@ -109,16 +109,16 @@ class WorkoutSerializer(serializers.ModelSerializer):
|
||||
|
||||
|
||||
instance.name=validated_data['name']
|
||||
instance.date=validated_data['date']
|
||||
instance.date=validated_data['date']
|
||||
instance.workouttype=validated_data['workouttype']
|
||||
instance.duration=validated_data['duration']
|
||||
instance.duration=validated_data['duration']
|
||||
instance.distance=validated_data['distance']
|
||||
instance.starttime=validated_data['starttime']
|
||||
instance.starttime=validated_data['starttime']
|
||||
instance.notes=validated_data['notes']
|
||||
instance.summary=validated_data['summary']
|
||||
instance.averagehr=validated_data['averagehr']
|
||||
instance.averagehr=validated_data['averagehr']
|
||||
instance.maxhr=validated_data['maxhr']
|
||||
instance.startdatetime=rowdatetime
|
||||
instance.startdatetime=rowdatetime
|
||||
instance.timezone=validated_data['timezone']
|
||||
instance.forceunit=validated_data['forceunit']
|
||||
instance.inboard=validated_data['inboard']
|
||||
@@ -140,7 +140,6 @@ class StrokeDataSerializer(serializers.Serializer):
|
||||
"""
|
||||
|
||||
# do something
|
||||
print "fake serializer"
|
||||
return 1
|
||||
|
||||
|
||||
|
||||
+139
-138
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the functionality to connect to SportTracks
|
||||
|
||||
from rowers.imports import *
|
||||
@@ -9,7 +10,7 @@ from rowsandall_app.settings import (
|
||||
SPORTTRACKS_REDIRECT_URI
|
||||
)
|
||||
|
||||
import mytypes
|
||||
import rowers.mytypes as mytypes
|
||||
|
||||
oauth_data = {
|
||||
'client_id': SPORTTRACKS_CLIENT_ID,
|
||||
@@ -64,19 +65,19 @@ def rower_sporttracks_token_refresh(user):
|
||||
def get_sporttracks_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.sporttrackstokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.sporttrackstoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.sporttrackstoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
@@ -84,19 +85,19 @@ def get_sporttracks_workout_list(user):
|
||||
def get_workout(user,sporttracksid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.sporttrackstokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.sporttrackstoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities/"+str(sporttracksid)
|
||||
s = requests.get(url,headers=headers)
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.sporttrackstoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities/"+str(sporttracksid)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
data = s.json()
|
||||
|
||||
@@ -139,19 +140,19 @@ def createsporttracksworkoutdata(w):
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
if not lat.std() and not lon.std():
|
||||
haslatlon = 0
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
haslatlon = 0
|
||||
|
||||
|
||||
haspower = 1
|
||||
try:
|
||||
power = row.df[' Power (watts)'].astype(int).values
|
||||
power = row.df[' Power (watts)'].astype(int).values
|
||||
except KeyError:
|
||||
haspower = 0
|
||||
haspower = 0
|
||||
|
||||
locdata = []
|
||||
hrdata = []
|
||||
@@ -160,18 +161,18 @@ def createsporttracksworkoutdata(w):
|
||||
powerdata = []
|
||||
|
||||
for i in range(len(t)):
|
||||
hrdata.append(t[i])
|
||||
hrdata.append(hr[i])
|
||||
distancedata.append(t[i])
|
||||
distancedata.append(d[i])
|
||||
spmdata.append(t[i])
|
||||
spmdata.append(spm[i])
|
||||
if haslatlon:
|
||||
locdata.append(t[i])
|
||||
locdata.append([lat[i],lon[i]])
|
||||
if haspower:
|
||||
powerdata.append(t[i])
|
||||
powerdata.append(power[i])
|
||||
hrdata.append(t[i])
|
||||
hrdata.append(hr[i])
|
||||
distancedata.append(t[i])
|
||||
distancedata.append(d[i])
|
||||
spmdata.append(t[i])
|
||||
spmdata.append(spm[i])
|
||||
if haslatlon:
|
||||
locdata.append(t[i])
|
||||
locdata.append([lat[i],lon[i]])
|
||||
if haspower:
|
||||
powerdata.append(t[i])
|
||||
powerdata.append(power[i])
|
||||
|
||||
|
||||
try:
|
||||
@@ -183,37 +184,37 @@ def createsporttracksworkoutdata(w):
|
||||
st = st.replace(microsecond=0)
|
||||
|
||||
if haslatlon:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
"start_time": st.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"location": locdata,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
"start_time": st.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"location": locdata,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
else:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
"start_time": st.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
"start_time": st.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": duration,
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
|
||||
if haspower:
|
||||
data['power'] = powerdata
|
||||
data['power'] = powerdata
|
||||
|
||||
return data
|
||||
|
||||
@@ -239,41 +240,41 @@ def workout_sporttracks_upload(user,w):
|
||||
thetoken = sporttracks_open(user)
|
||||
|
||||
if (checkworkoutuser(user,w)):
|
||||
data = createsporttracksworkoutdata(w)
|
||||
data = createsporttracksworkoutdata(w)
|
||||
if not data:
|
||||
message = "Data error"
|
||||
stid = 0
|
||||
return message,stid
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtosporttracks = -1
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtosporttracks = -1
|
||||
stid = -1
|
||||
w.save()
|
||||
w.save()
|
||||
return message, stid
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
s= response.json()
|
||||
stid = getidfromresponse(response)
|
||||
w.uploadedtosporttracks = stid
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
s= response.json()
|
||||
stid = getidfromresponse(response)
|
||||
w.uploadedtosporttracks = stid
|
||||
w.save()
|
||||
return 'Successfully synced to SportTracks',stid
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
|
||||
stid = 0
|
||||
return message,stid
|
||||
|
||||
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
stid = 0
|
||||
return message,stid
|
||||
|
||||
@@ -289,33 +290,33 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
|
||||
workouttype = 'other'
|
||||
|
||||
if workouttype not in [x[0] for x in Workout.workouttypes]:
|
||||
workouttype = 'other'
|
||||
workouttype = 'other'
|
||||
try:
|
||||
comments = data['comments']
|
||||
comments = data['comments']
|
||||
except:
|
||||
comments = ''
|
||||
comments = ''
|
||||
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['start_time'])
|
||||
rowdatetime = iso8601.parse_date(data['start_time'])
|
||||
except iso8601.ParseError:
|
||||
try:
|
||||
rowdatetime = datetime.datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
try:
|
||||
rowdatetime = dateutil.parser.parse(data['start_time'])
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
try:
|
||||
rowdatetime = datetime.datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
try:
|
||||
rowdatetime = dateutil.parser.parse(data['start_time'])
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except:
|
||||
title = "Imported data"
|
||||
title = "Imported data"
|
||||
|
||||
try:
|
||||
res = splitstdata(data['distance'])
|
||||
@@ -331,41 +332,41 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
|
||||
|
||||
|
||||
try:
|
||||
l = data['location']
|
||||
l = data['location']
|
||||
|
||||
res = splitstdata(l)
|
||||
times_location = res[0]
|
||||
latlong = res[1]
|
||||
latcoord = []
|
||||
loncoord = []
|
||||
res = splitstdata(l)
|
||||
times_location = res[0]
|
||||
latlong = res[1]
|
||||
latcoord = []
|
||||
loncoord = []
|
||||
|
||||
for coord in latlong:
|
||||
lat = coord[0]
|
||||
lon = coord[1]
|
||||
latcoord.append(lat)
|
||||
loncoord.append(lon)
|
||||
for coord in latlong:
|
||||
lat = coord[0]
|
||||
lon = coord[1]
|
||||
latcoord.append(lat)
|
||||
loncoord.append(lon)
|
||||
except:
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
if workouttype in mytypes.otwtypes:
|
||||
workouttype = 'rower'
|
||||
|
||||
|
||||
try:
|
||||
res = splitstdata(data['cadence'])
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
res = splitstdata(data['cadence'])
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
except KeyError:
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
|
||||
try:
|
||||
res = splitstdata(data['heartrate'])
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
res = splitstdata(data['heartrate'])
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
except KeyError:
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
|
||||
|
||||
# create data series and remove duplicates
|
||||
@@ -383,12 +384,12 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
|
||||
|
||||
# Create dicts and big dataframe
|
||||
d = {
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -432,7 +433,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
|
||||
df = df.fillna(0)
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
# csvfilename ='media/Import_'+str(importid)+'.csv'
|
||||
|
||||
+182
-180
@@ -1,3 +1,5 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
|
||||
# All the functionality needed to connect to Strava
|
||||
from scipy import optimize
|
||||
from scipy.signal import savgol_filter
|
||||
@@ -10,15 +12,15 @@ queue = django_rq.get_queue('default')
|
||||
queuelow = django_rq.get_queue('low')
|
||||
queuehigh = django_rq.get_queue('low')
|
||||
|
||||
from dataprep import columndict
|
||||
from rowers.dataprep import columndict
|
||||
|
||||
import stravalib
|
||||
from stravalib.exc import ActivityUploadFailed,TimeoutExceeded
|
||||
|
||||
from iso8601 import ParseError
|
||||
from utils import myqueue
|
||||
from rowers.utils import myqueue
|
||||
|
||||
import mytypes
|
||||
import rowers.mytypes as mytypes
|
||||
import gzip
|
||||
|
||||
from rowsandall_app.settings import (
|
||||
@@ -35,7 +37,7 @@ from rowers.imports import *
|
||||
|
||||
headers = {'Accept': 'application/json',
|
||||
'Api-Key': STRAVA_CLIENT_ID,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'user-agent': 'sanderroosendaal'}
|
||||
|
||||
|
||||
@@ -89,26 +91,26 @@ def make_authorization_url(request):
|
||||
def get_strava_workout_list(user,limit_n=0):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (r.stravatokenexpirydate is None or timezone.now()+timedelta(seconds=3599)>r.stravatokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.stravatoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.stravatoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "https://www.strava.com/api/v3/athlete/activities"
|
||||
url = "https://www.strava.com/api/v3/athlete/activities"
|
||||
|
||||
if limit_n==0:
|
||||
params = {}
|
||||
else:
|
||||
params = {'per_page':limit_n}
|
||||
|
||||
s = requests.get(url,headers=headers,params=params)
|
||||
s = requests.get(url,headers=headers,params=params)
|
||||
|
||||
|
||||
return s
|
||||
@@ -200,27 +202,27 @@ def create_async_workout(alldata,user,stravaid,debug=False):
|
||||
thetimezone = 'UTC'
|
||||
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
except KeyError:
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
except ParseError:
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
|
||||
try:
|
||||
c2intervaltype = data['workout_type']
|
||||
|
||||
|
||||
except KeyError:
|
||||
c2intervaltype = ''
|
||||
|
||||
c2intervaltype = ''
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except KeyError:
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
|
||||
workoutdate = rowdatetime.astimezone(
|
||||
pytz.timezone(thetimezone)
|
||||
@@ -259,7 +261,7 @@ def create_async_workout(alldata,user,stravaid,debug=False):
|
||||
|
||||
return 1
|
||||
|
||||
from utils import get_strava_stream
|
||||
from rowers.utils import get_strava_stream
|
||||
|
||||
|
||||
|
||||
@@ -273,26 +275,26 @@ def get_workout(user,stravaid):
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (r.stravatokenexpirydate is not None and timezone.now()>r.stravatokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
fetchresolution = 'high'
|
||||
# ready to fetch. Hurray
|
||||
fetchresolution = 'high'
|
||||
series_type = 'time'
|
||||
authorizationstring = str('Bearer ' + r.stravatoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'resolution': 'medium',}
|
||||
url = "https://www.strava.com/api/v3/activities/"+str(stravaid)
|
||||
workoutsummary = requests.get(url,headers=headers).json()
|
||||
authorizationstring = str('Bearer ' + r.stravatoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'resolution': 'medium',}
|
||||
url = "https://www.strava.com/api/v3/activities/"+str(stravaid)
|
||||
workoutsummary = requests.get(url,headers=headers).json()
|
||||
|
||||
workoutsummary['timezone'] = "Etc/UTC"
|
||||
workoutsummary['timezone'] = "Etc/UTC"
|
||||
try:
|
||||
startdatetime = workoutsummary['start_date']
|
||||
startdatetime = workoutsummary['start_date']
|
||||
except KeyError:
|
||||
startdatetime = timezone.now()
|
||||
|
||||
@@ -306,9 +308,9 @@ def get_workout(user,stravaid):
|
||||
|
||||
|
||||
try:
|
||||
t = np.array(timejson.json()[0]['data'])
|
||||
nr_rows = len(t)
|
||||
d = np.array(distancejson.json()[1]['data'])
|
||||
t = np.array(timejson.json()[0]['data'])
|
||||
nr_rows = len(t)
|
||||
d = np.array(distancejson.json()[1]['data'])
|
||||
if nr_rows == 0:
|
||||
return (0,"Error: Time data had zero length")
|
||||
|
||||
@@ -318,70 +320,70 @@ def get_workout(user,stravaid):
|
||||
except KeyError:
|
||||
return (0,"something went wrong with the Strava import")
|
||||
|
||||
try:
|
||||
spm = np.array(spmjson.json()[1]['data'])
|
||||
except:
|
||||
spm = np.zeros(nr_rows)
|
||||
try:
|
||||
spm = np.array(spmjson.json()[1]['data'])
|
||||
except:
|
||||
spm = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
power = np.array(powerjson.json()[1]['data'])
|
||||
except IndexError:
|
||||
power = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
hr = np.array(hrjson.json()[1]['data'])
|
||||
except IndexError:
|
||||
hr = np.zeros(nr_rows)
|
||||
try:
|
||||
hr = np.array(hrjson.json()[1]['data'])
|
||||
except IndexError:
|
||||
hr = np.zeros(nr_rows)
|
||||
except KeyError:
|
||||
hr = np.zeros(nr_rows)
|
||||
hr = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
velo = np.array(velojson.json()[1]['data'])
|
||||
except IndexError:
|
||||
velo = np.zeros(nr_rows)
|
||||
try:
|
||||
velo = np.array(velojson.json()[1]['data'])
|
||||
except IndexError:
|
||||
velo = np.zeros(nr_rows)
|
||||
except KeyError:
|
||||
velo = np.zeros(nr_rows)
|
||||
|
||||
dt = np.diff(t).mean()
|
||||
wsize = round(5./dt)
|
||||
dt = np.diff(t).mean()
|
||||
wsize = round(5./dt)
|
||||
|
||||
velo2 = ewmovingaverage(velo,wsize)
|
||||
coords = np.array(latlongjson.json()[0]['data'])
|
||||
try:
|
||||
lat = coords[:,0]
|
||||
lon = coords[:,1]
|
||||
except IndexError:
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
velo2 = ewmovingaverage(velo,wsize)
|
||||
coords = np.array(latlongjson.json()[0]['data'])
|
||||
try:
|
||||
lat = coords[:,0]
|
||||
lon = coords[:,1]
|
||||
except IndexError:
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
except KeyError:
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
|
||||
|
||||
|
||||
|
||||
strokelength = velo*60./(spm)
|
||||
strokelength[np.isinf(strokelength)] = 0.0
|
||||
strokelength = velo*60./(spm)
|
||||
strokelength[np.isinf(strokelength)] = 0.0
|
||||
|
||||
|
||||
pace = 500./(1.0*velo2)
|
||||
pace[np.isinf(pace)] = 0.0
|
||||
pace = 500./(1.0*velo2)
|
||||
pace[np.isinf(pace)] = 0.0
|
||||
|
||||
df = pd.DataFrame({'t':10*t,
|
||||
'd':10*d,
|
||||
'p':10*pace,
|
||||
'spm':spm,
|
||||
'hr':hr,
|
||||
'lat':lat,
|
||||
'lon':lon,
|
||||
df = pd.DataFrame({'t':10*t,
|
||||
'd':10*d,
|
||||
'p':10*pace,
|
||||
'spm':spm,
|
||||
'hr':hr,
|
||||
'lat':lat,
|
||||
'lon':lon,
|
||||
'power':power,
|
||||
'strokelength':strokelength,
|
||||
})
|
||||
'strokelength':strokelength,
|
||||
})
|
||||
|
||||
|
||||
# startdatetime = datetime.datetime.strptime(startdatetime,"%Y-%m-%d-%H:%M:%S")
|
||||
# startdatetime = datetime.datetime.strptime(startdatetime,"%Y-%m-%d-%H:%M:%S")
|
||||
|
||||
return [workoutsummary,df]
|
||||
return [workoutsummary,df]
|
||||
|
||||
# Generate Workout data for Strava (a TCX file)
|
||||
def createstravaworkoutdata(w,dozip=True):
|
||||
@@ -478,41 +480,41 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
workouttype = 'water'
|
||||
|
||||
if workouttype not in [x[0] for x in Workout.workouttypes]:
|
||||
workouttype = 'other'
|
||||
workouttype = 'other'
|
||||
try:
|
||||
comments = data['comments']
|
||||
comments = data['comments']
|
||||
except:
|
||||
comments = ' '
|
||||
comments = ' '
|
||||
|
||||
try:
|
||||
thetimezone = tz(data['timezone'])
|
||||
thetimezone = tz(data['timezone'])
|
||||
except:
|
||||
thetimezone = 'UTC'
|
||||
thetimezone = 'UTC'
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
except KeyError:
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
except ParseError:
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
|
||||
|
||||
|
||||
try:
|
||||
intervaltype = data['workout_type']
|
||||
|
||||
|
||||
except KeyError:
|
||||
intervaltype = ''
|
||||
|
||||
intervaltype = ''
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except KeyError:
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
|
||||
@@ -526,17 +528,17 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
nr_rows = len(unixtime)
|
||||
|
||||
try:
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
except:
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
|
||||
|
||||
try:
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
except:
|
||||
strokelength = np.zeros(nr_rows)
|
||||
strokelength = np.zeros(nr_rows)
|
||||
|
||||
dist2 = 0.1*strokedata.loc[:,'d']
|
||||
|
||||
@@ -566,28 +568,28 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
# save csv
|
||||
# Create data frame with all necessary data to write to csv
|
||||
df = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
|
||||
@@ -623,34 +625,34 @@ def workout_strava_upload(user,w):
|
||||
r = Rower.objects.get(user=user)
|
||||
res = -1
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
raise NoTokenError("Your hovercraft is full of eels")
|
||||
else:
|
||||
if (checkworkoutuser(user,w)):
|
||||
if (checkworkoutuser(user,w)):
|
||||
try:
|
||||
tcxfile,tcxmesg = createstravaworkoutdata(w)
|
||||
tcxfile,tcxmesg = createstravaworkoutdata(w)
|
||||
if tcxfile:
|
||||
with open(tcxfile,'rb') as f:
|
||||
res,mes = handle_stravaexport(
|
||||
with open(tcxfile,'rb') as f:
|
||||
res,mes = handle_stravaexport(
|
||||
f,w.name,
|
||||
r.stravatoken,
|
||||
description=w.notes+'\n from '+w.workoutsource+' via rowsandall.com',
|
||||
r.stravatoken,
|
||||
description=w.notes+'\n from '+w.workoutsource+' via rowsandall.com',
|
||||
activity_type=r.stravaexportas)
|
||||
if res==0:
|
||||
message = mes
|
||||
w.uploadedtostrava = -1
|
||||
message = mes
|
||||
w.uploadedtostrava = -1
|
||||
stravaid = -1
|
||||
w.save()
|
||||
w.save()
|
||||
try:
|
||||
os.remove(tcxfile)
|
||||
os.remove(tcxfile)
|
||||
except WindowsError:
|
||||
pass
|
||||
return message,stravaid
|
||||
|
||||
w.uploadedtostrava = res
|
||||
w.save()
|
||||
w.uploadedtostrava = res
|
||||
w.save()
|
||||
try:
|
||||
os.remove(tcxfile)
|
||||
os.remove(tcxfile)
|
||||
except WindowsError:
|
||||
pass
|
||||
message = mes
|
||||
@@ -663,14 +665,14 @@ def workout_strava_upload(user,w):
|
||||
w.save()
|
||||
return message, stravaid
|
||||
|
||||
except ActivityUploadFailed as e:
|
||||
message = "Strava Upload error: %s" % e
|
||||
w.uploadedtostrava = -1
|
||||
except ActivityUploadFailed as e:
|
||||
message = "Strava Upload error: %s" % e
|
||||
w.uploadedtostrava = -1
|
||||
stravaid = -1
|
||||
w.save()
|
||||
os.remove(tcxfile)
|
||||
w.save()
|
||||
os.remove(tcxfile)
|
||||
return message,stravaid
|
||||
return message,stravaid
|
||||
return message,stravaid
|
||||
return message,stravaid
|
||||
|
||||
|
||||
@@ -688,9 +690,9 @@ def handle_strava_import_stroke_data(title,
|
||||
series_type = 'time'
|
||||
authorizationstring = str('Bearer ' + stravatoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'resolution': 'medium',}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'resolution': 'medium',}
|
||||
url = "https://www.strava.com/api/v3/activities/"+str(stravaid)
|
||||
workoutsummary = requests.get(url,headers=headers).json()
|
||||
|
||||
@@ -708,9 +710,9 @@ def handle_strava_import_stroke_data(title,
|
||||
wattsjson = get_strava_stream(r,'watts',stravaid)
|
||||
|
||||
try:
|
||||
t = np.array(timejson.json()[0]['data'])
|
||||
nr_rows = len(t)
|
||||
d = np.array(distancejson.json()[1]['data'])
|
||||
t = np.array(timejson.json()[0]['data'])
|
||||
nr_rows = len(t)
|
||||
d = np.array(distancejson.json()[1]['data'])
|
||||
if nr_rows == 0:
|
||||
return 0
|
||||
except IndexError:
|
||||
@@ -720,9 +722,9 @@ def handle_strava_import_stroke_data(title,
|
||||
return 0
|
||||
|
||||
try:
|
||||
spm = np.array(spmjson.json()[1]['data'])
|
||||
spm = np.array(spmjson.json()[1]['data'])
|
||||
except:
|
||||
spm = np.zeros(nr_rows)
|
||||
spm = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
watts = np.array(wattsjson.json()[1]['data'])
|
||||
@@ -730,16 +732,16 @@ def handle_strava_import_stroke_data(title,
|
||||
watts = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
hr = np.array(hrjson.json()[1]['data'])
|
||||
hr = np.array(hrjson.json()[1]['data'])
|
||||
except IndexError:
|
||||
hr = np.zeros(nr_rows)
|
||||
hr = np.zeros(nr_rows)
|
||||
except KeyError:
|
||||
hr = np.zeros(nr_rows)
|
||||
hr = np.zeros(nr_rows)
|
||||
|
||||
try:
|
||||
velo = np.array(velojson.json()[1]['data'])
|
||||
velo = np.array(velojson.json()[1]['data'])
|
||||
except IndexError:
|
||||
velo = np.zeros(nr_rows)
|
||||
velo = np.zeros(nr_rows)
|
||||
except KeyError:
|
||||
velo = np.zeros(nr_rows)
|
||||
|
||||
@@ -756,14 +758,14 @@ def handle_strava_import_stroke_data(title,
|
||||
|
||||
coords = np.array(latlongjson.json()[0]['data'])
|
||||
try:
|
||||
lat = coords[:,0]
|
||||
lon = coords[:,1]
|
||||
lat = coords[:,0]
|
||||
lon = coords[:,1]
|
||||
except IndexError:
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
except KeyError:
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
lat = np.zeros(len(t))
|
||||
lon = np.zeros(len(t))
|
||||
|
||||
strokelength = velo*60./(spm)
|
||||
strokelength[np.isinf(strokelength)] = 0.0
|
||||
@@ -779,22 +781,22 @@ def handle_strava_import_stroke_data(title,
|
||||
|
||||
df = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' ElapsedTime (sec)':t,
|
||||
' Horizontal (meters)':d,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' latitude':lat,
|
||||
' longitude':lon,
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' Horizontal (meters)':d,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' latitude':lat,
|
||||
' longitude':lon,
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
'cum_dist':d,
|
||||
' DragFactor':np.zeros(nr_strokes),
|
||||
' DriveLength (meters)':np.zeros(nr_strokes),
|
||||
' StrokeDistance (meters)':strokedistance,
|
||||
' DriveTime (ms)':np.zeros(nr_strokes),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_strokes),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' lapIdx':np.zeros(nr_strokes),
|
||||
' DragFactor':np.zeros(nr_strokes),
|
||||
' DriveLength (meters)':np.zeros(nr_strokes),
|
||||
' StrokeDistance (meters)':strokedistance,
|
||||
' DriveTime (ms)':np.zeros(nr_strokes),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_strokes),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_strokes),
|
||||
' lapIdx':np.zeros(nr_strokes),
|
||||
' Power (watts)':watts,
|
||||
})
|
||||
|
||||
|
||||
+20
-16
@@ -1,4 +1,5 @@
|
||||
""" Background tasks done by Celery (develop) or QR (production) """
|
||||
from __future__ import absolute_import
|
||||
import os
|
||||
import time
|
||||
import gc
|
||||
@@ -16,7 +17,10 @@ from rowingdata import rowingdata as rdata
|
||||
from datetime import timedelta
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from celery import app
|
||||
#from celery import app
|
||||
from rowers.celery import app
|
||||
from celery import shared_task
|
||||
|
||||
import datetime
|
||||
import pytz
|
||||
import iso8601
|
||||
@@ -39,10 +43,11 @@ from django_rq import job
|
||||
from django.utils import timezone
|
||||
from django.utils.html import strip_tags
|
||||
|
||||
from utils import deserialize_list,ewmovingaverage,wavg
|
||||
from emails import htmlstrip
|
||||
from rowers.utils import deserialize_list,ewmovingaverage,wavg
|
||||
from rowers.emails import htmlstrip
|
||||
|
||||
from HTMLParser import HTMLParser
|
||||
#from HTMLParser import HTMLParser
|
||||
from html.parser import HTMLParser
|
||||
class MLStripper(HTMLParser):
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
@@ -80,13 +85,13 @@ from django.db.utils import OperationalError
|
||||
from jinja2 import Template,Environment,FileSystemLoader
|
||||
env = Environment(loader = FileSystemLoader(["rowers/templates"]))
|
||||
|
||||
import datautils
|
||||
import utils
|
||||
import rowers.datautils as datautils
|
||||
import rowers.utils as utils
|
||||
import requests
|
||||
import longtask
|
||||
import rowers.longtask as longtask
|
||||
import arrow
|
||||
|
||||
from utils import get_strava_stream
|
||||
from rowers.utils import get_strava_stream
|
||||
|
||||
siteurl = SITE_URL
|
||||
|
||||
@@ -128,9 +133,9 @@ def handle_c2_import_stroke_data(c2token,
|
||||
|
||||
return 1
|
||||
else:
|
||||
url = "https://log.concept2.com/api/users/me/results/"+str(c2id)
|
||||
url = "https://log.concept2.com/api/users/me/results/{id}".format(id=c2id)
|
||||
|
||||
s = requests.get(url,headers=headers)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
if s.status_code == 200:
|
||||
workoutdata = s.json()['data']
|
||||
@@ -1238,21 +1243,21 @@ def handle_zip_file(emailfrom, subject, file,**kwargs):
|
||||
debug = False
|
||||
|
||||
if debug:
|
||||
print message
|
||||
print(message)
|
||||
|
||||
email = EmailMessage(subject, message,
|
||||
emailfrom,
|
||||
['workouts@rowsandall.com'])
|
||||
email.attach_file(file)
|
||||
if debug:
|
||||
print "attaching"
|
||||
print("attaching")
|
||||
|
||||
|
||||
res = email.send()
|
||||
|
||||
|
||||
if debug:
|
||||
print "sent"
|
||||
print("sent")
|
||||
time.sleep(60)
|
||||
return 1
|
||||
|
||||
@@ -1490,9 +1495,8 @@ def handle_updateergcp(rower_id,workoutfilenames,debug=False,**kwargs):
|
||||
rowdata = rdata(f1 + '.gz')
|
||||
except IOError:
|
||||
rowdata = 0
|
||||
|
||||
if rowdata != 0:
|
||||
therows.append(rowdata)
|
||||
if rowdata != 0:
|
||||
therows.append(rowdata)
|
||||
|
||||
cpdata = rowingdata.cumcpdata(therows)
|
||||
cpdata.columns = cpdata.columns.str.lower()
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ from django.db import IntegrityError
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
|
||||
from utils import myqueue
|
||||
from rowers.utils import myqueue
|
||||
|
||||
import django_rq
|
||||
queue = django_rq.get_queue('default')
|
||||
|
||||
+1
-6
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
# All the functionality needed to connect to Runkeeper
|
||||
from rowers.imports import *
|
||||
|
||||
@@ -149,12 +150,6 @@ def uploadactivity(access_token,filename,description='',
|
||||
headers=headers)
|
||||
|
||||
if resp.status_code != 200:
|
||||
if settings.DEBUG:
|
||||
print resp.status_code
|
||||
print resp.reason
|
||||
print ""
|
||||
print headers
|
||||
print ""
|
||||
return 0,resp.reason,resp.status_code,headers
|
||||
else:
|
||||
return resp.json()[0]["Id"],"ok",200,""
|
||||
|
||||
+101
-100
@@ -1,6 +1,7 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
from rowers.imports import *
|
||||
|
||||
import mytypes
|
||||
import rowers.mytypes as mytypes
|
||||
from rowers.mytypes import otwtypes
|
||||
|
||||
from rowsandall_app.settings import (
|
||||
@@ -45,18 +46,18 @@ def make_authorization_url(request):
|
||||
def get_underarmour_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.underarmourtoken == '') or (r.underarmourtoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/workout/?user="+str(get_userid(r.underarmourtoken))+"&order_by=-start_datetime"
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/workout/?user="+str(get_userid(r.underarmourtoken))+"&order_by=-start_datetime"
|
||||
|
||||
s = requests.get(url,headers=headers)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
|
||||
return s
|
||||
@@ -65,17 +66,17 @@ def get_underarmour_workout_list(user):
|
||||
def get_workout(user,underarmourid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.underarmourtoken == '') or (r.underarmourtoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/workout/"+str(underarmourid)+"/?field_set=time_series"
|
||||
s = requests.get(url,headers=headers)
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/workout/"+str(underarmourid)+"/?field_set=time_series"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
data = s.json()
|
||||
|
||||
@@ -135,12 +136,12 @@ def createunderarmourworkoutdata(w):
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude']
|
||||
lon = row.df[' longitude']
|
||||
lat = row.df[' latitude']
|
||||
lon = row.df[' longitude']
|
||||
if not lat.std() and not lon.std():
|
||||
haslatlon = 0
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
haslatlon = 0
|
||||
|
||||
|
||||
|
||||
@@ -201,7 +202,7 @@ def createunderarmourworkoutdata(w):
|
||||
timeseries["position"] = locdata
|
||||
|
||||
data = {
|
||||
"start_datetime": start_time,
|
||||
"start_datetime": start_time,
|
||||
"name": name,
|
||||
"has_time_series": True,
|
||||
"time_series": timeseries,
|
||||
@@ -236,8 +237,8 @@ def refresh_ua_actlist(user):
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/activity_type/"
|
||||
response = requests.get(url,headers=headers)
|
||||
|
||||
@@ -263,8 +264,8 @@ def get_typefromid(typeid,user):
|
||||
authorizationstring = str('Bearer ' + r.underarmourtoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ua.com/v7.1/activity_type/"+str(typeid)
|
||||
response = requests.get(url,headers=headers)
|
||||
|
||||
@@ -285,8 +286,8 @@ def get_userid(access_token):
|
||||
authorizationstring = str('Bearer ' + access_token)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "https://api.ua.com/v7.1/user/self/"
|
||||
response = requests.get(url,headers=headers)
|
||||
@@ -311,42 +312,42 @@ def workout_ua_upload(user,w):
|
||||
# ready to upload. Hurray
|
||||
|
||||
if (checkworkoutuser(user,w)):
|
||||
data = createunderarmourworkoutdata(w)
|
||||
data = createunderarmourworkoutdata(w)
|
||||
# return HttpResponse(json.dumps(data))
|
||||
if not data:
|
||||
message = "Data error"
|
||||
uaid = 0
|
||||
return message, uaid
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
url = "https://api.ua.com/v7.1/workout/"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.ua.com/v7.1/workout/"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtounderarmour = -1
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
w.uploadedtounderarmour = -1
|
||||
uaid = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
uaid = getidfromresponse(response)
|
||||
w.uploadedtounderarmour = uaid
|
||||
w.save()
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
uaid = getidfromresponse(response)
|
||||
w.uploadedtounderarmour = uaid
|
||||
w.save()
|
||||
return 'Successfully synchronized with MapMyFitness',uaid
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_underarmour_upload_view: %s - %s" % (s.reason,s.text)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_underarmour_upload_view: %s - %s" % (s.reason,s.text)
|
||||
uaid = 0
|
||||
return message, uaid
|
||||
|
||||
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
uaid = 0
|
||||
return message, uaid
|
||||
|
||||
@@ -360,36 +361,36 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
workouttype = 'water'
|
||||
|
||||
try:
|
||||
comments = data['notes']
|
||||
comments = data['notes']
|
||||
except:
|
||||
comments = ''
|
||||
comments = ''
|
||||
|
||||
try:
|
||||
thetimezone = tz(data['start_locale_timezone'])
|
||||
thetimezone = tz(data['start_locale_timezone'])
|
||||
except:
|
||||
thetimezone = 'UTC'
|
||||
thetimezone = 'UTC'
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['start_datetime'])
|
||||
rowdatetime = iso8601.parse_date(data['start_datetime'])
|
||||
except iso8601.ParseError:
|
||||
try:
|
||||
rowdatetime = datetime.strptime(data['start_datetime'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
try:
|
||||
rowdatetime = parser.parse(data['start_datetime'])
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
try:
|
||||
rowdatetime = datetime.strptime(data['start_datetime'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
try:
|
||||
rowdatetime = parser.parse(data['start_datetime'])
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
except:
|
||||
rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
|
||||
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
|
||||
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except:
|
||||
title = "Imported data"
|
||||
title = "Imported data"
|
||||
|
||||
timeseries = data['time_series']
|
||||
|
||||
@@ -403,41 +404,41 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
|
||||
|
||||
try:
|
||||
l = timeseries['position']
|
||||
l = timeseries['position']
|
||||
|
||||
res = splituadata(l)
|
||||
times_location = res[0]
|
||||
latlong = res[1]
|
||||
latcoord = []
|
||||
loncoord = []
|
||||
res = splituadata(l)
|
||||
times_location = res[0]
|
||||
latlong = res[1]
|
||||
latcoord = []
|
||||
loncoord = []
|
||||
|
||||
for coord in latlong:
|
||||
lat = coord['lat']
|
||||
lon = coord['lng']
|
||||
latcoord.append(lat)
|
||||
loncoord.append(lon)
|
||||
for coord in latlong:
|
||||
lat = coord['lat']
|
||||
lon = coord['lng']
|
||||
latcoord.append(lat)
|
||||
loncoord.append(lon)
|
||||
except:
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
times_location = times_distance
|
||||
latcoord = np.zeros(len(times_distance))
|
||||
loncoord = np.zeros(len(times_distance))
|
||||
if workouttype in otwtypes:
|
||||
workouttype = 'rower'
|
||||
|
||||
|
||||
try:
|
||||
res = splituadata(timeseries['cadence'])
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
res = splituadata(timeseries['cadence'])
|
||||
times_spm = res[0]
|
||||
spm = res[1]
|
||||
except KeyError:
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
times_spm = times_distance
|
||||
spm = 0*times_distance
|
||||
|
||||
try:
|
||||
res = splituadata(timeseries['heartrate'])
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
res = splituadata(timeseries['heartrate'])
|
||||
hr = res[1]
|
||||
times_hr = res[0]
|
||||
except KeyError:
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
times_hr = times_distance
|
||||
hr = 0*times_distance
|
||||
|
||||
|
||||
# create data series and remove duplicates
|
||||
@@ -455,12 +456,12 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
|
||||
# Create dicts and big dataframe
|
||||
d = {
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
' Horizontal (meters)': distseries,
|
||||
' latitude': latseries,
|
||||
' longitude': lonseries,
|
||||
' Cadence (stokes/min)': spmseries,
|
||||
' HRCur (bpm)' : hrseries,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -499,7 +500,7 @@ def add_workout_from_data(user,importid,data,strokedata,
|
||||
df = df.fillna(0)
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
csvfilename ='media/{code}_{importid}.csv'.format(
|
||||
|
||||
+22
-17
@@ -26,12 +26,13 @@ queue = django_rq.get_queue('default')
|
||||
queuelow = django_rq.get_queue('low')
|
||||
queuehigh = django_rq.get_queue('low')
|
||||
|
||||
from mytypes import workouttypes,boattypes,otwtypes,workoutsources
|
||||
from rowers.mytypes import workouttypes,boattypes,otwtypes,workoutsources
|
||||
|
||||
try:
|
||||
from cStringIO import StringIO
|
||||
except:
|
||||
from StringIO import StringIO
|
||||
from io import StringIO
|
||||
|
||||
|
||||
from rowers.utils import (
|
||||
geo_distance,serialize_list,deserialize_list,uniqify,
|
||||
@@ -403,34 +404,34 @@ def make_plot(r,w,f1,f2,plottype,title,imagename='',plotnr=0):
|
||||
ftp = ftp*(100.-r.otwslack)/100.
|
||||
|
||||
hrpwrdata = {
|
||||
'hrmax':r.max,
|
||||
'hrut2':r.ut2,
|
||||
'hrut1':r.ut1,
|
||||
'hrat':r.at,
|
||||
'hrtr':r.tr,
|
||||
'hran':r.an,
|
||||
'ftp':ftp,
|
||||
'hrmax':r.max,
|
||||
'hrut2':r.ut2,
|
||||
'hrut1':r.ut1,
|
||||
'hrat':r.at,
|
||||
'hrtr':r.tr,
|
||||
'hran':r.an,
|
||||
'ftp':ftp,
|
||||
'powerperc':serialize_list(powerperc),
|
||||
'powerzones':serialize_list(r.powerzones),
|
||||
}
|
||||
|
||||
# make plot - asynchronous task
|
||||
plotnrs = {
|
||||
'timeplot':1,
|
||||
'distanceplot':2,
|
||||
'pieplot':3,
|
||||
'timeplot':1,
|
||||
'distanceplot':2,
|
||||
'pieplot':3,
|
||||
}
|
||||
|
||||
if plotnr == 0:
|
||||
plotnr = plotnrs[plottype]
|
||||
|
||||
if w.workouttype in otwtypes:
|
||||
plotnr = plotnr+3
|
||||
plotnr = plotnr+3
|
||||
|
||||
|
||||
job = myqueue(queue,handle_makeplot,f1,f2,
|
||||
title,hrpwrdata,
|
||||
plotnr,imagename)
|
||||
title,hrpwrdata,
|
||||
plotnr,imagename)
|
||||
|
||||
try:
|
||||
width,height = Image.open(fullpathimagename).size
|
||||
@@ -451,8 +452,12 @@ def make_plot(r,w,f1,f2,plottype,title,imagename='',plotnr=0):
|
||||
|
||||
return i.id,job.id
|
||||
|
||||
import c2stuff,stravastuff,sporttracksstuff,runkeeperstuff
|
||||
import underarmourstuff,tpstuff
|
||||
import rowers.c2stuff as c2stuff
|
||||
import rowers.stravastuff as stravastuff
|
||||
import rowers.sporttracksstuff as sporttracksstuff
|
||||
import rowers.runkeeperstuff as runkeeperstuff
|
||||
import rowers.underarmourstuff as underarmourstuff
|
||||
import rowers.tpstuff as tpstuff
|
||||
|
||||
def set_workouttype(w,options):
|
||||
try:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ from django.conf import settings
|
||||
from django.conf.urls import url, include
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required, permission_required
|
||||
from models import Workout,Rower,StrokeData,FavoriteChart
|
||||
from rowers.models import Workout,Rower,StrokeData,FavoriteChart
|
||||
|
||||
from rest_framework import routers, serializers, viewsets,permissions
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
|
||||
+2
-2
@@ -439,10 +439,10 @@ def ewmovingaverage(interval,window_size):
|
||||
# Custom error class - to raise a NoTokenError
|
||||
class NoTokenError(Exception):
|
||||
def __init__(self,value):
|
||||
self.value=value
|
||||
self.value=value
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
return repr(self.value)
|
||||
|
||||
class ProcessorCustomerError(Exception):
|
||||
def __init__(self, value):
|
||||
|
||||
+718
-717
File diff suppressed because it is too large
Load Diff
+24
-24
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
# Stroke data form to test API upload
|
||||
@@ -18,22 +18,22 @@ def strokedataform(request,id=0):
|
||||
if request.method == 'GET':
|
||||
form = StrokeDataForm()
|
||||
return render(request, 'strokedata_form.html',
|
||||
{
|
||||
'form':form,
|
||||
{
|
||||
'form':form,
|
||||
'teams':get_my_teams(request.user),
|
||||
'id':id,
|
||||
'workout':w,
|
||||
})
|
||||
})
|
||||
elif request.method == 'POST':
|
||||
form = StrokeDataForm()
|
||||
|
||||
return render(request, 'strokedata_form.html',
|
||||
{
|
||||
'form':form,
|
||||
{
|
||||
'form':form,
|
||||
'teams':get_my_teams(request.user),
|
||||
'id':id,
|
||||
'workout':w,
|
||||
})
|
||||
})
|
||||
|
||||
# Process the POSTed stroke data according to the API definition
|
||||
# Return the GET stroke data according to the API definition
|
||||
@@ -124,30 +124,30 @@ def strokedatajson(request,id):
|
||||
logfile.write(request.user.username+"(POST) \r\n")
|
||||
|
||||
data = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' Horizontal (meters)': distance,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' DragFactor':dragfactor,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DriveLength (meters)':drivelength,
|
||||
' DriveTime (ms)':drivetime,
|
||||
' StrokeRecoveryTime (ms)':strokerecoverytime,
|
||||
' AverageDriveForce (lbs)':averagedriveforce,
|
||||
' PeakDriveForce (lbs)':peakdriveforce,
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':time,
|
||||
' Horizontal (meters)': distance,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' DragFactor':dragfactor,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DriveLength (meters)':drivelength,
|
||||
' DriveTime (ms)':drivetime,
|
||||
' StrokeRecoveryTime (ms)':strokerecoverytime,
|
||||
' AverageDriveForce (lbs)':averagedriveforce,
|
||||
' PeakDriveForce (lbs)':peakdriveforce,
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':time,
|
||||
'catch':catch,
|
||||
'slip':slip,
|
||||
'finish':finish,
|
||||
'wash':wash,
|
||||
'driveenergy':driveenergy,
|
||||
'peakforceangle':peakforceangle,
|
||||
})
|
||||
})
|
||||
|
||||
# Following part should be replaced with dataprep.new_workout_from_df
|
||||
|
||||
r = getrower(request.user)
|
||||
r = getrower(request.user)
|
||||
|
||||
timestr = row.startdatetime.strftime("%Y%m%d-%H%M%S")
|
||||
csvfilename ='media/Import_'+timestr+'.csv'
|
||||
@@ -167,8 +167,8 @@ def strokedatajson(request,id):
|
||||
ftp = ftp*(100.-r.otwslack)/100.
|
||||
|
||||
rr = rrower(hrmax=r.max,hrut2=r.ut2,
|
||||
hrut1=r.ut1,hrat=r.at,
|
||||
hrtr=r.tr,hran=r.an,ftp=ftp,
|
||||
hrut1=r.ut1,hrat=r.at,
|
||||
hrtr=r.tr,hran=r.an,ftp=ftp,
|
||||
powerperc=powerperc,powerzones=r.powerzones)
|
||||
rowdata = rdata(row.csvfilename,rower=rr).df
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
# Custom error pages with Rowsandall headers
|
||||
def error500_view(request):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
|
||||
|
||||
+262
-262
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
# Send workout to TP
|
||||
@@ -71,17 +71,17 @@ def workout_strava_upload_view(request,id=0):
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
else:
|
||||
# ready to upload. Hurray
|
||||
# ready to upload. Hurray
|
||||
w = get_workout_permitted(request.user,id)
|
||||
r = w.user
|
||||
if (checkworkoutuser(request.user,w)):
|
||||
if (checkworkoutuser(request.user,w)):
|
||||
try:
|
||||
tcxfile,tcxmessg = stravastuff.createstravaworkoutdata(w)
|
||||
tcxfile,tcxmessg = stravastuff.createstravaworkoutdata(w)
|
||||
if tcxfile:
|
||||
with open(tcxfile,'rb') as f:
|
||||
with open(tcxfile,'rb') as f:
|
||||
try:
|
||||
newnotes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com'
|
||||
except TypeError:
|
||||
@@ -91,38 +91,38 @@ def workout_strava_upload_view(request,id=0):
|
||||
else:
|
||||
activity_type = mytypes.stravamapping[w.workouttype]
|
||||
|
||||
res,mes = stravastuff.handle_stravaexport(
|
||||
res,mes = stravastuff.handle_stravaexport(
|
||||
f,w.name,
|
||||
r.stravatoken,
|
||||
description=newnotes,
|
||||
r.stravatoken,
|
||||
description=newnotes,
|
||||
activity_type=activity_type)
|
||||
if res==0:
|
||||
messages.error(request,mes)
|
||||
w.uploadedtostrava = -1
|
||||
w.save()
|
||||
w.uploadedtostrava = -1
|
||||
w.save()
|
||||
try:
|
||||
os.remove(tcxfile)
|
||||
os.remove(tcxfile)
|
||||
except WindowsError:
|
||||
pass
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
return response
|
||||
|
||||
try:
|
||||
w.uploadedtostrava = res
|
||||
w.save()
|
||||
w.uploadedtostrava = res
|
||||
w.save()
|
||||
try:
|
||||
os.remove(tcxfile)
|
||||
os.remove(tcxfile)
|
||||
except WindowsError:
|
||||
pass
|
||||
url = reverse('workout_edit_view',kwargs={'id':w.id})
|
||||
|
||||
|
||||
messages.info(request,mes)
|
||||
except:
|
||||
except:
|
||||
with open("media/stravaerrors.log","a") as errorlog:
|
||||
errorstring = str(sys.exc_info()[0])
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
@@ -135,33 +135,33 @@ def workout_strava_upload_view(request,id=0):
|
||||
messages.error(request,message)
|
||||
w.uploadedtostrava = -1
|
||||
w.save()
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
|
||||
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
}
|
||||
)
|
||||
response = HttpResponseRedirect(url)
|
||||
except ActivityUploadFailed as e:
|
||||
message = "Strava Upload error: %s" % e
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
}
|
||||
)
|
||||
response = HttpResponseRedirect(url)
|
||||
except ActivityUploadFailed as e:
|
||||
message = "Strava Upload error: %s" % e
|
||||
messages.error(request,message)
|
||||
w.uploadedtostrava = -1
|
||||
w.save()
|
||||
os.remove(tcxfile)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
w.uploadedtostrava = -1
|
||||
w.save()
|
||||
os.remove(tcxfile)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
response = HttpResponseRedirect(url)
|
||||
|
||||
return response
|
||||
|
||||
return response
|
||||
|
||||
# Upload workout to Concept2 logbook
|
||||
@login_required()
|
||||
def workout_c2_upload_view(request,id=0):
|
||||
@@ -199,59 +199,59 @@ def workout_runkeeper_upload_view(request,id=0):
|
||||
r = w.user
|
||||
|
||||
try:
|
||||
thetoken = runkeeper_open(r.user)
|
||||
thetoken = runkeeper_open(r.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/runkeeperauthorize/")
|
||||
return HttpResponseRedirect("/rowers/me/runkeeperauthorize/")
|
||||
|
||||
# ready to upload. Hurray
|
||||
|
||||
if (checkworkoutuser(request.user,w)):
|
||||
data = runkeeperstuff.createrunkeeperworkoutdata(w)
|
||||
data = runkeeperstuff.createrunkeeperworkoutdata(w)
|
||||
if not data:
|
||||
message = "Data error"
|
||||
messages.error(request,message)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':id,
|
||||
})
|
||||
kwargs = {
|
||||
'id':id,
|
||||
})
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/vnd.com.runkeeper.NewFitnessActivity+json',
|
||||
'Content-Length':'nnn'}
|
||||
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.runkeeper.com/fitnessActivities"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
messages.error(request,message)
|
||||
w.uploadedtorunkeeper = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
runkeeperid = runkeeperstuff.getidfromresponse(response)
|
||||
w.uploadedtorunkeeper = runkeeperid
|
||||
w.save()
|
||||
w.uploadedtorunkeeper = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
runkeeperid = runkeeperstuff.getidfromresponse(response)
|
||||
w.uploadedtorunkeeper = runkeeperid
|
||||
w.save()
|
||||
url = reverse('workout_edit_view',
|
||||
kwargs={'id':encoder.encode_hex(w.id)})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_runkeeper_upload_view: %s - %s" % (s.reason,s.text)
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_runkeeper_upload_view: %s - %s" % (s.reason,s.text)
|
||||
messages.error(request,message)
|
||||
|
||||
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
messages.error(request,message)
|
||||
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -263,59 +263,59 @@ def workout_underarmour_upload_view(request,id=0):
|
||||
r = w.user
|
||||
|
||||
try:
|
||||
thetoken = underarmour_open(r.user)
|
||||
thetoken = underarmour_open(r.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/underarmourauthorize/")
|
||||
return HttpResponseRedirect("/rowers/me/underarmourauthorize/")
|
||||
|
||||
# ready to upload. Hurray
|
||||
|
||||
if (checkworkoutuser(request.user,w)):
|
||||
data = underarmourstuff.createunderarmourworkoutdata(w)
|
||||
data = underarmourstuff.createunderarmourworkoutdata(w)
|
||||
if not data:
|
||||
message = "Data error"
|
||||
messages.error(request,message)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'Api-Key': UNDERARMOUR_CLIENT_KEY,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
url = "https://api.ua.com/v7.1/workout/"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.ua.com/v7.1/workout/"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
messages.error(request,message)
|
||||
w.uploadedtounderarmour = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
underarmourid = underarmourstuff.getidfromresponse(response)
|
||||
w.uploadedtounderarmour = underarmourid
|
||||
w.save()
|
||||
w.uploadedtounderarmour = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
underarmourid = underarmourstuff.getidfromresponse(response)
|
||||
w.uploadedtounderarmour = underarmourid
|
||||
w.save()
|
||||
url = reverse('workout_edit_view',kwargs={'id':encoder.encode_hex(w.id)})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_underarmour_upload_view: %s " % s.reason
|
||||
messages.error(request,message)
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_underarmour_upload_view: %s " % s.reason
|
||||
messages.error(request,message)
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
messages.error(request,message)
|
||||
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -328,64 +328,64 @@ def workout_sporttracks_upload_view(request,id=0):
|
||||
r = w.user
|
||||
|
||||
try:
|
||||
thetoken = sporttracks_open(r.user)
|
||||
thetoken = sporttracks_open(r.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/sporttracksauthorize/")
|
||||
return HttpResponseRedirect("/rowers/me/sporttracksauthorize/")
|
||||
|
||||
|
||||
if (checkworkoutuser(request.user,w)):
|
||||
data = sporttracksstuff.createsporttracksworkoutdata(w)
|
||||
data = sporttracksstuff.createsporttracksworkoutdata(w)
|
||||
|
||||
if not data:
|
||||
message = "Data error"
|
||||
messages.error(request,message)
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
authorizationstring = str('Bearer ' + thetoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
# check for duplicate error first
|
||||
if (response.status_code == 409 ):
|
||||
message = "Duplicate error"
|
||||
messages.error(request,message)
|
||||
w.uploadedtosporttracks = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
s= response.json()
|
||||
sporttracksid = sporttracksstuff.getidfromresponse(response)
|
||||
w.uploadedtosporttracks = sporttracksid
|
||||
w.save()
|
||||
w.uploadedtosporttracks = -1
|
||||
w.save()
|
||||
elif (response.status_code == 201 or response.status_code==200):
|
||||
s= response.json()
|
||||
sporttracksid = sporttracksstuff.getidfromresponse(response)
|
||||
w.uploadedtosporttracks = sporttracksid
|
||||
w.save()
|
||||
message = "Upload to SportTracks was successful"
|
||||
messages.info(request,message)
|
||||
|
||||
url = reverse('workout_edit_view',kwargs={'id':encoder.encode_hex(w.id)})
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
|
||||
messages.error(request,message)
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
s = response
|
||||
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
|
||||
messages.error(request,message)
|
||||
else:
|
||||
message = "You are not authorized to upload this workout"
|
||||
message = "You are not authorized to upload this workout"
|
||||
messages.error(request,message)
|
||||
|
||||
url = reverse(r.defaultlandingpage,
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
kwargs = {
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
# Concept2 authorization
|
||||
# Concept2 authorization
|
||||
@login_required()
|
||||
def rower_c2_authorize(request):
|
||||
# Generate a random string for the state parameter
|
||||
@@ -411,7 +411,7 @@ def rower_strava_authorize(request):
|
||||
params = {"client_id": STRAVA_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"redirect_uri": STRAVA_REDIRECT_URI,
|
||||
"scope": "activity:write,activity:read_all"}
|
||||
"scope": "activity:write,activity:read_all"}
|
||||
|
||||
url = "https://www.strava.com/oauth/authorize?"+ urllib.urlencode(params)
|
||||
|
||||
@@ -427,7 +427,7 @@ def rower_polar_authorize(request):
|
||||
"response_type": "code",
|
||||
"redirect_uri": POLAR_REDIRECT_URI,
|
||||
"state": state,
|
||||
# "scope":"accesslink.read_all"
|
||||
# "scope":"accesslink.read_all"
|
||||
}
|
||||
url = "https://flow.polar.com/oauth2/authorization?" +urllib.urlencode(params)
|
||||
|
||||
@@ -445,7 +445,7 @@ def rower_runkeeper_authorize(request):
|
||||
|
||||
params = {"client_id": RUNKEEPER_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"state": state,
|
||||
"state": state,
|
||||
"redirect_uri": RUNKEEPER_REDIRECT_URI}
|
||||
|
||||
url = "https://runkeeper.com/apps/authorize?"+ urllib.urlencode(params)
|
||||
@@ -463,7 +463,7 @@ def rower_sporttracks_authorize(request):
|
||||
|
||||
params = {"client_id": SPORTTRACKS_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"state": state,
|
||||
"state": state,
|
||||
"redirect_uri": SPORTTRACKS_REDIRECT_URI}
|
||||
|
||||
url = "https://api.sporttracks.mobi/oauth2/authorize?"+ urllib.urlencode(params)
|
||||
@@ -499,7 +499,7 @@ def rower_tp_authorize(request):
|
||||
"response_type": "code",
|
||||
"redirect_uri": TP_REDIRECT_URI,
|
||||
"scope": "file:write",
|
||||
}
|
||||
}
|
||||
url = "https://oauth.trainingpeaks.com/oauth/authorize/?" +urllib.urlencode(params)
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
@@ -624,16 +624,16 @@ def rower_sporttracks_token_refresh(request):
|
||||
@login_required()
|
||||
def rower_process_callback(request):
|
||||
try:
|
||||
code = request.GET['code']
|
||||
res = c2stuff.get_token(code)
|
||||
code = request.GET['code']
|
||||
res = c2stuff.get_token(code)
|
||||
except MultiValueDictKeyError:
|
||||
message = "The resource owner or authorization server denied the request"
|
||||
message = "The resource owner or authorization server denied the request"
|
||||
messages.error(request,message)
|
||||
|
||||
url = reverse('workouts_view')
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
|
||||
access_token = res[0]
|
||||
if access_token == 0:
|
||||
message = res[1]
|
||||
@@ -643,7 +643,7 @@ def rower_process_callback(request):
|
||||
url = reverse('workouts_view')
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
|
||||
|
||||
expires_in = res[1]
|
||||
refresh_token = res[2]
|
||||
@@ -893,24 +893,24 @@ def workout_stravaimport_view(request,message="",userid=0):
|
||||
messages.info(request,"You cannot import other people's workouts from Strava")
|
||||
|
||||
try:
|
||||
thetoken = strava_open(request.user)
|
||||
thetoken = strava_open(request.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
|
||||
|
||||
res = stravastuff.get_strava_workout_list(request.user)
|
||||
|
||||
|
||||
if (res.status_code != 200):
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
message = "Something went wrong in workout_stravaimport_view"
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.stravatoken == '') or (r.stravatoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/stravaauthorize/")
|
||||
message = "Something went wrong in workout_stravaimport_view"
|
||||
messages.error(request,message)
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
workouts = []
|
||||
r = getrower(request.user)
|
||||
@@ -944,7 +944,7 @@ def workout_stravaimport_view(request,message="",userid=0):
|
||||
])
|
||||
newids = [stravaid for stravaid in stravaids if not stravaid in knownstravaids]
|
||||
|
||||
for item in res.json():
|
||||
for item in res.json():
|
||||
d = int(float(item['distance']))
|
||||
i = item['id']
|
||||
if i in knownstravaids:
|
||||
@@ -956,9 +956,9 @@ def workout_stravaimport_view(request,message="",userid=0):
|
||||
s = item['start_date']
|
||||
r = item['type']
|
||||
keys = ['id','distance','duration','starttime','type','name','new']
|
||||
values = [i,d,ttot,s,r,n,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
values = [i,d,ttot,s,r,n,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
|
||||
breadcrumbs = [
|
||||
{
|
||||
@@ -974,13 +974,13 @@ def workout_stravaimport_view(request,message="",userid=0):
|
||||
|
||||
r = getrower(request.user)
|
||||
|
||||
return render(request,'strava_list_import.html',
|
||||
{'workouts':workouts,
|
||||
return render(request,'strava_list_import.html',
|
||||
{'workouts':workouts,
|
||||
'rower':r,
|
||||
'active':'nav-workouts',
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'teams':get_my_teams(request.user),
|
||||
})
|
||||
})
|
||||
|
||||
return HttpResponse(res)
|
||||
|
||||
@@ -989,32 +989,32 @@ def workout_stravaimport_view(request,message="",userid=0):
|
||||
def workout_runkeeperimport_view(request,message="",userid=0):
|
||||
res = runkeeperstuff.get_runkeeper_workout_list(request.user)
|
||||
if (res.status_code != 200):
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.runkeepertoken == '') or (r.runkeepertoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/runkeeperauthorize/")
|
||||
message = "Something went wrong in workout_runkeeperimport_view"
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.runkeepertoken == '') or (r.runkeepertoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/runkeeperauthorize/")
|
||||
message = "Something went wrong in workout_runkeeperimport_view"
|
||||
messages.error(request,message)
|
||||
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
workouts = []
|
||||
for item in res.json()['items']:
|
||||
d = int(float(item['total_distance']))
|
||||
i = getidfromuri(item['uri'])
|
||||
d = int(float(item['total_distance']))
|
||||
i = getidfromuri(item['uri'])
|
||||
ttot = str(datetime.timedelta(seconds=int(float(item['duration']))))
|
||||
s = item['start_time']
|
||||
r = item['type']
|
||||
keys = ['id','distance','duration','starttime','type']
|
||||
values = [i,d,ttot,s,r]
|
||||
keys = ['id','distance','duration','starttime','type']
|
||||
values = [i,d,ttot,s,r]
|
||||
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
|
||||
breadcrumbs = [
|
||||
{
|
||||
@@ -1030,12 +1030,12 @@ def workout_runkeeperimport_view(request,message="",userid=0):
|
||||
r = getrower(request.user)
|
||||
|
||||
return render(request,'runkeeper_list_import.html',
|
||||
{'workouts':workouts,
|
||||
{'workouts':workouts,
|
||||
'rower':r,
|
||||
'active':'nav-workouts',
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'teams':get_my_teams(request.user),
|
||||
})
|
||||
})
|
||||
|
||||
return HttpResponse(res)
|
||||
|
||||
@@ -1044,14 +1044,14 @@ def workout_runkeeperimport_view(request,message="",userid=0):
|
||||
def workout_underarmourimport_view(request,message="",userid=0):
|
||||
res = underarmourstuff.get_underarmour_workout_list(request.user)
|
||||
if (res.status_code != 200):
|
||||
return HttpResponseRedirect("/rowers/me/underarmourauthorize/")
|
||||
return HttpResponseRedirect("/rowers/me/underarmourauthorize/")
|
||||
|
||||
workouts = []
|
||||
items = res.json()['_embedded']['workouts']
|
||||
for item in items:
|
||||
s = item['start_datetime']
|
||||
s = item['start_datetime']
|
||||
i,r = underarmourstuff.get_idfromuri(request.user,item['_links'])
|
||||
n = item['name']
|
||||
n = item['name']
|
||||
try:
|
||||
d = item['aggregates']['distance_total']
|
||||
except KeyError:
|
||||
@@ -1061,11 +1061,11 @@ def workout_underarmourimport_view(request,message="",userid=0):
|
||||
except KeyError:
|
||||
ttot = 0
|
||||
|
||||
keys = ['id','distance','duration','starttime','type']
|
||||
values = [i,d,ttot,s,r]
|
||||
thedict = dict(zip(keys,values))
|
||||
keys = ['id','distance','duration','starttime','type']
|
||||
values = [i,d,ttot,s,r]
|
||||
thedict = dict(zip(keys,values))
|
||||
|
||||
workouts.append(thedict)
|
||||
workouts.append(thedict)
|
||||
|
||||
rower = getrower(request.user)
|
||||
breadcrumbs = [
|
||||
@@ -1080,12 +1080,12 @@ def workout_underarmourimport_view(request,message="",userid=0):
|
||||
]
|
||||
|
||||
return render(request,'underarmour_list_import.html',
|
||||
{'workouts':workouts,
|
||||
{'workouts':workouts,
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'rower':rower,
|
||||
'active':'nav-workouts',
|
||||
'teams':get_my_teams(request.user),
|
||||
})
|
||||
})
|
||||
|
||||
return HttpResponse(res)
|
||||
|
||||
@@ -1153,20 +1153,20 @@ def workout_sporttracksimport_view(request,message="",userid=0):
|
||||
|
||||
res = sporttracksstuff.get_sporttracks_workout_list(request.user)
|
||||
if (res.status_code != 200):
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/sporttracksauthorize/")
|
||||
if (res.status_code == 401):
|
||||
r = getrower(request.user)
|
||||
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return HttpResponseRedirect("/rowers/me/sporttracksauthorize/")
|
||||
else:
|
||||
return HttpResponseRedirect("/rowers/me/sporttracksrefresh/")
|
||||
message = "Something went wrong in workout_sporttracksimport_view"
|
||||
message = "Something went wrong in workout_sporttracksimport_view"
|
||||
messages.error(request,message)
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
workouts = []
|
||||
r = getrower(request.user)
|
||||
@@ -1177,19 +1177,19 @@ def workout_sporttracksimport_view(request,message="",userid=0):
|
||||
newids = [stid for stid in stids if not stid in knownstids]
|
||||
for item in res.json()['items']:
|
||||
d = int(float(item['total_distance']))
|
||||
i = int(getidfromuri(item['uri']))
|
||||
i = int(getidfromuri(item['uri']))
|
||||
if i in knownstids:
|
||||
nnn = ''
|
||||
else:
|
||||
nnn = 'NEW'
|
||||
n = item['name']
|
||||
ttot = str(datetime.timedelta(seconds=int(float(item['duration']))))
|
||||
s = item['start_time']
|
||||
r = item['type']
|
||||
keys = ['id','distance','duration','starttime','type','name','new']
|
||||
values = [i,d,ttot,s,r,n,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
n = item['name']
|
||||
ttot = str(datetime.timedelta(seconds=int(float(item['duration']))))
|
||||
s = item['start_time']
|
||||
r = item['type']
|
||||
keys = ['id','distance','duration','starttime','type','name','new']
|
||||
values = [i,d,ttot,s,r,n,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
|
||||
r = getrower(request.user)
|
||||
|
||||
@@ -1205,55 +1205,55 @@ def workout_sporttracksimport_view(request,message="",userid=0):
|
||||
]
|
||||
|
||||
return render(request,'sporttracks_list_import.html',
|
||||
{'workouts':workouts,
|
||||
{'workouts':workouts,
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'active':'nav-workouts',
|
||||
'rower':r,
|
||||
'teams':get_my_teams(request.user),
|
||||
})
|
||||
})
|
||||
|
||||
return HttpResponse(res)
|
||||
|
||||
|
||||
# List of workouts on Concept2 logbook. This view only used for debugging
|
||||
@login_required()
|
||||
def c2listdebug_view(request,page=1,message=""):
|
||||
try:
|
||||
thetoken = c2_open(request.user)
|
||||
thetoken = c2_open(request.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
|
||||
r = getrower(request.user)
|
||||
|
||||
res = c2stuff.get_c2_workout_list(request.user,page=page)
|
||||
|
||||
if (res.status_code != 200):
|
||||
message = "Something went wrong in workout_c2import_view (C2 token renewal)"
|
||||
message = "Something went wrong in workout_c2import_view (C2 token renewal)"
|
||||
messages.error(request,message)
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
if settings.DEBUG:
|
||||
return HttpResponse(res)
|
||||
else:
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
else:
|
||||
workouts = []
|
||||
workouts = []
|
||||
|
||||
for item in res.json()['data']:
|
||||
d = item['distance']
|
||||
i = item['id']
|
||||
ttot = item['time_formatted']
|
||||
s = item['date']
|
||||
r = item['type']
|
||||
s2 = item['source']
|
||||
c = item['comments']
|
||||
keys = ['id','distance','duration','starttime','rowtype','source','comment']
|
||||
values = [i,d,ttot,s,r,s2,c]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
for item in res.json()['data']:
|
||||
d = item['distance']
|
||||
i = item['id']
|
||||
ttot = item['time_formatted']
|
||||
s = item['date']
|
||||
r = item['type']
|
||||
s2 = item['source']
|
||||
c = item['comments']
|
||||
keys = ['id','distance','duration','starttime','rowtype','source','comment']
|
||||
values = [i,d,ttot,s,r,s2,c]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
|
||||
|
||||
return render(request,
|
||||
'c2_list_import2.html',
|
||||
{'workouts':workouts,
|
||||
|
||||
return render(request,
|
||||
'c2_list_import2.html',
|
||||
{'workouts':workouts,
|
||||
'teams':get_my_teams(request.user),
|
||||
})
|
||||
|
||||
@@ -1261,14 +1261,14 @@ def c2listdebug_view(request,page=1,message=""):
|
||||
@login_required()
|
||||
def workout_getc2workout_all(request,page=1,message=""):
|
||||
try:
|
||||
thetoken = c2_open(request.user)
|
||||
thetoken = c2_open(request.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
|
||||
res = c2stuff.get_c2_workout_list(request.user,page=page)
|
||||
|
||||
if (res.status_code != 200):
|
||||
message = "Something went wrong in workout_c2import_view (C2 token refresh)"
|
||||
message = "Something went wrong in workout_c2import_view (C2 token refresh)"
|
||||
messages.error(request,message)
|
||||
else:
|
||||
r = getrower(request.user)
|
||||
@@ -1302,17 +1302,17 @@ def workout_c2import_view(request,page=1,userid=0,message=""):
|
||||
r = getrower(request.user)
|
||||
|
||||
try:
|
||||
thetoken = c2_open(request.user)
|
||||
thetoken = c2_open(request.user)
|
||||
except NoTokenError:
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
return HttpResponseRedirect("/rowers/me/c2authorize/")
|
||||
|
||||
res = c2stuff.get_c2_workout_list(request.user,page=page)
|
||||
|
||||
if (res.status_code != 200):
|
||||
message = "Something went wrong in workout_c2import_view (C2 token refresh)"
|
||||
message = "Something went wrong in workout_c2import_view (C2 token refresh)"
|
||||
messages.error(request,message)
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
url = reverse('workouts_view')
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
workouts = []
|
||||
c2ids = [item['id'] for item in res.json()['data']]
|
||||
@@ -1321,21 +1321,21 @@ def workout_c2import_view(request,page=1,userid=0,message=""):
|
||||
])
|
||||
newids = [c2id for c2id in c2ids if not c2id in knownc2ids]
|
||||
for item in res.json()['data']:
|
||||
d = item['distance']
|
||||
i = item['id']
|
||||
ttot = item['time_formatted']
|
||||
s = item['date']
|
||||
r = item['type']
|
||||
s2 = item['source']
|
||||
c = item['comments']
|
||||
d = item['distance']
|
||||
i = item['id']
|
||||
ttot = item['time_formatted']
|
||||
s = item['date']
|
||||
r = item['type']
|
||||
s2 = item['source']
|
||||
c = item['comments']
|
||||
if i in knownc2ids:
|
||||
nnn = ''
|
||||
else:
|
||||
nnn = 'NEW'
|
||||
keys = ['id','distance','duration','starttime','rowtype','source','comment','new']
|
||||
values = [i,d,ttot,s,r,s2,c,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
keys = ['id','distance','duration','starttime','rowtype','source','comment','new']
|
||||
values = [i,d,ttot,s,r,s2,c,nnn]
|
||||
res = dict(zip(keys,values))
|
||||
workouts.append(res)
|
||||
|
||||
|
||||
breadcrumbs = [
|
||||
@@ -1356,8 +1356,8 @@ def workout_c2import_view(request,page=1,userid=0,message=""):
|
||||
r = getrower(request.user)
|
||||
|
||||
return render(request,
|
||||
'c2_list_import2.html',
|
||||
{'workouts':workouts,
|
||||
'c2_list_import2.html',
|
||||
{'workouts':workouts,
|
||||
'rower':r,
|
||||
'active':'nav-workouts',
|
||||
'breadcrumbs':breadcrumbs,
|
||||
@@ -1449,7 +1449,7 @@ def workout_getimportview(request,externalid,source = 'c2'):
|
||||
'id':encoder.encode_hex(w.id),
|
||||
})
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
# strokedata not empty - continue
|
||||
id,message = importsources[source].add_workout_from_data(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
@login_required()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
def paidplans_view(request):
|
||||
if not request.user.is_anonymous():
|
||||
@@ -478,32 +478,32 @@ def rower_register_view(request):
|
||||
nextpage = '/rowers/list-workouts/'
|
||||
|
||||
if request.method == 'POST':
|
||||
#form = RegistrationFormUniqueEmail(request.POST)
|
||||
form = RegistrationFormSex(request.POST)
|
||||
if form.is_valid():
|
||||
first_name = form.cleaned_data['first_name']
|
||||
last_name = form.cleaned_data['last_name']
|
||||
email = form.cleaned_data['email']
|
||||
password = form.cleaned_data['password1']
|
||||
username = form.cleaned_data['username']
|
||||
#form = RegistrationFormUniqueEmail(request.POST)
|
||||
form = RegistrationFormSex(request.POST)
|
||||
if form.is_valid():
|
||||
first_name = form.cleaned_data['first_name']
|
||||
last_name = form.cleaned_data['last_name']
|
||||
email = form.cleaned_data['email']
|
||||
password = form.cleaned_data['password1']
|
||||
username = form.cleaned_data['username']
|
||||
sex = form.cleaned_data['sex']
|
||||
birthdate = form.cleaned_data['birthdate']
|
||||
weightcategory = form.cleaned_data['weightcategory']
|
||||
adaptiveclass = form.cleaned_data['adaptiveclass']
|
||||
nextpage = request.POST['next']
|
||||
theuser = User.objects.create_user(username,password=password)
|
||||
theuser.first_name = first_name
|
||||
theuser.last_name = last_name
|
||||
theuser.email = email
|
||||
theuser.save()
|
||||
theuser = User.objects.create_user(username,password=password)
|
||||
theuser.first_name = first_name
|
||||
theuser.last_name = last_name
|
||||
theuser.email = email
|
||||
theuser.save()
|
||||
|
||||
birthdate = birthdate.replace(tzinfo=None)
|
||||
|
||||
therower = Rower(user=theuser,sex=sex,birthdate=birthdate,
|
||||
therower = Rower(user=theuser,sex=sex,birthdate=birthdate,
|
||||
weightcategory=weightcategory,
|
||||
adaptiveclass=adaptiveclass)
|
||||
|
||||
therower.save()
|
||||
therower.save()
|
||||
|
||||
# create default favorite charts
|
||||
add_defaultfavorites(therower)
|
||||
@@ -523,8 +523,8 @@ def rower_register_view(request):
|
||||
w.save()
|
||||
|
||||
# Create and send email
|
||||
fullemail = first_name + " " + last_name + " " + "<" + email + ">"
|
||||
subject = "Thank you for registering on rowsandall.com"
|
||||
fullemail = first_name + " " + last_name + " " + "<" + email + ">"
|
||||
subject = "Thank you for registering on rowsandall.com"
|
||||
from_address = 'Sander Roosendaal <info@rowsandall.com>'
|
||||
|
||||
d = {'first_name':theuser.first_name}
|
||||
@@ -533,31 +533,31 @@ def rower_register_view(request):
|
||||
subject,'registeremail.html',d)
|
||||
|
||||
|
||||
subject2 = "New User"
|
||||
message2 = "New user registered.\n"
|
||||
message2 += fullemail + "\n"
|
||||
message2 += "User name: "+username
|
||||
subject2 = "New User"
|
||||
message2 = "New user registered.\n"
|
||||
message2 += fullemail + "\n"
|
||||
message2 += "User name: "+username
|
||||
|
||||
send_mail(subject2, message2,
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
send_mail(subject2, message2,
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
|
||||
theuser = authenticate(username=username,password=password)
|
||||
login(request,theuser)
|
||||
|
||||
return HttpResponseRedirect(nextpage)
|
||||
return HttpResponseRedirect(nextpage)
|
||||
# '/rowers/register/thankyou/')
|
||||
|
||||
else:
|
||||
return render(request,
|
||||
"registration_form.html",
|
||||
{'form':form,
|
||||
else:
|
||||
return render(request,
|
||||
"registration_form.html",
|
||||
{'form':form,
|
||||
'next':nextpage,})
|
||||
else:
|
||||
form = RegistrationFormSex()
|
||||
return render(request,
|
||||
"registration_form.html",
|
||||
{'form':form,
|
||||
form = RegistrationFormSex()
|
||||
return render(request,
|
||||
"registration_form.html",
|
||||
{'form':form,
|
||||
'next':nextpage,})
|
||||
|
||||
@login_required()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
@login_required()
|
||||
def plannedsession_comment_view(request,id=0,userid=0):
|
||||
@@ -496,8 +496,6 @@ def plannedsession_multicreate_view(request,
|
||||
for obj in ps_formset.deleted_objects:
|
||||
messages.info(request,"Deleted Planned Session "+str(obj))
|
||||
obj.delete()
|
||||
else:
|
||||
print ps_formset.errors
|
||||
|
||||
url = reverse(plannedsession_multicreate_view,
|
||||
kwargs = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
# List Courses
|
||||
@@ -653,7 +653,7 @@ def virtualevent_disqualify_view(request,raceid=0,recordid=0):
|
||||
latitude = rowdata.df[' latitude']
|
||||
if not latitude.std():
|
||||
hascoordinates = 0
|
||||
except KeyError, AttributeError:
|
||||
except (KeyError, AttributeError):
|
||||
hascoordinates = 0
|
||||
else:
|
||||
hascoordinates = 0
|
||||
|
||||
+95
-88
@@ -1,7 +1,7 @@
|
||||
|
||||
import time
|
||||
import colorsys
|
||||
import timestring
|
||||
|
||||
import zipfile
|
||||
import bleach
|
||||
import arrow
|
||||
@@ -56,7 +56,11 @@ from rowers.forms import (
|
||||
MetricsForm,DisqualificationForm,disqualificationreasons,
|
||||
disqualifiers,SearchForm,BillingForm,PlanSelectForm
|
||||
)
|
||||
from django.core.urlresolvers import reverse, reverse_lazy
|
||||
|
||||
try:
|
||||
from django.core.urlresolvers import reverse, reverse_lazy
|
||||
except ModuleNotFoundError:
|
||||
from django.urls import reverse, reverse_lazy
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.template import RequestContext
|
||||
@@ -181,7 +185,10 @@ from rowers.tasks import (
|
||||
|
||||
from scipy.signal import savgol_filter
|
||||
from django.shortcuts import render_to_response
|
||||
from Cookie import SimpleCookie
|
||||
try:
|
||||
from Cookie import SimpleCookie
|
||||
except ModuleNotFoundError:
|
||||
from http.cookies import SimpleCookie
|
||||
from shutil import copyfile,move
|
||||
import rowers.mytypes as mytypes
|
||||
from rowingdata import rower as rrower
|
||||
@@ -287,7 +294,7 @@ def getrequestrower(request,rowerid=0,userid=0,notpermanent=False):
|
||||
u = User.objects.get(id=userid)
|
||||
r = getrower(u)
|
||||
else:
|
||||
r = getrower(request.user)
|
||||
r = getrower(request.user)
|
||||
|
||||
except Rower.DoesNotExist:
|
||||
raise Http404("Rower doesn't exist")
|
||||
@@ -320,7 +327,7 @@ def getrequestplanrower(request,rowerid=0,userid=0,notpermanent=False):
|
||||
u = User.objects.get(id=userid)
|
||||
r = getrower(u)
|
||||
else:
|
||||
r = getrower(request.user)
|
||||
r = getrower(request.user)
|
||||
|
||||
except Rower.DoesNotExist:
|
||||
raise Http404("Rower doesn't exist")
|
||||
@@ -415,7 +422,7 @@ class SessionTaskListener(threading.Thread):
|
||||
for item in self.pubsub.listen():
|
||||
if item['data'] == "KILL":
|
||||
self.pubsub.unsubscribe()
|
||||
print self, "unsubscribed and finished"
|
||||
print(self, "unsubscribed and finished")
|
||||
break
|
||||
else:
|
||||
self.work(item)
|
||||
@@ -465,7 +472,7 @@ from rowers.interactiveplots import *
|
||||
from rowers.celery import result as celery_result
|
||||
|
||||
# Define the API documentation
|
||||
schema_view = get_swagger_view(title='Rowsandall API')
|
||||
#schema_view = get_swagger_view(title='Rowsandall API')
|
||||
|
||||
def remove_asynctask(request,id):
|
||||
try:
|
||||
@@ -740,9 +747,9 @@ def get_thumbnails(request,id):
|
||||
r = getrower(request.user)
|
||||
result = request.user.is_authenticated() and ispromember(request.user)
|
||||
if result:
|
||||
promember=1
|
||||
promember=1
|
||||
if request.user == row.user.user:
|
||||
mayedit=1
|
||||
mayedit=1
|
||||
|
||||
comments = WorkoutComment.objects.filter(workout=row)
|
||||
|
||||
@@ -872,7 +879,7 @@ def rowhascoordinates(row):
|
||||
|
||||
if not latitude.std():
|
||||
hascoordinates = 0
|
||||
except KeyError,AttributeError:
|
||||
except (KeyError,AttributeError):
|
||||
hascoordinates = 0
|
||||
|
||||
else:
|
||||
@@ -885,11 +892,11 @@ def rowhascoordinates(row):
|
||||
# Checks for CSV file, then for gzipped CSV file, and if all fails, returns 0
|
||||
def rdata(file,rower=rrower()):
|
||||
try:
|
||||
res = rrdata(csvfile=file,rower=rower)
|
||||
except IOError, IndexError:
|
||||
res = rrdata(csvfile=file,rower=rower)
|
||||
except (IOError, IndexError):
|
||||
try:
|
||||
res = rrdata(csvfile=file+'.gz',rower=rower)
|
||||
except IOError, IndexError:
|
||||
except (IOError, IndexError):
|
||||
res = 0
|
||||
|
||||
return res
|
||||
@@ -913,24 +920,24 @@ def get_my_teams(user):
|
||||
# Used for the interval editor - translates seconds to a time object
|
||||
def get_time(second):
|
||||
if (second<=0) or (second>1e9):
|
||||
hours = 0
|
||||
minutes=0
|
||||
sec=0
|
||||
microsecond = 0
|
||||
hours = 0
|
||||
minutes=0
|
||||
sec=0
|
||||
microsecond = 0
|
||||
elif math.isnan(second):
|
||||
hours = 0
|
||||
minutes=0
|
||||
sec=0
|
||||
microsecond = 0
|
||||
hours = 0
|
||||
minutes=0
|
||||
sec=0
|
||||
microsecond = 0
|
||||
else:
|
||||
days = int(second/(24.*3600.)) % (24*3600)
|
||||
hours = int((second-24.*3600.*days)/3600.) % 24
|
||||
minutes = int((second-3600.*(hours+24.*days))/60.) % 60
|
||||
sec = int(second-3600.*(hours+24.*days)-60.*minutes) % 60
|
||||
microsecond = int(1.0e6*(second-3600.*(hours+24.*days)-60.*minutes-sec))
|
||||
days = int(second/(24.*3600.)) % (24*3600)
|
||||
hours = int((second-24.*3600.*days)/3600.) % 24
|
||||
minutes = int((second-3600.*(hours+24.*days))/60.) % 60
|
||||
sec = int(second-3600.*(hours+24.*days)-60.*minutes) % 60
|
||||
microsecond = int(1.0e6*(second-3600.*(hours+24.*days)-60.*minutes-sec))
|
||||
return datetime.time(hours,minutes,sec,microsecond)
|
||||
|
||||
|
||||
|
||||
# get the workout ID from the SportTracks URI
|
||||
def getidfromsturi(uri,length=8):
|
||||
return uri[len(uri)-length:]
|
||||
@@ -942,7 +949,7 @@ def getidfromuri(uri):
|
||||
return m.group(2)
|
||||
|
||||
|
||||
|
||||
|
||||
from rowers.utils import (
|
||||
geo_distance,serialize_list,deserialize_list,uniqify,
|
||||
str2bool,range_to_color_hex,absolute,myqueue,get_call,
|
||||
@@ -1041,24 +1048,24 @@ def sendmail(request):
|
||||
if request.method == 'POST':
|
||||
form = EmailForm(request.POST)
|
||||
if form.is_valid():
|
||||
firstname = form.cleaned_data['firstname']
|
||||
lastname = form.cleaned_data['lastname']
|
||||
email = form.cleaned_data['email']
|
||||
subject = form.cleaned_data['subject']
|
||||
botcheck = form.cleaned_data['botcheck'].lower()
|
||||
message = form.cleaned_data['message']
|
||||
if botcheck == 'yes':
|
||||
try:
|
||||
fullemail = firstname + " " + lastname + " " + "<" + email + ">"
|
||||
send_mail(subject, message, fullemail, ['info@rowsandall.com'])
|
||||
return HttpResponseRedirect('/rowers/email/thankyou/')
|
||||
except:
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
else:
|
||||
firstname = form.cleaned_data['firstname']
|
||||
lastname = form.cleaned_data['lastname']
|
||||
email = form.cleaned_data['email']
|
||||
subject = form.cleaned_data['subject']
|
||||
botcheck = form.cleaned_data['botcheck'].lower()
|
||||
message = form.cleaned_data['message']
|
||||
if botcheck == 'yes':
|
||||
try:
|
||||
fullemail = firstname + " " + lastname + " " + "<" + email + ">"
|
||||
send_mail(subject, message, fullemail, ['info@rowsandall.com'])
|
||||
return HttpResponseRedirect('/rowers/email/thankyou/')
|
||||
except:
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
else:
|
||||
messages.error(request,'You have to answer YES to the question')
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
else:
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
else:
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
else:
|
||||
return HttpResponseRedirect('/rowers/email/')
|
||||
|
||||
@@ -1074,43 +1081,43 @@ def add_workout_from_strokedata(user,importid,data,strokedata,
|
||||
workouttype = 'rower'
|
||||
|
||||
if workouttype not in [x[0] for x in Workout.workouttypes]:
|
||||
workouttype = 'other'
|
||||
workouttype = 'other'
|
||||
try:
|
||||
comments = data['comments']
|
||||
comments = data['comments']
|
||||
except:
|
||||
comments = ' '
|
||||
comments = ' '
|
||||
|
||||
# comments = "Imported data \n %s" % comments
|
||||
# comments = "Imported data \n"+comments # str(comments)
|
||||
try:
|
||||
thetimezone = tz(data['timezone'])
|
||||
thetimezone = tz(data['timezone'])
|
||||
except:
|
||||
thetimezone = 'UTC'
|
||||
thetimezone = 'UTC'
|
||||
|
||||
r = getrower(user)
|
||||
try:
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
rowdatetime = iso8601.parse_date(data['date_utc'])
|
||||
except KeyError:
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
rowdatetime = iso8601.parse_date(data['start_date'])
|
||||
except ParseError:
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
rowdatetime = iso8601.parse_date(data['date'])
|
||||
|
||||
|
||||
|
||||
try:
|
||||
c2intervaltype = data['workout_type']
|
||||
|
||||
|
||||
except KeyError:
|
||||
c2intervaltype = ''
|
||||
|
||||
c2intervaltype = ''
|
||||
|
||||
try:
|
||||
title = data['name']
|
||||
title = data['name']
|
||||
except KeyError:
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
title = ""
|
||||
try:
|
||||
t = data['comments'].split('\n', 1)[0]
|
||||
title += t[:20]
|
||||
except:
|
||||
title = 'Imported'
|
||||
|
||||
starttimeunix = arrow.get(rowdatetime).timestamp
|
||||
|
||||
@@ -1125,17 +1132,17 @@ def add_workout_from_strokedata(user,importid,data,strokedata,
|
||||
nr_rows = len(unixtime)
|
||||
|
||||
try:
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
latcoord = strokedata.loc[:,'lat']
|
||||
loncoord = strokedata.loc[:,'lon']
|
||||
except:
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
latcoord = np.zeros(nr_rows)
|
||||
loncoord = np.zeros(nr_rows)
|
||||
|
||||
|
||||
try:
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
strokelength = strokedata.loc[:,'strokelength']
|
||||
except:
|
||||
strokelength = np.zeros(nr_rows)
|
||||
strokelength = np.zeros(nr_rows)
|
||||
|
||||
dist2 = 0.1*strokedata.loc[:,'d']
|
||||
|
||||
@@ -1159,27 +1166,27 @@ def add_workout_from_strokedata(user,importid,data,strokedata,
|
||||
# save csv
|
||||
# Create data frame with all necessary data to write to csv
|
||||
df = pd.DataFrame({'TimeStamp (sec)':unixtime,
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
' Horizontal (meters)': dist2,
|
||||
' Cadence (stokes/min)':spm,
|
||||
' HRCur (bpm)':hr,
|
||||
' longitude':loncoord,
|
||||
' latitude':latcoord,
|
||||
' Stroke500mPace (sec/500m)':pace,
|
||||
' Power (watts)':power,
|
||||
' DragFactor':np.zeros(nr_rows),
|
||||
' DriveLength (meters)':np.zeros(nr_rows),
|
||||
' StrokeDistance (meters)':strokelength,
|
||||
' DriveTime (ms)':np.zeros(nr_rows),
|
||||
' StrokeRecoveryTime (ms)':np.zeros(nr_rows),
|
||||
' AverageDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' PeakDriveForce (lbs)':np.zeros(nr_rows),
|
||||
' lapIdx':lapidx,
|
||||
' ElapsedTime (sec)':seconds
|
||||
})
|
||||
|
||||
|
||||
df.sort_values(by='TimeStamp (sec)',ascending=True)
|
||||
|
||||
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
|
||||
@login_required()
|
||||
|
||||
+41
-41
@@ -1,4 +1,4 @@
|
||||
from statements import *
|
||||
from rowers.views.statements import *
|
||||
|
||||
@login_required()
|
||||
def start_trial_view(request):
|
||||
@@ -22,8 +22,8 @@ def start_trial_view(request):
|
||||
message2 += "User name: "+request.user.username
|
||||
|
||||
send_mail(subject2, message2,
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -50,8 +50,8 @@ def start_plantrial_view(request):
|
||||
message2 += "User name: "+request.user.username
|
||||
|
||||
send_mail(subject2, message2,
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
'Rowsandall Server <info@rowsandall.com>',
|
||||
['roosendaalsander@gmail.com'])
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
@@ -151,7 +151,7 @@ def rower_exportsettings_view(request,userid=0):
|
||||
]
|
||||
|
||||
return render(request, 'rower_exportsettings.html',
|
||||
{'form':form,
|
||||
{'form':form,
|
||||
'rower':r,
|
||||
'breadcrumbs': breadcrumbs,
|
||||
})
|
||||
@@ -242,14 +242,14 @@ def rower_edit_view(request,rowerid=0,userid=0,message=""):
|
||||
|
||||
grants = AccessToken.objects.filter(user=request.user)
|
||||
return render(request, 'rower_form.html',
|
||||
{
|
||||
{
|
||||
'teams':get_my_teams(request.user),
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'grants':grants,
|
||||
'userform':userform,
|
||||
'accountform':accountform,
|
||||
'rower':r,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
# Page where user can set his details
|
||||
@@ -276,43 +276,43 @@ def rower_prefs_view(request,userid=0,message=""):
|
||||
powerzonesform = RowerPowerZonesForm(instance=r)
|
||||
|
||||
if request.method == 'POST' and "ut2" in request.POST:
|
||||
form = RowerForm(request.POST)
|
||||
if form.is_valid():
|
||||
# something
|
||||
cd = form.cleaned_data
|
||||
hrmax = cd['max']
|
||||
ut2 = cd['ut2']
|
||||
ut1 = cd['ut1']
|
||||
at = cd['at']
|
||||
tr = cd['tr']
|
||||
an = cd['an']
|
||||
rest = cd['rest']
|
||||
form = RowerForm(request.POST)
|
||||
if form.is_valid():
|
||||
# something
|
||||
cd = form.cleaned_data
|
||||
hrmax = cd['max']
|
||||
ut2 = cd['ut2']
|
||||
ut1 = cd['ut1']
|
||||
at = cd['at']
|
||||
tr = cd['tr']
|
||||
an = cd['an']
|
||||
rest = cd['rest']
|
||||
|
||||
r.max = max(min(hrmax,250),10)
|
||||
r.ut2 = max(min(ut2,250),10)
|
||||
r.ut1 = max(min(ut1,250),10)
|
||||
r.at = max(min(at,250),10)
|
||||
r.tr = max(min(tr,250),10)
|
||||
r.an = max(min(an,250),10)
|
||||
r.rest = max(min(rest,250),10)
|
||||
r.save()
|
||||
r.max = max(min(hrmax,250),10)
|
||||
r.ut2 = max(min(ut2,250),10)
|
||||
r.ut1 = max(min(ut1,250),10)
|
||||
r.at = max(min(at,250),10)
|
||||
r.tr = max(min(tr,250),10)
|
||||
r.an = max(min(an,250),10)
|
||||
r.rest = max(min(rest,250),10)
|
||||
r.save()
|
||||
successmessage = "Your Heart Rate data were changed"
|
||||
messages.info(request,successmessage)
|
||||
elif request.method == 'POST' and "ftp" in request.POST:
|
||||
powerform = RowerPowerForm(request.POST)
|
||||
if powerform.is_valid():
|
||||
cd = powerform.cleaned_data
|
||||
powerform = RowerPowerForm(request.POST)
|
||||
if powerform.is_valid():
|
||||
cd = powerform.cleaned_data
|
||||
hrftp = cd['hrftp']
|
||||
if hrftp == 0:
|
||||
hrftp = int((r.an+r.tr)/2.)
|
||||
ftp = cd['ftp']
|
||||
ftp = cd['ftp']
|
||||
otwslack = cd['otwslack']
|
||||
|
||||
powerfrac = 100*np.array([r.pw_ut2,
|
||||
r.pw_ut1,
|
||||
r.pw_at,
|
||||
r.pw_tr,r.pw_an])/r.ftp
|
||||
r.ftp = max(min(ftp,650),50)
|
||||
r.ftp = max(min(ftp,650),50)
|
||||
r.otwslack = max(min(otwslack,50),0)
|
||||
ut2,ut1,at,tr,an = (r.ftp*powerfrac/100.).astype(int)
|
||||
r.pw_ut2 = ut2
|
||||
@@ -321,14 +321,14 @@ def rower_prefs_view(request,userid=0,message=""):
|
||||
r.pw_tr = tr
|
||||
r.pw_an = an
|
||||
r.hrftp = hrftp
|
||||
r.save()
|
||||
message = "FTP and/or OTW slack values changed."
|
||||
r.save()
|
||||
message = "FTP and/or OTW slack values changed."
|
||||
messages.info(request,message)
|
||||
|
||||
elif request.method == 'POST' and "ut3name" in request.POST:
|
||||
powerzonesform = RowerPowerZonesForm(request.POST)
|
||||
if powerzonesform.is_valid():
|
||||
cd = powerzonesform.cleaned_data
|
||||
powerzonesform = RowerPowerZonesForm(request.POST)
|
||||
if powerzonesform.is_valid():
|
||||
cd = powerzonesform.cleaned_data
|
||||
pw_ut2 = cd['pw_ut2']
|
||||
pw_ut1 = cd['pw_ut1']
|
||||
pw_at = cd['pw_at']
|
||||
@@ -353,14 +353,14 @@ def rower_prefs_view(request,userid=0,message=""):
|
||||
messages.info(request,successmessage)
|
||||
|
||||
return render(request, 'rower_preferences.html',
|
||||
{
|
||||
'form':form,
|
||||
{
|
||||
'form':form,
|
||||
'teams':get_my_teams(request.user),
|
||||
'powerform':powerform,
|
||||
'powerform':powerform,
|
||||
'powerzonesform':powerzonesform,
|
||||
'breadcrumbs':breadcrumbs,
|
||||
'rower':r,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
# Revoke an app that you granted access through the API.
|
||||
|
||||
+633
-633
File diff suppressed because it is too large
Load Diff
+30
-29
@@ -1,3 +1,4 @@
|
||||
from __future__ import unicode_literals, absolute_import
|
||||
import requests
|
||||
import json
|
||||
from lxml import objectify,etree
|
||||
@@ -30,9 +31,9 @@ def get_weather_data(long,lat,unixtime):
|
||||
s = requests.get(url)
|
||||
|
||||
if s.ok:
|
||||
return s.json()
|
||||
return s.json()
|
||||
else:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
# Get Metar data
|
||||
def get_metar_data(airportcode,unixtime):
|
||||
@@ -78,7 +79,7 @@ def get_metar_data(airportcode,unixtime):
|
||||
|
||||
message = 'Summary for your location at '+timestamp+': '
|
||||
message += 'Temperature '+temp_c+'C/'+temp_f+'F'
|
||||
message += '. Wind: '+str(wind_ms)+' m/s ('+str(wind_knots)+' kt)'
|
||||
message += '. Wind: '+str(wind_ms)+' m/s ('+str(wind_knots)+' kt)'
|
||||
message +='. Wind Bearing: '+str(windbearing)+' degrees'
|
||||
# message +='\n'+rawtext
|
||||
|
||||
@@ -93,36 +94,36 @@ def get_metar_data(airportcode,unixtime):
|
||||
def get_wind_data(lat,long,unixtime):
|
||||
data = get_weather_data(lat,long,unixtime)
|
||||
if data:
|
||||
try:
|
||||
# we are getting wind in mph
|
||||
windspeed = data['currently']['windSpeed']*0.44704
|
||||
windbearing = data['currently']['windBearing']
|
||||
except KeyError:
|
||||
windspeed = 0
|
||||
windbearing = 0
|
||||
try:
|
||||
# we are getting wind in mph
|
||||
windspeed = data['currently']['windSpeed']*0.44704
|
||||
windbearing = data['currently']['windBearing']
|
||||
except KeyError:
|
||||
windspeed = 0
|
||||
windbearing = 0
|
||||
|
||||
try:
|
||||
airports = data['flags']['madis-stations']
|
||||
except KeyError:
|
||||
airports = ['unknown']
|
||||
try:
|
||||
airports = data['flags']['madis-stations']
|
||||
except KeyError:
|
||||
airports = ['unknown']
|
||||
|
||||
try:
|
||||
temperature = data['currently']['temperature']
|
||||
try:
|
||||
temperature = data['currently']['temperature']
|
||||
# Temp is given in Fahrenheit, so convert to Celsius for Europeans
|
||||
temperaturec = (temperature-32.)*(5./9.)
|
||||
temperaturec = int(10*temperaturec)/10.
|
||||
except KeyError:
|
||||
temperature = 'unknown'
|
||||
temperaturec = 'unknown'
|
||||
temperaturec = (temperature-32.)*(5./9.)
|
||||
temperaturec = int(10*temperaturec)/10.
|
||||
except KeyError:
|
||||
temperature = 'unknown'
|
||||
temperaturec = 'unknown'
|
||||
|
||||
try:
|
||||
summary = data['currently']['summary']
|
||||
except KeyError:
|
||||
summary = 'unknown'
|
||||
try:
|
||||
summary = data['currently']['summary']
|
||||
except KeyError:
|
||||
summary = 'unknown'
|
||||
else:
|
||||
windspeed = 0
|
||||
windbearing = 0
|
||||
message = 'Not able to get weather data'
|
||||
windspeed = 0
|
||||
windbearing = 0
|
||||
message = 'Not able to get weather data'
|
||||
|
||||
# apply Hellman's coefficient for neutral air above human
|
||||
# inhabitated areas
|
||||
@@ -135,7 +136,7 @@ def get_wind_data(lat,long,unixtime):
|
||||
message += '. Temperature '+str(temperature)+'F/'+str(temperaturec)+'C'
|
||||
|
||||
if data:
|
||||
message += '. Wind: '+str(windspeed)+' m/s. Wind Bearing: '+str(windbearing)+' degrees'
|
||||
message += '. Wind: '+str(windspeed)+' m/s. Wind Bearing: '+str(windbearing)+' degrees'
|
||||
|
||||
|
||||
return [windspeed,windbearing,message,airports,timestamp]
|
||||
|
||||
@@ -378,9 +378,11 @@ REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'rest_framework.authentication.BasicAuthentication',
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
|
||||
# 'oauth2_provider.ext.rest_framework.OAuth2Authentication',
|
||||
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
|
||||
),
|
||||
'PAGE_SIZE': 20,
|
||||
'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.LimitOffsetPagination',
|
||||
}
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
|
||||
@@ -9,7 +9,7 @@ https://docs.djangoproject.com/en/1.9/topics/settings/
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.9/ref/settings/
|
||||
"""
|
||||
from settings import *
|
||||
from .settings import *
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
|
||||
@@ -12,7 +12,7 @@ https://docs.djangoproject.com/en/1.9/ref/settings/
|
||||
|
||||
import os
|
||||
|
||||
from settings import *
|
||||
from .settings import *
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
|
||||
+24
-12
@@ -35,19 +35,26 @@ handler500 = 'rowers.views.error500_view'
|
||||
urlpatterns = [
|
||||
url('^', include('django.contrib.auth.urls')),
|
||||
url(r'^django-rq/',include('django_rq.urls')),
|
||||
url(r'^password_change_done/$',auth_views.password_change_done,name='password_change_done'),
|
||||
url(r'^password_change/$',auth_views.password_change),
|
||||
# url(r'^password_change_done/$',auth_views.password_change_done,name='password_change_done'),
|
||||
url(r'^password_change_done/$',auth_views.PasswordChangeDoneView,name='password_change_done'),
|
||||
# url(r'^password_change/$',auth_views.password_change),
|
||||
url(r'^password_change/$',auth_views.PasswordChangeView,name='password_change'),
|
||||
url(r'^password_reset/$',
|
||||
auth_views.password_reset,
|
||||
# auth_views.password_reset,
|
||||
auth_views.PasswordResetView,
|
||||
{'template_name': 'rowers/templates/registration/password_reset.html'},
|
||||
name='password_reset'),
|
||||
url(r'^password_reset/done/$',
|
||||
auth_views.password_reset_done,
|
||||
# auth_views.password_reset_done,
|
||||
auth_views.PasswordResetDoneView,
|
||||
name='password_reset_done'),
|
||||
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',
|
||||
auth_views.password_reset_confirm,
|
||||
# auth_views.password_reset_confirm,
|
||||
auth_views.PasswordResetConfirmView,
|
||||
name='password_reset_confirm'),
|
||||
url(r'^reset/done/$', auth_views.password_reset_complete,
|
||||
url(r'^reset/done/$',
|
||||
# auth_views.password_reset_complete,
|
||||
auth_views.PasswordResetCompleteView,
|
||||
name='password_reset_complete'),
|
||||
]
|
||||
|
||||
@@ -55,16 +62,21 @@ urlpatterns += [
|
||||
url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt',
|
||||
content_type='text/plain')),
|
||||
url(r'^admin/', admin.site.urls),
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework2')),
|
||||
url(r'^$',rootview),
|
||||
url(r'^getblogs/$',rowersviews.get_blog_posts),
|
||||
url(r'^login/',auth_views.login, name='login'),
|
||||
url(r'^logout/$',auth_views.logout,
|
||||
url(r'^login/',
|
||||
# auth_views.login,
|
||||
auth_views.LoginView,
|
||||
name='login'),
|
||||
url(r'^logout/$',
|
||||
# auth_views.logout,
|
||||
auth_views.LogoutView,
|
||||
{'next_page': '/'},
|
||||
name='logout',),
|
||||
url(r'^rowers/',include('rowers.urls')),
|
||||
# url(r'^cvkbrno/',include('cvkbrno.urls')),
|
||||
url(r'^admin/rq/',include('django_rq_dashboard.urls')),
|
||||
# url(r'^admin/rq/',include('django_rq_dashboard.urls')),
|
||||
url(r'^call\_back',rowersviews.rower_process_callback),
|
||||
url(r'^stravacall\_back',rowersviews.rower_process_stravacallback),
|
||||
url(r'^sporttracks\_callback',rowersviews.rower_process_sporttrackscallback),
|
||||
@@ -75,7 +87,7 @@ urlpatterns += [
|
||||
url(r'^twitter\_callback',rowersviews.rower_process_twittercallback),
|
||||
url(r'^i18n/', include('django.conf.urls.i18n')),
|
||||
url(r'^tz_detect/', include('tz_detect.urls')),
|
||||
url(r'^jsi18n/', 'django.views.i18n.javascript_catalog',name='jsi18n'),
|
||||
# url(r'^jsi18n/', 'django.views.i18n.javascript_catalog',name='jsi18n'),
|
||||
]
|
||||
|
||||
|
||||
@@ -83,7 +95,7 @@ if settings.DEBUG:
|
||||
import debug_toolbar
|
||||
import django
|
||||
urlpatterns += [
|
||||
url(r'^__debug__/',include(debug_toolbar.urls)),
|
||||
# url(r'^__debug__/','debug_toolbar.urls'),
|
||||
url(r'^static/(?P<path>.*)$',
|
||||
django.views.static.serve,
|
||||
kwargs={'document_root': settings.STATIC_ROOT,}
|
||||
|
||||
Reference in New Issue
Block a user