Created
September 30, 2018 21:54
-
-
Save abfo/91d060e4abd889d2766f965a3b9cb9b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add your Google API Project OAuth client ID and client secret here | |
var ClientID = ''; | |
var ClientSecret = ''; | |
function onOpen() { | |
var ui = SpreadsheetApp.getUi(); | |
ui.createMenu('Google Fit') | |
.addItem('Authorize if needed (does nothing if already authorized)', 'showSidebar') | |
.addItem('Get Steps for Yesterday', 'getSteps') | |
.addItem('Get Steps for past 30 days', 'getHistory') | |
.addToUi(); | |
} | |
function getSteps() { | |
getStepsForDay(1, 'Steps'); | |
} | |
function getHistory() { | |
for(var day = 1; day <= 30; day++) { | |
getStepsForDay(day, 'History'); | |
} | |
} | |
// see step count example at https://developers.google.com/fit/scenarios/read-daily-step-total | |
function getStepsForDay(daysAgo, tabName) { | |
var start = new Date(); | |
start.setHours(0,0,0,0); | |
start.setDate(start.getDate() - daysAgo); | |
var end = new Date(); | |
end.setHours(23,59,59,999); | |
end.setDate(end.getDate() - daysAgo); | |
var fitService = getFitService(); | |
var request = { | |
"aggregateBy": [{ | |
"dataTypeName": "com.google.step_count.delta", | |
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps" | |
}], | |
"bucketByTime": { "durationMillis": 86400000 }, | |
"startTimeMillis": start.getTime(), | |
"endTimeMillis": end.getTime() | |
}; | |
var response = UrlFetchApp.fetch('https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate', { | |
headers: { | |
Authorization: 'Bearer ' + fitService.getAccessToken() | |
}, | |
'method' : 'post', | |
'contentType' : 'application/json', | |
'payload' : JSON.stringify(request, null, 2) | |
}); | |
var json = JSON.parse(response.getContentText()); | |
var steps = json.bucket[0].dataset[0].point[0].value[0].intVal; | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheet = ss.getSheetByName(tabName); | |
sheet.appendRow([start, steps]); | |
} | |
// functions below adapted from Google OAuth example at https://github.com/googlesamples/apps-script-oauth2 | |
function getFitService() { | |
// Create a new service with the given name. The name will be used when | |
// persisting the authorized token, so ensure it is unique within the | |
// scope of the property store. | |
return OAuth2.createService('fit') | |
// Set the endpoint URLs, which are the same for all Google services. | |
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') | |
.setTokenUrl('https://accounts.google.com/o/oauth2/token') | |
// Set the client ID and secret, from the Google Developers Console. | |
.setClientId(ClientID) | |
.setClientSecret(ClientSecret) | |
// Set the name of the callback function in the script referenced | |
// above that should be invoked to complete the OAuth flow. | |
.setCallbackFunction('authCallback') | |
// Set the property store where authorized tokens should be persisted. | |
.setPropertyStore(PropertiesService.getUserProperties()) | |
// Set the scopes to request (space-separated for Google services). | |
// see https://developers.google.com/fit/rest/v1/authorization for a list of Google Fit scopes | |
.setScope('https://www.googleapis.com/auth/fitness.activity.read') | |
// Below are Google-specific OAuth2 parameters. | |
// Sets the login hint, which will prevent the account chooser screen | |
// from being shown to users logged in with multiple accounts. | |
.setParam('login_hint', Session.getActiveUser().getEmail()) | |
// Requests offline access. | |
.setParam('access_type', 'offline') | |
// Forces the approval prompt every time. This is useful for testing, | |
// but not desirable in a production application. | |
//.setParam('approval_prompt', 'force'); | |
} | |
function showSidebar() { | |
var fitService = getFitService(); | |
if (!fitService.hasAccess()) { | |
var authorizationUrl = fitService.getAuthorizationUrl(); | |
var template = HtmlService.createTemplate( | |
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' + | |
'Close this after you have finished.'); | |
template.authorizationUrl = authorizationUrl; | |
var page = template.evaluate(); | |
SpreadsheetApp.getUi().showSidebar(page); | |
} else { | |
// ... | |
} | |
} | |
function authCallback(request) { | |
var fitService = getFitService(); | |
var isAuthorized = fitService.handleCallback(request); | |
if (isAuthorized) { | |
return HtmlService.createHtmlOutput('Success! You can close this tab.'); | |
} else { | |
return HtmlService.createHtmlOutput('Denied. You can close this tab'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment