more pep
This commit is contained in:
@@ -2,9 +2,7 @@ from rowers.models import Alert, Condition, User, Rower, Workout
|
||||
from rowers.teams import coach_getcoachees
|
||||
from rowers.dataprep import getsmallrowdata_db, getrowdata_db
|
||||
import datetime
|
||||
# BASIC operations
|
||||
|
||||
# create alert
|
||||
import numpy as np
|
||||
|
||||
|
||||
def create_alert(manager, rower, measured, period=7, emailalert=True,
|
||||
@@ -65,7 +63,6 @@ def alert_add_filters(alert, filters):
|
||||
for f in filters:
|
||||
metric = f['metric']
|
||||
value1 = f['value1']
|
||||
value2 = f['value2']
|
||||
condition = f['condition']
|
||||
|
||||
if condition and metric and value1:
|
||||
|
||||
@@ -20,7 +20,7 @@ import pytz
|
||||
import iso8601
|
||||
|
||||
from matplotlib.backends.backend_agg import FigureCanvas
|
||||
#from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from rowsandall_app.settings import SITE_URL
|
||||
@@ -130,10 +130,10 @@ def send_confirm(user, name, link, options): # pragma: no cover
|
||||
fullemail = user.email
|
||||
subject = 'New Workout Added: '+name
|
||||
|
||||
res = send_template_email('Rowsandall <info@rowsandall.com>',
|
||||
[fullemail],
|
||||
subject, 'confirmemail.html',
|
||||
d
|
||||
)
|
||||
_ = send_template_email('Rowsandall <info@rowsandall.com>',
|
||||
[fullemail],
|
||||
subject, 'confirmemail.html',
|
||||
d
|
||||
)
|
||||
|
||||
return 1
|
||||
|
||||
@@ -129,7 +129,7 @@ def create_invoice(rower, amount, braintreeid, dosend=True,
|
||||
if res.status_code not in [200, 201]: # pragma: no cover
|
||||
return 0
|
||||
|
||||
url = res.json()['url']
|
||||
# url = res.json()['url']
|
||||
id = res.json()['id']
|
||||
|
||||
urlpay = 'https://app.fakturoid.cz/api/v2/accounts/{slug}/invoices/{id}/fire.json?event=pay'.format(
|
||||
|
||||
@@ -11,7 +11,7 @@ import requests
|
||||
from requests import Session, Request
|
||||
from requests_oauthlib import OAuth1, OAuth1Session
|
||||
from requests_oauthlib.oauth1_session import TokenRequestDenied
|
||||
from requests import Request, Session
|
||||
|
||||
import rowers.mytypes as mytypes
|
||||
from rowers.mytypes import otwtypes
|
||||
from rowers.rower_rules import is_workout_user, ispromember
|
||||
@@ -35,13 +35,6 @@ from rowsandall_app.settings import (
|
||||
|
||||
from pytz import timezone as tz, utc
|
||||
|
||||
# You must initialize logging, otherwise you'll not see debug output.
|
||||
# logging.basicConfig()
|
||||
# logging.getLogger().setLevel(logging.DEBUG)
|
||||
#requests_log = logging.getLogger("requests.packages.urllib3")
|
||||
# requests_log.setLevel(logging.DEBUG)
|
||||
#requests_log.propagate = True
|
||||
|
||||
|
||||
from rowers.tasks import handle_get_garmin_file
|
||||
import django_rq
|
||||
@@ -100,18 +93,15 @@ repeattypes = {
|
||||
"RepeatUntilDistance": "REPEAT_UNTIL_TIME",
|
||||
"RepeatUntilCalories": "REPEAT_UNTIL_CALORIES",
|
||||
"RepeatUntilHrLessThan": "REPEAT_UNTIL_HR_LESS_THAN",
|
||||
"RepeatUntilHrGreaterThan": "REPEAT_UNTIL_HR_GREATER_THAN",
|
||||
"RepeatUntilPowerLessThan": "REPEAT_UNTIL_POWER_LESS_THAN",
|
||||
"RepeatUntilHrGreaterThan": "REPEAT_UNTIL_HR_GREATER_THAN",
|
||||
"RepeatUntilPowerLessThan": "REPEAT_UNTIL_POWER_LESS_THAN",
|
||||
"RepeatUntilPowerGreaterThan": "REPEAT_UNTIL_POWER_GREATER_THAN",
|
||||
"RepeatUntilPowerLapLessThan": "REPEAT_UNTIL_POWER_LAP_LESS_THAN",
|
||||
"RepeatUntilPowerLapLessThan": "REPEAT_UNTIL_POWER_LAP_LESS_THAN",
|
||||
"RepeatUntilPowerLapGreaterThan": "REPEAT_UNTIL_POWER_LAP_GREATER_THAN",
|
||||
}
|
||||
|
||||
|
||||
def garmin_authorize(): # pragma: no cover
|
||||
redirect_uri = oauth_data['redirect_uri']
|
||||
client_secret = oauth_data['client_secret']
|
||||
client_id = oauth_data['client_id']
|
||||
base_uri = oauth_data['base_url']
|
||||
|
||||
garmin = OAuth1Session(oauth_data['client_id'],
|
||||
@@ -133,7 +123,7 @@ def garmin_processcallback(redirect_response, resource_owner_key, resource_owner
|
||||
oauth_response = garmin.parse_authorization_response(redirect_response)
|
||||
|
||||
verifier = oauth_response.get('oauth_verifier')
|
||||
token = oauth_response.get('oauth_token')
|
||||
# token = oauth_response.get('oauth_token')
|
||||
access_token_url = 'https://connectapi.garmin.com/oauth-service/oauth/access_token'
|
||||
|
||||
# Using OAuth1Session
|
||||
@@ -155,7 +145,7 @@ def garmin_processcallback(redirect_response, resource_owner_key, resource_owner
|
||||
|
||||
def garmin_open(user): # pragma: no cover
|
||||
r = Rower.objects.get(user=user)
|
||||
token = Rower.garmintoken
|
||||
token = r.garmintoken
|
||||
|
||||
if (token == '') or (token is None):
|
||||
raise NoTokenError("User has no garmin token")
|
||||
@@ -191,7 +181,8 @@ def get_garmin_workout_list(user): # pragma: no cover
|
||||
resource_owner_secret=r.garminrefreshtoken,
|
||||
)
|
||||
|
||||
url = 'https://healthapi.garmin.com/wellness-api/rest/activities?uploadStartTimeInSeconds=1593113760&uploadEndTimeInSeconds=1593279360'
|
||||
url = 'https://healthapi.garmin.com/wellness-api/rest/' \
|
||||
'activities?uploadStartTimeInSeconds=1593113760&uploadEndTimeInSeconds=1593279360'
|
||||
|
||||
result = garmin.get(url)
|
||||
|
||||
@@ -218,7 +209,7 @@ def step_to_garmin(step, order=0):
|
||||
intensity = 'INTERVAL'
|
||||
except KeyError:
|
||||
intensity = None
|
||||
#durationvaluetype = ''
|
||||
# durationvaluetype = ''
|
||||
if durationtype == 'Time':
|
||||
durationtype = 'TIME'
|
||||
durationvalue = int(durationvalue/1000.)
|
||||
@@ -272,11 +263,11 @@ def step_to_garmin(step, order=0):
|
||||
|
||||
if targetType is not None and targetType.lower() == "power":
|
||||
targetType = 'POWER'
|
||||
if targetValue is not None and targetValue <= 1000:
|
||||
targetValueType = 'PERCENT' # pragma: no cover
|
||||
else:
|
||||
targetValueType = None
|
||||
targetValue -= 1000
|
||||
# if targetValue is not None and targetValue <= 1000:
|
||||
# targetValueType = 'PERCENT' # pragma: no cover
|
||||
# else:
|
||||
# # targetValueType = None
|
||||
# targetValue -= 1000
|
||||
|
||||
try:
|
||||
targetValueLow = step['dict']['targetValueLow']
|
||||
@@ -285,8 +276,8 @@ def step_to_garmin(step, order=0):
|
||||
targetValue = None
|
||||
elif targetValueLow == 0: # pragma: no cover
|
||||
targetValueLow = None
|
||||
elif targetValueLow <= 1000 and targetType == 'POWER': # pragma: no cover
|
||||
targetValueType = 'PERCENT'
|
||||
# elif targetValueLow <= 1000 and targetType == 'POWER': # pragma: no cover
|
||||
# targetValueType = 'PERCENT'
|
||||
elif targetValueLow > 1000 and targetType == 'POWER': # pragma: no cover
|
||||
targetValueLow -= 1000
|
||||
except KeyError:
|
||||
@@ -296,8 +287,8 @@ def step_to_garmin(step, order=0):
|
||||
if targetValue is not None and targetValue > 0 and targetValueHigh == 0: # pragma: no cover
|
||||
targetValueHigh = targetValue
|
||||
targetValue = 0
|
||||
elif targetValueHigh <= 1000 and targetType == 'POWER': # pragma: no cover
|
||||
targetValueType = 'PERCENT'
|
||||
# elif targetValueHigh <= 1000 and targetType == 'POWER': # pragma: no cover
|
||||
# targetValueType = 'PERCENT'
|
||||
elif targetValueHigh > 1000 and targetType == 'POWER': # pragma: no cover
|
||||
targetValueHigh -= 1000
|
||||
elif targetValueHigh == 0: # pragma: no cover
|
||||
@@ -477,12 +468,6 @@ def garmin_getworkout(garminid, r, activity):
|
||||
distance = activity['distanceInMeters']
|
||||
except KeyError:
|
||||
distance = 0
|
||||
try:
|
||||
averagehr = activity['averageHeartRateInBeatsPerMinute']
|
||||
maxhr = activity['maxHeartRateInBeatsPerMinute']
|
||||
except KeyError: # pragma: no cover
|
||||
averagehr = 0
|
||||
maxhr = 0
|
||||
try:
|
||||
w = Workout.objects.get(uploadedtogarmin=garminid)
|
||||
except Workout.DoesNotExist:
|
||||
@@ -494,7 +479,7 @@ def garmin_getworkout(garminid, r, activity):
|
||||
|
||||
utc_offset = datetime.timedelta(seconds=offset)
|
||||
now = datetime.datetime.now(pytz.utc)
|
||||
zones = [tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
|
||||
zones = [ttz.zone for ttz in map(pytz.timezone, pytz.all_timezones_set)
|
||||
if now.astimezone(tz).utcoffset() == utc_offset]
|
||||
if r.defaulttimezone in zones: # pragma: no cover
|
||||
thetimezone = r.defaulttimezone
|
||||
@@ -557,12 +542,12 @@ def garmin_workouts_from_details(data):
|
||||
df[' AverageBoatSpeed (m/s)'] = 0
|
||||
df[' Stroke500mPace (sec/500m)'] = pace
|
||||
try:
|
||||
spm = df[' Cadence (stokes/min)']
|
||||
_ = df[' Cadence (stokes/min)']
|
||||
except KeyError:
|
||||
df[' Cadence (stokes/min)'] = 0
|
||||
df['cum_dist'] = df[' Horizontal (meters)']
|
||||
try:
|
||||
power = df[' Power (watts)']
|
||||
_ = df[' Power (watts)']
|
||||
except KeyError:
|
||||
df[' Power (watts)'] = 0
|
||||
df[' AverageDriveForce (lbs)'] = 0
|
||||
@@ -591,7 +576,7 @@ def garmin_workouts_from_summaries(activities):
|
||||
try:
|
||||
r = Rower.objects.get(garmintoken=garmintoken)
|
||||
id = activity['summaryId']
|
||||
w = garmin_getworkout(id, r, activity)
|
||||
_ = garmin_getworkout(id, r, activity)
|
||||
except Rower.DoesNotExist: # pragma: no cover
|
||||
pass
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import datetime
|
||||
from datetime import timedelta
|
||||
from uuid import uuid4
|
||||
@@ -52,14 +53,14 @@ def add_workout_from_data(userid, nkid, data, strokedata, source='nk', splitdata
|
||||
elapsedTime = data["elapsedTime"]
|
||||
totalDistanceGps = data["totalDistanceGps"]
|
||||
totalDistanceImp = data["totalDistanceImp"]
|
||||
intervals = data["intervals"] # add intervals
|
||||
# intervals = data["intervals"] # add intervals
|
||||
oarlockSessions = data["oarlockSessions"]
|
||||
deviceId = data["deviceId"] # you could get the firmware version
|
||||
# deviceId = data["deviceId"] # you could get the firmware version
|
||||
|
||||
totalDistance = totalDistanceGps
|
||||
useImpeller = False
|
||||
if speedInput: # pragma: no cover
|
||||
totdalDistance = totalDistanceImp
|
||||
totalDistance = totalDistanceImp
|
||||
useImpeller = True
|
||||
|
||||
summary = get_nk_allstats(data, strokedata)
|
||||
@@ -69,19 +70,19 @@ def add_workout_from_data(userid, nkid, data, strokedata, source='nk', splitdata
|
||||
# oarlock inboard, length, boat name
|
||||
if oarlockSessions:
|
||||
oarlocksession = oarlockSessions[0] # should take seatIndex
|
||||
boatName = oarlocksession["boatName"]
|
||||
# boatName = oarlocksession["boatName"]
|
||||
oarLength = oarlocksession["oarLength"] # cm
|
||||
oarInboardLength = oarlocksession["oarInboardLength"] # cm
|
||||
seatNumber = oarlocksession["seatNumber"]
|
||||
# seatNumber = oarlocksession["seatNumber"]
|
||||
try:
|
||||
oarlockfirmware = oarlocksession["firmwareVersion"]
|
||||
except KeyError:
|
||||
oarlockfirmware = ''
|
||||
else: # pragma: no cover
|
||||
boatName = ''
|
||||
# boatName = ''
|
||||
oarLength = 289
|
||||
oarInboardLength = 88
|
||||
seatNumber = 1
|
||||
# seatNumber = 1
|
||||
oarlockfirmware = ''
|
||||
|
||||
workouttype = "water"
|
||||
@@ -139,7 +140,7 @@ def get_nk_intervalstats(workoutdata, strokedata):
|
||||
i = 0
|
||||
|
||||
for interval in intervals:
|
||||
id = interval['id']
|
||||
# id = interval['id']
|
||||
sdist = interval['totalDistanceGps']
|
||||
avgpace = interval['avgPaceGps']/1000.
|
||||
avgpacetd = timedelta(seconds=avgpace)
|
||||
@@ -325,6 +326,6 @@ def readlogs_summaries(logfile, dosave=0): # pragma: no cover
|
||||
json.dump(strokeData, f2)
|
||||
with open(filename2, 'w') as f2:
|
||||
json.dump(summaryData, f2)
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
print(traceback.format_exc())
|
||||
print("error")
|
||||
|
||||
@@ -31,13 +31,6 @@ queue = django_rq.get_queue('default')
|
||||
queuelow = django_rq.get_queue('low')
|
||||
queuehigh = django_rq.get_queue('low')
|
||||
|
||||
|
||||
try:
|
||||
from json.decoder import JSONDecodeError
|
||||
except ImportError: # pragma: no cover
|
||||
JSONDecodeError = ValueError
|
||||
|
||||
|
||||
oauth_data = {
|
||||
'client_id': NK_CLIENT_ID,
|
||||
'client_secret': NK_CLIENT_SECRET,
|
||||
@@ -56,12 +49,6 @@ oauth_data = {
|
||||
def get_token(code): # pragma: no cover
|
||||
url = oauth_data['base_url']
|
||||
|
||||
headers = {'Accept': 'application/json',
|
||||
# 'Authorization': auth_header,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
# 'user-agent': 'sanderroosendaal'
|
||||
}
|
||||
|
||||
post_data = {"client_id": oauth_data['client_id'],
|
||||
"grant_type": "authorization_code",
|
||||
"redirect_uri": oauth_data['redirect_uri'],
|
||||
@@ -88,13 +75,12 @@ def nk_open(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
|
||||
if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
raise NoTokenError("User has no token")
|
||||
else:
|
||||
if (timezone.now() > r.nktokenexpirydate):
|
||||
|
||||
thetoken = rower_nk_token_refresh(user)
|
||||
if thetoken == None: # pragma: no cover
|
||||
if thetoken is None: # pragma: no cover
|
||||
raise NoTokenError("User has no token")
|
||||
return thetoken
|
||||
else:
|
||||
@@ -105,7 +91,7 @@ def nk_open(user):
|
||||
|
||||
def get_nk_workouts(rower, do_async=True, before=0, after=0):
|
||||
try:
|
||||
thetoken = nk_open(rower.user)
|
||||
_ = nk_open(rower.user)
|
||||
except NoTokenError: # pragma: no cover
|
||||
return 0
|
||||
|
||||
@@ -136,7 +122,7 @@ def get_nk_workouts(rower, do_async=True, before=0, after=0):
|
||||
pass
|
||||
|
||||
knownnkids = uniqify(knownnkids+tombstones+parkedids)
|
||||
newids = [nkid for nkid in nkids if not nkid in knownnkids]
|
||||
newids = [nkid for nkid in nkids if nkid not in knownnkids]
|
||||
s = 'New NK IDs {newids}'.format(newids=newids)
|
||||
dologging('nklog.log', s)
|
||||
|
||||
@@ -211,7 +197,8 @@ def get_nk_workout_list(user, fake=False, after=0, before=0):
|
||||
if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401, s)
|
||||
elif (r.nktokenexpirydate is None or timezone.now()+timedelta(seconds=10) > r.nktokenexpirydate): # pragma: no cover
|
||||
elif (r.nktokenexpirydate is None or
|
||||
timezone.now()+timedelta(seconds=10) > r.nktokenexpirydate): # pragma: no cover
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401, s)
|
||||
else:
|
||||
@@ -251,10 +238,6 @@ def get_workout(user, nkid, do_async=True, startdate='', enddate=''):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401, s), 0
|
||||
|
||||
params = {
|
||||
'sessionIds': nkid,
|
||||
}
|
||||
|
||||
before = 0
|
||||
after = 0
|
||||
if startdate: # pragma: no cover
|
||||
|
||||
@@ -7,7 +7,7 @@ import requests
|
||||
import requests.auth
|
||||
import json
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
import numpy as np
|
||||
from dateutil import parser
|
||||
import time
|
||||
@@ -30,7 +30,10 @@ from rowingdata import rowingdata
|
||||
import pandas as pd
|
||||
from rowers.models import Rower, Workout
|
||||
|
||||
from rowsandall_app.settings import C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET, STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI, STRAVA_CLIENT_SECRET, SPORTTRACKS_CLIENT_SECRET, SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI
|
||||
from rowsandall_app.settings import (
|
||||
C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET,
|
||||
STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI, STRAVA_CLIENT_SECRET,
|
||||
SPORTTRACKS_CLIENT_SECRET, SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI)
|
||||
|
||||
TEST_CLIENT_ID = "1"
|
||||
TEST_CLIENT_SECRET = "aapnootmies"
|
||||
@@ -57,8 +60,8 @@ def custom_exception_handler(exc, message): # pragma: no cover
|
||||
|
||||
|
||||
def do_refresh_token(refreshtoken): # pragma: no cover
|
||||
client_auth = requests.auth.HTTPBasicAuth(
|
||||
TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
# 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,
|
||||
@@ -86,8 +89,8 @@ def do_refresh_token(refreshtoken): # pragma: no cover
|
||||
|
||||
|
||||
def get_token(code): # pragma: no cover
|
||||
client_auth = requests.auth.HTTPBasicAuth(
|
||||
TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
# client_auth = requests.auth.HTTPBasicAuth(
|
||||
# TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": "http://localhost:8000/rowers/test_callback",
|
||||
@@ -123,7 +126,6 @@ def make_authorization_url(request): # pragma: no cover
|
||||
"scope": "write",
|
||||
"state": state}
|
||||
|
||||
import urllib
|
||||
url = "http://localhost:8000/rowers/o/authorize" + \
|
||||
urllib.parse.urlencode(params)
|
||||
|
||||
@@ -170,8 +172,8 @@ def get_ownapi_workout_list(user): # pragma: no cover
|
||||
def get_ownapi_workout(user, ownapiid): # pragma: no cover
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
return custom_exception_handler(401, s)
|
||||
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)
|
||||
|
||||
@@ -76,8 +76,8 @@ def mkplot(row, title):
|
||||
ax1.set_title(title)
|
||||
plt.grid(True)
|
||||
majorFormatter = FuncFormatter(format_pace_tick)
|
||||
majorLocator = (5)
|
||||
timeTickFormatter = NullFormatter()
|
||||
# majorLocator = (5)
|
||||
# timeTickFormatter = NullFormatter()
|
||||
|
||||
ax1.yaxis.set_major_formatter(majorFormatter)
|
||||
|
||||
@@ -88,7 +88,7 @@ def mkplot(row, title):
|
||||
ax2.plot(t, hr, 'r-')
|
||||
ax2.set_ylabel('Heart Rate', color='r')
|
||||
majorTimeFormatter = FuncFormatter(format_time_tick)
|
||||
majorLocator = (15*60)
|
||||
# majorLocator = (15*60)
|
||||
ax2.xaxis.set_major_formatter(majorTimeFormatter)
|
||||
ax2.patch.set_alpha(0.0)
|
||||
for tl in ax2.get_yticklabels():
|
||||
|
||||
@@ -57,8 +57,6 @@ queuehigh = django_rq.get_queue('high')
|
||||
# Project
|
||||
# from .models import Profile
|
||||
|
||||
|
||||
#baseurl = 'https://polaraccesslink.com/v3-example'
|
||||
baseurl = 'https://polaraccesslink.com/v3'
|
||||
|
||||
|
||||
@@ -125,7 +123,7 @@ def get_token(code):
|
||||
def make_authorization_url(): # pragma: no cover
|
||||
# Generate a random string for the state parameter
|
||||
# Save it for use later to prevent xsrf attacks
|
||||
state = str(uuid4())
|
||||
# state = str(uuid4())
|
||||
|
||||
params = {"client_id": POLAR_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
@@ -155,7 +153,7 @@ def revoke_access(user): # pragma: no cover
|
||||
|
||||
def get_polar_notifications():
|
||||
url = baseurl+'/notifications'
|
||||
state = str(uuid4())
|
||||
# state = str(uuid4())
|
||||
auth_string = '{id}:{secret}'.format(
|
||||
id=POLAR_CLIENT_ID,
|
||||
secret=POLAR_CLIENT_SECRET
|
||||
@@ -302,16 +300,12 @@ def get_polar_workouts(user):
|
||||
'title': '',
|
||||
}
|
||||
|
||||
#session = requests.session()
|
||||
#newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
|
||||
# session.headers.update(newHeaders)
|
||||
|
||||
url = settings.UPLOAD_SERVICE_URL
|
||||
|
||||
dologging('polar.log', uploadoptions)
|
||||
dologging('polar.log', url)
|
||||
#response = session.post(url,json=uploadoptions)
|
||||
job = myqueue(
|
||||
|
||||
_ = myqueue(
|
||||
queuehigh,
|
||||
handle_request_post,
|
||||
url,
|
||||
@@ -381,9 +375,6 @@ def register_user(user, token):
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
#url = baseurl+'/users'
|
||||
|
||||
#response = requests.post(url,params=params,headers=headers)
|
||||
|
||||
if response.status_code not in [200, 201]: # pragma: no cover
|
||||
# dologging('polar.log',url)
|
||||
@@ -419,10 +410,6 @@ def get_polar_user_info(user, physical=False): # pragma: no cover
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
|
||||
params = {
|
||||
'user-id': r.polaruserid
|
||||
}
|
||||
|
||||
if not physical:
|
||||
url = baseurl+'/users/{userid}'.format(
|
||||
userid=r.polaruserid
|
||||
@@ -478,11 +465,11 @@ def get_polar_workout(user, id, transactionid):
|
||||
exercise_dict = response.json()
|
||||
thisid = exercise_dict['id']
|
||||
if thisid == id:
|
||||
url = baseurl+'/users/{userid}/exercise-transactions/{transactionid}/exercises/{exerciseid}/tcx'.format(
|
||||
userid=r.polaruserid,
|
||||
transactionid=transactionid,
|
||||
exerciseid=id
|
||||
)
|
||||
url = baseurl+'/users/{userid}/exercise-transactions/{transactionid}' \
|
||||
'/exercises/{exerciseid}/tcx'.format(
|
||||
userid=r.polaruserid,
|
||||
transactionid=transactionid,
|
||||
exerciseid=id)
|
||||
authorizationstring = str('Bearer ' + r.polartoken)
|
||||
headers2 = {
|
||||
'Authorization': authorizationstring,
|
||||
|
||||
@@ -19,7 +19,18 @@ DESCRIPTOR = _descriptor.FileDescriptor(
|
||||
package='rowing_workout_metrics',
|
||||
syntax='proto3',
|
||||
serialized_options=None,
|
||||
serialized_pb=_b('\n\x1crowing-workout-metrics.proto\x12\x16rowing_workout_metrics\"p\n\x15WorkoutMetricsRequest\x12\x10\n\x08\x66ilename\x18\x01 \x01(\t\x12\x0b\n\x03sex\x18\x02 \x01(\t\x12\x0b\n\x03\x66tp\x18\x03 \x01(\x01\x12\r\n\x05hrftp\x18\x04 \x01(\x01\x12\r\n\x05hrmax\x18\x05 \x01(\x01\x12\r\n\x05hrmin\x18\x06 \x01(\x01\"p\n\x16WorkoutMetricsResponse\x12\x0b\n\x03tss\x18\x01 \x01(\x01\x12\r\n\x05normp\x18\x02 \x01(\x01\x12\r\n\x05trimp\x18\x03 \x01(\x01\x12\r\n\x05hrtss\x18\x04 \x01(\x01\x12\r\n\x05normv\x18\x05 \x01(\x01\x12\r\n\x05normw\x18\x06 \x01(\x01\x32w\n\x07Metrics\x12l\n\x0b\x43\x61lcMetrics\x12-.rowing_workout_metrics.WorkoutMetricsRequest\x1a..rowing_workout_metrics.WorkoutMetricsResponseb\x06proto3')
|
||||
serialized_pb=_b('\n\x1crowing-workout-metrics.proto\x12\x16'
|
||||
'rowing_workout_metrics\"p\n\x15WorkoutMetricsRequest'
|
||||
'\x12\x10\n\x08\x66ilename'
|
||||
'\x18\x01 \x01(\t\x12\x0b\n\x03sex'
|
||||
'\x18\x02 \x01(\t\x12\x0b\n\x03\x66tp\x18\x03 \x01'
|
||||
'(\x01\x12\r\n\x05hrftp\x18\x04 \x01(\x01\x12\r\n\x05hrmax'
|
||||
'\x18\x05 \x01(\x01\x12\r\n\x05hrmin\x18\x06 \x01(\x01\"p\n\x16WorkoutMetricsResponse'
|
||||
'\x12\x0b\n\x03tss\x18\x01 \x01(\x01\x12\r\n\x05normp\x18\x02 \x01(\x01\x12\r\n\x05trimp'
|
||||
'\x18\x03 \x01(\x01\x12\r\n\x05hrtss\x18\x04 \x01(\x01\x12\r\n\x05normv'
|
||||
'\x18\x05 \x01(\x01\x12\r\n\x05normw\x18\x06 \x01(\x01\x32w\n\x07Metrics'
|
||||
'\x12l\n\x0b\x43\x61lcMetrics\x12-.rowing_workout_metrics.WorkoutMetricsRequest'
|
||||
'\x1a..rowing_workout_metrics.WorkoutMetricsResponseb\x06proto3')
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from rest_framework import serializers
|
||||
from rowers.models import (
|
||||
Workout, Rower, FavoriteChart, VirtualRaceResult,
|
||||
VirtualRace, GeoCourse, StandardCollection, CourseStandard,
|
||||
GeoCourse, GeoPolygon, GeoPoint, PlannedSession,
|
||||
GeoPolygon, GeoPoint, PlannedSession,
|
||||
)
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
|
||||
@@ -7,6 +7,8 @@ import time
|
||||
import os
|
||||
import sys
|
||||
import django
|
||||
from django.contrib import messages
|
||||
|
||||
proj_path = "../"
|
||||
sys.path.append(proj_path)
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rowsandall_app.settings")
|
||||
@@ -15,11 +17,7 @@ django.setup()
|
||||
|
||||
@app.task
|
||||
def addcomment2(userid, id, debug=False):
|
||||
|
||||
time.sleep(5)
|
||||
# w = Workout.objects.get(id=id)
|
||||
# w.notes += '\n the task has run'
|
||||
# w.save()
|
||||
u = User.objects.get(id=userid)
|
||||
messages.info(u, ' The task has run')
|
||||
messages.error(u, ' Het is veel te laat')
|
||||
|
||||
@@ -151,8 +151,6 @@ class TraverseLinksTest(TestCase):
|
||||
if response.status_code == 200:
|
||||
soup = BeautifulSoup(response.content, 'html.parser')
|
||||
|
||||
text = soup.get_text()
|
||||
|
||||
for link in soup.find_all('a'):
|
||||
new_link = link.get('href')
|
||||
if VERBOSE:
|
||||
|
||||
@@ -17,7 +17,6 @@ from rest_framework.permissions import *
|
||||
from rowers import views
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.views.generic.base import TemplateView
|
||||
from django.utils.decorators import method_decorator
|
||||
|
||||
from rowers.permissions import (
|
||||
IsOwnerOrNot, IsOwnerOrReadOnly,
|
||||
@@ -71,7 +70,7 @@ class PlannedSessionViewSet(viewsets.ModelViewSet):
|
||||
|
||||
class WorkoutViewSet(viewsets.ModelViewSet):
|
||||
model = Workout
|
||||
#queryset = Workout.objects.all().order_by("-date", "-starttime")
|
||||
|
||||
serializer_class = WorkoutSerializer
|
||||
|
||||
def get_queryset(self): # pragma: no cover
|
||||
@@ -90,7 +89,6 @@ class WorkoutViewSet(viewsets.ModelViewSet):
|
||||
class RowerViewSet(viewsets.ModelViewSet):
|
||||
model = Rower
|
||||
serializer_class = RowerSerializer
|
||||
#queryset = Rower.objects.all()
|
||||
|
||||
def get_queryset(self): # pragma: no cover
|
||||
try:
|
||||
@@ -109,7 +107,6 @@ class RowerViewSet(viewsets.ModelViewSet):
|
||||
class FavoriteChartViewSet(viewsets.ModelViewSet):
|
||||
model = FavoriteChart
|
||||
serializer_class = FavoriteChartSerializer
|
||||
#queryset = FavoriteChart.objects.all()
|
||||
|
||||
def get_queryset(self): # pragma: no cover
|
||||
try:
|
||||
@@ -235,8 +232,6 @@ handler400 = views.error400_view
|
||||
handler500 = views.error500_view
|
||||
|
||||
|
||||
#app_name = "rowers"
|
||||
|
||||
urlpatterns = [
|
||||
re_path(r'^o/authorize/$', base.AuthorizationView.as_view(), name="authorize"),
|
||||
re_path(r'^o/token/$', base.TokenView.as_view(), name="token"),
|
||||
@@ -352,17 +347,21 @@ urlpatterns = [
|
||||
re_path(r'^workouts-join-select/user/(?P<userid>\d+)/$',
|
||||
views.workouts_join_select, name='workouts_join_select'),
|
||||
re_path(
|
||||
r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'),
|
||||
r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(
|
||||
r'^user-analysis-select/(?P<function>\w.*)/session/(?P<session>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'),
|
||||
r'^user-analysis-select/(?P<function>\w.*)/session/(?P<session>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(
|
||||
r'^user-analysis-select/(?P<function>\w.*)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'),
|
||||
r'^user-analysis-select/(?P<function>\w.*)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(r'^user-analysis-select/(?P<function>\w.*)/user/(?P<userid>\d+)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(
|
||||
r'^user-analysis-select/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'),
|
||||
r'^user-analysis-select/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(r'^user-analysis-select/user/(?P<userid>\d+)/$',
|
||||
views.analysis_new, name='analysis_new'),
|
||||
re_path(r'^user-analysis-select/team/(?P<teamid>\d+)/$',
|
||||
@@ -613,7 +612,8 @@ urlpatterns = [
|
||||
views.workout_nkimport_view, name='workout_nkimport_view'),
|
||||
re_path(r'^workout/nkimport/all/$', views.workout_getnkworkout_all,
|
||||
name='workout_getnkworkout_all'),
|
||||
re_path(r'^workout/nkimport/all/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$', views.workout_getnkworkout_all,
|
||||
re_path(r'^workout/nkimport/all/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',
|
||||
views.workout_getnkworkout_all,
|
||||
name='workout_getnkworkout_all'),
|
||||
re_path(r'^workout/rp3import/(?P<externalid>\d+)/$', views.workout_getrp3importview,
|
||||
name='workout_getrp3importview'),
|
||||
@@ -853,12 +853,16 @@ urlpatterns = [
|
||||
name='workout_workflow_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/courses/$', views.workout_course_view,
|
||||
name='workout_course_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>[\w\ ]+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+)/$',
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
|
||||
'(?P<xparam>[\w\ ]+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+)/$',
|
||||
views.workout_flexchart3_view, name='workout_flexchart3_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+.*)/$',
|
||||
views.workout_flexchart3_view, name='workout_flexchart3_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/$',
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
|
||||
'(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+.*)/$',
|
||||
views.workout_flexchart3_view, name='workout_flexchart3_view'),
|
||||
re_path(
|
||||
r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
|
||||
'(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/$',
|
||||
views.workout_flexchart3_view, name='workout_flexchart3_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/$',
|
||||
views.workout_flexchart3_view, name='workout_flexchart3_view'),
|
||||
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchartstacked/$',
|
||||
@@ -1002,7 +1006,8 @@ urlpatterns = [
|
||||
name='plannedsession_teamclone_view'),
|
||||
re_path(r'^sessions/(?P<id>\d+)/clone/$', views.plannedsession_clone_view),
|
||||
re_path(
|
||||
r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/user/(?P<userid>\d+)/$', views.plannedsession_detach_view),
|
||||
r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/user/(?P<userid>\d+)/$',
|
||||
views.plannedsession_detach_view),
|
||||
re_path(
|
||||
r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.plannedsession_detach_view),
|
||||
re_path(r'^sessions/(?P<id>\d+)/$', views.plannedsession_view,
|
||||
@@ -1043,7 +1048,8 @@ urlpatterns = [
|
||||
name='plannedsessions_print_view'),
|
||||
re_path(r'^sessions/(?P<id>\d+)/message/$', views.plannedsession_message_view,
|
||||
name='plannedsession_message_view'),
|
||||
re_path(r'^sessions/print/user/(?P<userid>\d+)/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$', views.plannedsessions_print_view,
|
||||
re_path(r'^sessions/print/user/(?P<userid>\d+)/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',
|
||||
views.plannedsessions_print_view,
|
||||
name='plannedsessions_print_view'),
|
||||
re_path(r'^sessions/sendcalendar/$', views.plannedsessions_icsemail_view,
|
||||
name='plannedsessions_coach_icsemail_view'),
|
||||
|
||||
@@ -16,14 +16,11 @@ import datetime
|
||||
import json
|
||||
import time
|
||||
from fitparse import FitFile
|
||||
from django.conf import settings
|
||||
|
||||
from django.http import HttpResponse
|
||||
|
||||
import requests
|
||||
|
||||
from django.http import HttpResponse
|
||||
|
||||
import humanize
|
||||
from pytz.exceptions import UnknownTimeZoneError
|
||||
import pytz
|
||||
@@ -189,7 +186,6 @@ palettes = {
|
||||
'gold_sunset': (47, -31, .26, -0.12, 0.94, -0.5),
|
||||
'blue_red': (207, -200, .85, 0, .74, -.24),
|
||||
'blue_green': (207, -120, .85, 0, .75, .25),
|
||||
'cyan_green': (192, -50, .08, .65, .98, -.34),
|
||||
'cyan_purple': trcolors(237, 248, 251, 136, 65, 157),
|
||||
'green_blue': trcolors(240, 249, 232, 8, 104, 172),
|
||||
'orange_red': trcolors(254, 240, 217, 179, 0, 0),
|
||||
@@ -237,7 +233,8 @@ def str2bool(v): # pragma: no cover
|
||||
def uniqify(seq, idfun=None):
|
||||
# order preserving
|
||||
if idfun is None:
|
||||
def idfun(x): return x
|
||||
def idfun(x):
|
||||
return x
|
||||
seen = {}
|
||||
result = []
|
||||
for item in seq:
|
||||
@@ -465,14 +462,14 @@ def totaltime_sec_to_string(totaltime, shorten=False):
|
||||
hours=hours,
|
||||
minutes=minutes,
|
||||
seconds=seconds,
|
||||
tenths=tenths
|
||||
# tenths=tenths
|
||||
)
|
||||
else:
|
||||
duration = "{minutes}:{seconds:02d}".format(
|
||||
hours=hours,
|
||||
# hours=hours,
|
||||
minutes=minutes,
|
||||
seconds=seconds,
|
||||
tenths=tenths
|
||||
# tenths=tenths
|
||||
)
|
||||
|
||||
return duration
|
||||
@@ -559,12 +556,12 @@ def get_strava_stream(r, metric, stravaid, series_type='time', fetchresolution='
|
||||
if metric == 'power': # pragma: no cover
|
||||
metric = 'watts'
|
||||
|
||||
url = "https://www.strava.com/api/v3/activities/{stravaid}/streams/{metric}?resolution={fetchresolution}&series_type={series_type}".format(
|
||||
stravaid=stravaid,
|
||||
fetchresolution=fetchresolution,
|
||||
series_type=series_type,
|
||||
metric=metric
|
||||
)
|
||||
url = "https://www.strava.com/api/v3/activities/{stravaid}" \
|
||||
"/streams/{metric}?resolution={fetchresolution}&series_type={series_type}".format(
|
||||
stravaid=stravaid,
|
||||
fetchresolution=fetchresolution,
|
||||
series_type=series_type,
|
||||
metric=metric)
|
||||
|
||||
s = requests.get(url, headers=headers)
|
||||
|
||||
@@ -574,7 +571,6 @@ def get_strava_stream(r, metric, stravaid, series_type='time', fetchresolution='
|
||||
|
||||
try:
|
||||
for data in s.json():
|
||||
y = None
|
||||
try:
|
||||
if data['type'] == metric:
|
||||
return np.array(data['data'])
|
||||
@@ -790,14 +786,14 @@ def get_step_type(step): # pragma: no cover
|
||||
return t
|
||||
|
||||
|
||||
def peel(l):
|
||||
if len(l) == 0: # pragma: no cover
|
||||
def peel(listToPeel):
|
||||
if len(listToPeel) == 0: # pragma: no cover
|
||||
return None, None
|
||||
if len(l) == 1:
|
||||
return l[0], None
|
||||
if len(listToPeel) == 1:
|
||||
return listToPeel[0], None
|
||||
|
||||
first = l[0]
|
||||
rest = l[1:]
|
||||
first = listToPeel[0]
|
||||
rest = listToPeel[1:]
|
||||
|
||||
if first['type'] == 'Step': # pragma: no cover
|
||||
return first, rest
|
||||
@@ -944,7 +940,7 @@ def step_to_string(step, short=False):
|
||||
repeatValue = 1
|
||||
|
||||
nr = 0
|
||||
name = ''
|
||||
|
||||
intensity = ''
|
||||
duration = ''
|
||||
unit = ''
|
||||
@@ -954,7 +950,11 @@ def step_to_string(step, short=False):
|
||||
|
||||
durationtype = step['durationType']
|
||||
if step['durationValue'] == 0:
|
||||
if durationtype not in ['RepeatUntilStepsCmplt', 'RepeatUntilHrLessThan', 'RepeatUntilHrGreaterThan']: # pragma: no cover
|
||||
if durationtype not in [
|
||||
'RepeatUntilStepsCmplt',
|
||||
'RepeatUntilHrLessThan',
|
||||
'RepeatUntilHrGreaterThan'
|
||||
]: # pragma: no cover
|
||||
return '', type, -1, -1, 1
|
||||
|
||||
if durationtype == 'Time':
|
||||
@@ -963,7 +963,6 @@ def step_to_string(step, short=False):
|
||||
if value/1000. >= 3600: # pragma: no cover
|
||||
unit = 'h'
|
||||
dd = timedelta(seconds=value/1000.)
|
||||
#duration = humanize.naturaldelta(dd, minimum_unit="seconds")
|
||||
duration = '{v}'.format(v=str(dd))
|
||||
elif durationtype == 'Distance':
|
||||
unit = 'm'
|
||||
@@ -1163,7 +1162,7 @@ def step_to_string(step, short=False):
|
||||
|
||||
nr = step['stepId']
|
||||
|
||||
name = step['wkt_step_name']
|
||||
# name = step['wkt_step_name']
|
||||
|
||||
notes = ''
|
||||
try:
|
||||
@@ -1178,10 +1177,10 @@ def step_to_string(step, short=False):
|
||||
intensity = 0
|
||||
|
||||
s = '{duration} {unit} {target} {repeat} {notes}'.format(
|
||||
nr=nr,
|
||||
name=name,
|
||||
# nr=nr,
|
||||
# name=name,
|
||||
unit=unit,
|
||||
intensity=intensity,
|
||||
# intensity=intensity,
|
||||
duration=duration,
|
||||
target=target,
|
||||
repeat=repeat,
|
||||
|
||||
Reference in New Issue
Block a user