Guest User

Untitled

a guest
Apr 30th, 2015
944
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* FitbitDownload.gs
  2. This script will access your Fitbit data via the Fitbit API and insert it into a Google spreadsheet.
  3. The first row of the spreadsheet will be a header row containing data element names. Subsequent rows will contain data, one day per row.
  4. Note that Fitbit uses metric units (weight, distance) so you may wish to convert them.
  5. Original script by [email protected]
  6. Original instructional video by Ernesto Ramirez at http://vimeo.com/26338767
  7. Modifications by Mark Leavitt (PDX Quantified Self organizer) www.markleavitt.com
  8. Here's to your (quantified) health!
  9. */
  10.  
  11. // Key of ScriptProperty for Firtbit consumer key.
  12. var CONSUMER_KEY_PROPERTY_NAME = "fitbitConsumerKey";
  13. // Key of ScriptProperty for Fitbit consumer secret.
  14. var CONSUMER_SECRET_PROPERTY_NAME = "fitbitConsumerSecret";
  15. // Default loggable resources (from Fitbit API docs).
  16. var LOGGABLES = ["activities/log/steps", "activities/log/distance",
  17.     "activities/log/activeScore", "activities/log/activityCalories",
  18.     "activities/log/calories", "foods/log/caloriesIn",
  19.     "activities/log/minutesSedentary",
  20.     "activities/log/minutesLightlyActive",
  21.     "activities/log/minutesFairlyActive",
  22.     "activities/log/minutesVeryActive", "sleep/timeInBed",
  23.     "sleep/minutesAsleep", "sleep/minutesAwake", "sleep/awakeningsCount",
  24.     "body/weight", "body/bmi", "body/fat",];
  25.  
  26. // function authorize() makes a call to the Fitbit API to fetch the user profile    
  27. function authorize() {
  28.     var oAuthConfig = UrlFetchApp.addOAuthService("fitbit");
  29.     oAuthConfig.setAccessTokenUrl("https://api.fitbit.com/oauth/access_token");
  30.     oAuthConfig.setRequestTokenUrl("https://api.fitbit.com/oauth/request_token");
  31.     oAuthConfig.setAuthorizationUrl("https://api.fitbit.com/oauth/authorize");
  32.     oAuthConfig.setConsumerKey(getConsumerKey());
  33.     oAuthConfig.setConsumerSecret(getConsumerSecret());
  34.     var options = {
  35.         "oAuthServiceName": "fitbit",
  36.         "oAuthUseToken": "always",
  37.     };
  38.     // get the profile to force authentication
  39.     Logger.log("Function authorize() is attempting a fetch...");
  40.     try {
  41.        var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/profile.json", options);
  42.        var o = Utilities.jsonParse(result.getContentText());
  43.        return o.user;
  44.     }
  45.     catch (exception) {
  46.        Logger.log(exception);
  47.        Browser.msgBox("Error attempting authorization");
  48.        return null;
  49.     }
  50. }
  51.  
  52. // function setup accepts and stores the Consumer Key, Consumer Secret, firstDate, and list of Data Elements
  53. function setup() {
  54.     var doc = SpreadsheetApp.getActiveSpreadsheet();
  55.     var app = UiApp.createApplication().setTitle("Setup Fitbit Download");
  56.     app.setStyleAttribute("padding", "10px");
  57.  
  58.     var consumerKeyLabel = app.createLabel("Fitbit OAuth Consumer Key:*");
  59.     var consumerKey = app.createTextBox();
  60.     consumerKey.setName("consumerKey");
  61.     consumerKey.setWidth("100%");
  62.     consumerKey.setText(getConsumerKey());
  63.     var consumerSecretLabel = app.createLabel("Fitbit OAuth Consumer Secret:*");
  64.     var consumerSecret = app.createTextBox();
  65.     consumerSecret.setName("consumerSecret");
  66.     consumerSecret.setWidth("100%");
  67.     consumerSecret.setText(getConsumerSecret());
  68.     var firstDate = app.createTextBox().setId("firstDate").setName("firstDate");
  69.     firstDate.setName("firstDate");
  70.     firstDate.setWidth("100%");
  71.     firstDate.setText(getFirstDate());
  72.  
  73.     // add listbox to select data elements
  74.     var loggables = app.createListBox(true).setId("loggables").setName(
  75.       "loggables");
  76.     loggables.setVisibleItemCount(4);
  77.     // add all possible elements (in array LOGGABLES)
  78.     var logIndex = 0;
  79.     for (var resource in LOGGABLES) {
  80.         loggables.addItem(LOGGABLES[resource]);
  81.         // check if this resource is in the getLoggables list
  82.         if (getLoggables().indexOf(LOGGABLES[resource]) > -1) {
  83.           // if so, pre-select it
  84.           loggables.setItemSelected(logIndex, true);
  85.         }
  86.         logIndex++;
  87.     }
  88.     // create the save handler and button
  89.     var saveHandler = app.createServerClickHandler("saveSetup");
  90.     var saveButton = app.createButton("Save Setup", saveHandler);
  91.  
  92.     // put the controls in a grid
  93.     var listPanel = app.createGrid(6, 3);
  94.     listPanel.setWidget(1, 0, consumerKeyLabel);
  95.     listPanel.setWidget(1, 1, consumerKey);
  96.     listPanel.setWidget(2, 0, consumerSecretLabel);
  97.     listPanel.setWidget(2, 1, consumerSecret);
  98.     listPanel.setWidget(3, 0, app.createLabel(" * (obtain these at dev.fitbit.com)"));
  99.     listPanel.setWidget(4, 0, app.createLabel("Start Date for download (yyyy-mm-dd)"));
  100.     listPanel.setWidget(4, 1, firstDate);
  101.     listPanel.setWidget(5, 0, app.createLabel("Data Elements to download:"));
  102.     listPanel.setWidget(5, 1, loggables);
  103.    
  104.     // Ensure that all controls in the grid are handled
  105.     saveHandler.addCallbackElement(listPanel);
  106.     // Build a FlowPanel, adding the grid and the save button
  107.     var dialogPanel = app.createFlowPanel();
  108.     dialogPanel.add(listPanel);
  109.     dialogPanel.add(saveButton);
  110.     app.add(dialogPanel);
  111.     doc.show(app);
  112. }
  113.  
  114. // function sync() is called to download all desired data from Fitbit API to the spreadsheet                
  115. function sync() {
  116.     // if the user has never performed setup, do it now
  117.     if (!isConfigured()) {
  118.         setup();
  119.         return;
  120.     }
  121.  
  122.     var user = authorize();
  123.     var doc = SpreadsheetApp.getActiveSpreadsheet();
  124.     doc.setFrozenRows(1);
  125.     var options = {
  126.         "oAuthServiceName": "fitbit",
  127.         "oAuthUseToken": "always",
  128.         "method": "GET"
  129.     };
  130.     // prepare and format today's date, and a list of desired data elements
  131.     var dateString = formatToday();
  132.     var activities = getLoggables();
  133.     // for each data element, fetch a list beginning from the firstDate, ending with today
  134.     for (var activity in activities) {
  135.         var currentActivity = activities[activity];
  136.         try {
  137.             var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/"
  138.           + currentActivity + "/date/" + getFirstDate() + "/"
  139.           + dateString + ".json", options);
  140.         } catch (exception) {
  141.             Logger.log(exception);
  142.             Browser.msgBox("Error downloading " + currentActivity);
  143.         }
  144.         var o = Utilities.jsonParse(result.getContentText());
  145.  
  146.         // set title
  147.         var titleCell = doc.getRange("a1");
  148.         titleCell.setValue("date");
  149.         var cell = doc.getRange('a2');
  150.  
  151.         // fill the spreadsheet with the data
  152.         var index = 0;
  153.         for (var i in o) {
  154.             // set title for this column
  155.             var title = i.substring(i.lastIndexOf('-') + 1);
  156.             titleCell.offset(0, 1 + activity * 1.0).setValue(title);
  157.  
  158.             var row = o[i];
  159.             for (var j in row) {
  160.                 var val = row[j];
  161.                 cell.offset(index, 0).setValue(val["dateTime"]);
  162.                 // set the date index
  163.                 cell.offset(index, 1 + activity * 1.0).setValue(val["value"]);
  164.                 // set the value index index
  165.                 index++;
  166.             }
  167.         }
  168.     }
  169. }
  170.  
  171. function isConfigured() {
  172.     return getConsumerKey() != "" && getConsumerSecret() != "";
  173. }
  174.  
  175. function setConsumerKey(key) {
  176.     ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
  177. }
  178.  
  179. function getConsumerKey() {
  180.     var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
  181.     if (key == null) {
  182.         key = "";
  183.     }
  184.     return key;
  185. }
  186.  
  187. function setLoggables(loggable) {
  188.     ScriptProperties.setProperty("loggables", loggable);
  189. }
  190.  
  191. function getLoggables() {
  192.     var loggable = ScriptProperties.getProperty("loggables");
  193.     if (loggable == null) {
  194.         loggable = LOGGABLES;
  195.     } else {
  196.         loggable = loggable.split(',');
  197.     }
  198.     return loggable;
  199. }
  200.  
  201. function setFirstDate(firstDate) {
  202.     ScriptProperties.setProperty("firstDate", firstDate);
  203. }
  204.  
  205. function getFirstDate() {
  206.     var firstDate = ScriptProperties.getProperty("firstDate");
  207.     if (firstDate == null) {
  208.         firstDate = "2012-01-01";
  209.     }
  210.     return firstDate;
  211. }
  212.  
  213. function formatToday() {
  214.     var todayDate = new Date;
  215.     return todayDate.getFullYear()
  216.     + '-'
  217.     + ("00" + (todayDate.getMonth() + 1)).slice(-2)
  218.     + '-'
  219.     + ("00" + todayDate.getDate()).slice(-2);
  220. }
  221.  
  222. function setConsumerSecret(secret) {
  223.     ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
  224. }
  225.  
  226. function getConsumerSecret() {
  227.     var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
  228.     if (secret == null) {
  229.         secret = "";
  230.     }
  231.     return secret;
  232. }
  233.  
  234. // function saveSetup saves the setup params from the UI
  235. function saveSetup(e) {
  236.     setConsumerKey(e.parameter.consumerKey);
  237.     setConsumerSecret(e.parameter.consumerSecret);
  238.     setLoggables(e.parameter.loggables);
  239.     setFirstDate(e.parameter.firstDate);
  240.     var app = UiApp.getActiveApplication();
  241.     app.close();
  242.     return app;
  243. }
  244.  
  245. // function onOpen is called when the spreadsheet is opened; adds the Fitbit menu
  246. function onOpen() {
  247.     var ss = SpreadsheetApp.getActiveSpreadsheet();
  248.     var menuEntries = [{
  249.         name: "Sync",
  250.         functionName: "sync"
  251.     }, {
  252.         name: "Setup",
  253.         functionName: "setup"
  254.     }, {
  255.         name: "Authorize",
  256.         functionName: "authorize"
  257.     }];
  258.     ss.addMenu("Fitbit", menuEntries);
  259. }
  260.  
  261. // function onInstall is called when the script is installed (obsolete?)
  262. function onInstall() {
  263.     onOpen();
  264. }
Advertisement
Add Comment
Please, Sign In to add comment