189 lines
5.6 KiB
Python
189 lines
5.6 KiB
Python
# All the functionality needed to connect to Runkeeper
|
|
|
|
# Python
|
|
import oauth2 as oauth
|
|
import cgi
|
|
import requests
|
|
import requests.auth
|
|
import json
|
|
from django.utils import timezone
|
|
from datetime import datetime
|
|
import numpy as np
|
|
from dateutil import parser
|
|
import time
|
|
import math
|
|
from math import sin,cos,atan2,sqrt
|
|
import os,sys
|
|
|
|
# Django
|
|
from django.shortcuts import render_to_response
|
|
from django.http import HttpResponseRedirect, HttpResponse,JsonResponse
|
|
from django.conf import settings
|
|
from django.contrib.auth import authenticate, login, logout
|
|
from django.contrib.auth.models import User
|
|
from django.contrib.auth.decorators import login_required
|
|
|
|
# Project
|
|
# from .models import Profile
|
|
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,
|
|
RUNKEEPER_CLIENT_ID, RUNKEEPER_CLIENT_SECRET,RUNKEEPER_REDIRECT_URI,
|
|
)
|
|
|
|
# Exponentially weighted moving average
|
|
# Used for data smoothing of the jagged data obtained by Strava
|
|
# See bitbucket issue 72
|
|
def ewmovingaverage(interval,window_size):
|
|
# Experimental code using Exponential Weighted moving average
|
|
|
|
try:
|
|
intervaldf = pd.DataFrame({'v':interval})
|
|
idf_ewma1 = intervaldf.ewm(span=window_size)
|
|
idf_ewma2 = intervaldf[::-1].ewm(span=window_size)
|
|
|
|
i_ewma1 = idf_ewma1.mean().ix[:,'v']
|
|
i_ewma2 = idf_ewma2.mean().ix[:,'v']
|
|
|
|
interval2 = np.vstack((i_ewma1,i_ewma2[::-1]))
|
|
interval2 = np.mean( interval2, axis=0) # average
|
|
except ValueError:
|
|
interval2 = interval
|
|
|
|
return interval2
|
|
|
|
from utils import geo_distance
|
|
|
|
|
|
# Custom exception handler, returns a 401 HTTP message
|
|
# with exception details in the json data
|
|
def custom_exception_handler(exc,message):
|
|
|
|
response = {
|
|
"errors": [
|
|
{
|
|
"code": str(exc),
|
|
"detail": message,
|
|
}
|
|
]
|
|
}
|
|
|
|
res = HttpResponse(message)
|
|
res.status_code = 401
|
|
res.json = json.dumps(response)
|
|
|
|
return res
|
|
|
|
# Exchange access code for long-lived access token
|
|
def get_token(code):
|
|
client_auth = requests.auth.HTTPBasicAuth(RUNKEEPER_CLIENT_ID, RUNKEEPER_CLIENT_SECRET)
|
|
post_data = {"grant_type": "authorization_code",
|
|
"code": code,
|
|
"redirect_uri": RUNKEEPER_REDIRECT_URI,
|
|
"client_secret": RUNKEEPER_CLIENT_SECRET,
|
|
"client_id":RUNKEEPER_CLIENT_ID,
|
|
}
|
|
headers = {'user-agent': 'sanderroosendaal'}
|
|
response = requests.post("https://runkeeper.com/apps/token",
|
|
data=post_data,
|
|
headers=headers)
|
|
try:
|
|
token_json = response.json()
|
|
thetoken = token_json['access_token']
|
|
except KeyError:
|
|
thetoken = 0
|
|
|
|
return thetoken
|
|
|
|
# Make authorization URL including random string
|
|
def make_authorization_url(request):
|
|
# Generate a random string for the state parameter
|
|
# Save it for use later to prevent xsrf attacks
|
|
from uuid import uuid4
|
|
state = str(uuid4())
|
|
|
|
params = {"client_id": RUNKEEPER_CLIENT_ID,
|
|
"response_type": "code",
|
|
"redirect_uri": RUNKEEPER_REDIRECT_URI,
|
|
}
|
|
import urllib
|
|
url = "https://www.runkeeper.com/opps/authorize" +urllib.urlencode(params)
|
|
|
|
return HttpResponseRedirect(url)
|
|
|
|
# Get list of workouts available on Runkeeper
|
|
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)
|
|
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)
|
|
|
|
return s
|
|
|
|
# Get workout summary data by Runkeeper ID
|
|
def get_runkeeper_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"
|
|
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)
|
|
|
|
return s
|
|
|
|
# Generate Workout data for Runkeeper (a TCX file)
|
|
def createrunkeeperworkoutdata(w):
|
|
filename = w.csvfilename
|
|
try:
|
|
row = rowingdata(filename)
|
|
tcxfilename = filename[:-4]+'.tcx'
|
|
row.exporttotcx(tcxfilename,notes=w.notes)
|
|
except:
|
|
tcxfilename = 0
|
|
|
|
return tcxfilename
|
|
|
|
# Upload the TCX file to Runkeeper and set the workout activity type
|
|
# to rowing on Runkeeper
|
|
def handle_runkeeperexport(f2,workoutname,runkeepertoken,description=''):
|
|
# w = Workout.objects.get(id=workoutid)
|
|
client = runkeeperlib.Client(access_token=runkeepertoken)
|
|
|
|
act = client.upload_activity(f2,'tcx',name=workoutname)
|
|
try:
|
|
res = act.wait(poll_interval=5.0,timeout=30)
|
|
message = 'Workout successfully synchronized to Runkeeper'
|
|
except:
|
|
res = 0
|
|
|
|
|
|
|
|
# description doesn't work yet. Have to wait for runkeeperlib to update
|
|
if res:
|
|
act = client.update_activity(res.id,activity_type='Rowing',description=description)
|
|
else:
|
|
message = 'Runkeeper upload timed out.'
|
|
return (0,message)
|
|
|
|
return (res.id,message)
|
|
|
|
|