Comments (11)
@Deenthemachine what portions did you take out? That might have affected how the script runs. Also, how many workouts are you syncing over? If it's over 1,000 workouts it might start having performance issues like the error you received (I haven't tested this script with accounts that have over 1,000 workouts).
from peloton-coda-sync.
I took out the friends workout portion and some of the instructor data, see below for the code I currently have (with my username/PW removed of course). I'm at 859 workouts so might be getting long. Is there a way to only pull in bike workouts?
// One-way data sync from Peloton API to Coda in Google Apps Script
// Author: Al Chen ([email protected])
// Last Updated: March 2nd, 2021
// Notes: Assumes you are using the V8 runtime (https://developers.google.com/apps-script/guides/v8-runtime)
// Coda's library for Google Apps Script: 15IQuWOk8MqT50FDWomh57UqWGH23gjsWVWYFms3ton6L-UHmefYHS9Vl
// See full writeup here:
//////////////// Setup and global variables ////////////////////////////////
CodaAPI.authenticate('80ee79e3-8813-421b-999b-87120f1793d2')
CODA_DOC_ID = 'nLz60leWPP'
PELOTON_USERNAME = ''
PELOTON_PASSWORD = ''
////////////////////////////////////////////////////////////////////////////
var base_url = 'https://api.onepeloton.com'
var creds = auth()
var options = creds[0]
var userID = creds[1]
CODA_TABLE_NAME = 'Workouts'
function runPelotonSync() {
getPelotonWorkouts()
getPelotonInstructors()
}
// Current workout IDs
function getWorkoutIds() {
var currentWorkoutIds = []
var currentRows = []
var pageToken
do {
var response = CodaAPI.listRows(CODA_DOC_ID, CODA_TABLE_NAME, {limit: 500, pageToken: pageToken});
var currentRows = currentRows.concat(response.items);
pageToken = response.nextPageToken;
} while (pageToken);
currentRows.map(function(row) {
currentWorkoutIds.push(row['name'])
})
return currentWorkoutIds
}
// Get workouts from Peloton API
function getPelotonWorkouts() {
var workoutData = {}
var workouts = JSON.parse(UrlFetchApp.fetch(base_url + '/api/user/' + userID + '/workouts?limit=1000', options), replacer)
workouts['data'].map(function(workout) {
var workoutId = workout['id']
workoutData[workoutId] = {}
var workoutSummary = JSON.parse(UrlFetchApp.fetch(base_url + '/api/workout/' + workoutId, options), replacer)
var workoutPerformance = JSON.parse(UrlFetchApp.fetch(base_url + '/api/workout/' + workoutId + '/performance_graph?every_n=1000', options), replacer)
workoutData[workoutId].summary = workoutSummary
workoutData[workoutId].performance = workoutPerformance
})
// Remove workouts that already exist in Coda
var currentWorkoutIds = getWorkoutIds()
for (var i = 0; i < currentWorkoutIds.length; i++ ) {
if (Object.keys(workoutData).indexOf(currentWorkoutIds[i]) !== -1) {
delete workoutData[currentWorkoutIds[i]]
}
}
// Push new workouts to Coda
var rows = []
for (workout in workoutData) {
var cells = []
cells = [
{'column': 'Workout ID', 'value': workout},
{'column': 'Date', 'value': workoutData[workout]['summary']['created_at']},
{'column': 'Workout Type', 'value': workoutData[workout]['summary']['fitness_discipline']},
{'column': 'Difficulty', 'value': workoutData[workout]['summary']['ride']['difficulty_estimate']},
{'column': 'Duration', 'value': workoutData[workout]['summary']['ride']['duration']},
{'column': 'Class Thumbnail', 'value': workoutData[workout]['summary']['ride']['image_url']},
{'column': 'Instructor ID', 'value': workoutData[workout]['summary']['ride']['instructor_id']},
{'column': 'Workout Name', 'value': workoutData[workout]['summary']['ride']['title']},
{'column': 'Total Workouts', 'value': workoutData[workout]['summary']['ride']['total_workouts']},
{'column': 'Leaderboard Rank', 'value': workoutData[workout]['summary']['leaderboard_rank']},
{'column': 'Leaderboard Users', 'value': workoutData[workout]['summary']['total_leaderboard_users']},
{'column': 'Avg Output (kj)', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['average_summaries'][0] === 'undefined' ? '' : workoutData[workout]['performance']['average_summaries'][0]['value'])},
{'column': 'Avg Cadence', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['average_summaries'][1] === 'undefined' ? '' : workoutData[workout]['performance']['average_summaries'][1]['value'])},
{'column': 'Avg Resistance', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['average_summaries'][2] === 'undefined' ? '' : workoutData[workout]['performance']['average_summaries'][2]['value'])},
{'column': 'Avg Speed (mph)', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['average_summaries'][3] === 'undefined' ? '' : workoutData[workout]['performance']['average_summaries'][3]['value'])},
{'column': 'Total Output (kj)', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['summaries'][0] === 'undefined' ? '' : workoutData[workout]['performance']['summaries'][0]['value'])},
{'column': 'Distance (mi)', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['summaries'][1] === 'undefined' ? '' : workoutData[workout]['performance']['summaries'][1]['value'])},
{'column': 'Calories (kcal)', 'value': (workoutData[workout]['performance']['average_summaries'].length < 1 || typeof workoutData[workout]['performance']['summaries'][2] === 'undefined' ? '' : workoutData[workout]['performance']['summaries'][2]['value'])}
]
rows.push({'cells': cells})
}
CodaAPI.upsertRows(CODA_DOC_ID, CODA_TABLE_NAME, {rows: rows});
Logger.log('Added ' + rows.length + ' workouts')
}
// Get instructors from Peloton API
function getPelotonInstructors() {
var codaInstructorsTable = 'Instructors'
var currentInstructorIds = []
// Get current instructors in Coda
var currentInstructors = CodaAPI.listRows(CODA_DOC_ID, codaInstructorsTable).items
currentInstructors.map(function(instructor) {
currentInstructorIds.push(instructor['name'])
})
var instructors = JSON.parse(UrlFetchApp.fetch(base_url + '/api/instructor?limit=100', options), replacer)['data']
// Remove instructors that already exist in Coda
var newInstructors = []
instructors.map(function(instructor) {
if(currentInstructorIds.indexOf(instructor['id']) == -1) {
newInstructors.push(instructor)
}
})
// Push new instructors to Coda
var rows = []
newInstructors.map(function(instructor) {
var cells = []
cells = [
{'column': 'Instructor ID', 'value': instructor['id']},
{'column': 'Name', 'value': instructor['name']},
{'column': 'Peloton Username', 'value': instructor['username']}
]
rows.push({'cells': cells})
})
CodaAPI.upsertRows(CODA_DOC_ID, codaInstructorsTable, {rows: rows});
Logger.log('Added ' + rows.length + ' instructors')
}
// Helpers
function prettyPrint(value) {
return JSON.stringify(value, null, 2);
}
function auth() {
var base_url = 'https://api.onepeloton.com'
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({'username_or_email': PELOTON_USERNAME, 'password': PELOTON_PASSWORD}),
'muteHttpExceptions' : true
};
var login = UrlFetchApp.fetch(base_url + '/auth/login', options);
var cookie = login.getAllHeaders()['Set-Cookie'];
for (var i = 0; i < cookie.length; i++) {
cookie[i] = cookie[i].split(';')[0];
};
var authenticated_options = {'headers': {'Cookie': cookie.join(';')}}
return [authenticated_options, JSON.parse(login.getContentText())['user_id']]
}
function replacer(key, value) { return (value == null) ? 0 : value }
from peloton-coda-sync.
Also, is it possible to export any of the views to Excel?
from peloton-coda-sync.
Hm this script should work as is. There is one part of the script that you should edit as right now it only pulls 500 workouts. Edit this line and change the limit:500
to limit:1000
(or some higher number):
var response = CodaAPI.listRows(CODA_DOC_ID, CODA_TABLE_NAME, {limit: 500, pageToken: pageToken});
To completely remove the instructor stuff, remove the getPelotonInstructors()
line near the top of the script. Let me know if these changes work!
from peloton-coda-sync.
from peloton-coda-sync.
Do any of the workouts show up at all in the main workouts table in your Coda doc? And I made a mistake in my last reply, can you try changing the limit
in this line to 500 or 100? Trying to see if limiting the amount of data we try to pull back from the Peloton API would work:
var workouts = JSON.parse(UrlFetchApp.fetch(base_url + '/api/user/' + userID + '/workouts?limit=1000', options), replacer)
from peloton-coda-sync.
from peloton-coda-sync.
The easiest way to "export" to Excel is to just copy and paste the Workouts table into Excel. You can also perform most of the formulas in Excel in Coda as well ;)
from peloton-coda-sync.
from peloton-coda-sync.
What happens when you copy all the rows in the Coda table and paste into Excel? Make sure you have highlighted all the rows in the Coda table.
from peloton-coda-sync.
from peloton-coda-sync.
Related Issues (7)
- Some classes with double entries HOT 7
- Error when running Google Script HOT 15
- Google Apps Script Error HOT 2
- Google Apps Script Error HOT 2
- 404 Error HOT 1
- 10 Most Recent Rides Table/View Query HOT 5
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from peloton-coda-sync.