var doGetPin = function(onSuccess) { Settings.data('authPin', null); Settings.data('authCode', null); Settings.data('authExpires', null); var card = new UI.Card(); card.title('Authorization'); card.body('Calling ecobee for authorization. Please wait.'); card.show(); var authUrl = Settings.data('ecobeeServerUrl')+ '/authorize?response_type=ecobeePin&scope=smartWrite&client_id='+ Settings.data('clientId'); ajax( { url: authUrl, type: 'json' }, function(data) { Vibe.vibrate('short'); console.log('Received AUTH data: '+JSON.stringify(data)); Settings.data('authPin', data.ecobeePin); Settings.data('authCode', data.code); var expiresAt = Date.now()+data.expires_in*60*1000; console.log('Pin will expire at '+expiresAt); Settings.data('authExpires', expiresAt); card.hide(); authPin(data.ecobeePin, data.code, onSuccess); }, function(error) { console.log('Error receiving AUTH data: '+JSON.stringify(error)); card.hide(); ErrorWindow.show('Unable to contact ecobee. Try again later.'); } ); };
postThermostat: function(req, onSuccess, onError) { cache = null; //SO that it refreshes var token = Oauth.getAccessToken(false); var callUrl = Settings.data('ecobeeServerUrl')+Settings.data('ecobeeApiEndpoint')+'?format=json'; console.log('POST '+JSON.stringify(req)+' to '+callUrl+' with OAuth token: '+token); ajax( { url: callUrl, type: 'json', method: 'post', headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Authorization': 'Bearer '+token }, data: req }, function(data) { console.log('Received data: '+JSON.stringify(data)); if (data.status.code!==0) { onError(data.status.message); } else { onSuccess(); } }, function(error) { console.log('Error receiving ecobee data: '+JSON.stringify(error)); onError(error); } ); }
var gameOver = function(winner){ var card = new UI.Card(); var data = Settings.data(); card.title('Game Over'); card.subtitle(Settings.data(winner) + ' wins!'); card.body(getBody() + "\nLong Click to Post"); Vibe.vibrate('short'); card.on('longClick', 'down', function(e){ var loser = ''; var winnerScore = loserScore = 0; if (winner === 'player1'){ loser = 'player2' winnerScore = 'player1Score'; loserScore = 'player2Score'; } else { loser = 'player1'; winnerScore = 'player2Score'; loserScore = 'player1Score'; } ajax({ url: config.WEBHOOK_URL + Settings.data(winner) + '/' + Settings.data(winnerScore) + '/' + Settings.data(loser) + '/' + Settings.data(loserScore), method: 'post' }); Vibe.vibrate('double'); card.hide(); }); card.show(); }
var checkScore = function(){ var player1Score = Settings.data('player1Score'); var player2Score = Settings.data('player2Score'); var highScore = 0, lowScore = 0; var winning = ''; if (player1Score === player2Score) return; if (player1Score > player2Score){ winning = 'player1'; highScore = player1Score; lowScore = player2Score; } else { winning = 'player2'; highScore = player2Score; lowScore = player1Score; } // Skunk if (highScore === 7 && lowScore === 0){ gameOver(winning); } // Normal win if (highScore >= 11 && (highScore - lowScore) >= 2){ gameOver(winning); } }
var display_locations_ok=function(result) { if (typeof result.error == 'undefined') { main.body("Location received"); // will need to allow the user to chose this via a menu in the future Settings.data("smappee_conf").serviceLocations=new Array(result.length); //console.log('# of locations :'+result.length); //console.log(JSON.stringify(result)); menu.items(MENU_LOCATION,new Array(result.length)); for (var i=0;i<result.length;i++) { //[{"serviceLocationId":7809,"name":"Page d'accueil"}] Settings.data("smappee_conf").serviceLocations[i]={'name':result[i].name,'locationID':result[i].serviceLocationId}; //menu.item(MENU_LOCATION, i, { title: result[i].name, subtitle: 'ID = '+result[i].serviceLocationId }); } update_location_menu(); //console.log(JSON.stringify(Settings.data("smappee_conf").serviceLocations)); smappee.getConsumption(Settings.data('smappee_conf'),display_cons); } else { console.log('Error retreiving locations'); console.log(result.message); } };
menu.on('select', function(e) { console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex); console.log('The item is titled "' + e.item.title + '"'); var aItems = Settings.data("buyList"); aItems.splice(e.itemIndex, 1); Settings.data("buyList", aItems); menu.items(0, aItems); });
function(data) { console.log('Received AUTH data: '+JSON.stringify(data)); Settings.data('refreshToken', data.refresh_token); Settings.data('oauthToken', data.access_token); var tokenExpiresIn = Date.now()+data.expires_in*1000; console.log('Token '+data.access_token+' will expire at '+tokenExpiresIn); Settings.data('oauthTokenExpires', tokenExpiresIn); return data.access_token; },
function(data) { Vibe.vibrate('short'); console.log('Received AUTH data: '+JSON.stringify(data)); Settings.data('authPin', data.ecobeePin); Settings.data('authCode', data.code); var expiresAt = Date.now()+data.expires_in*60*1000; console.log('Pin will expire at '+expiresAt); Settings.data('authExpires', expiresAt); card.hide(); authPin(data.ecobeePin, data.code, onSuccess); },
Pebble.addEventListener('webviewclosed', function(e) { // Decode the user's preferences //console.log(e.response); //var configData = JSON.parse(decodeURIComponent(e.response)); //console.log("Decoded config"); //console.log(JSON.stringify(configData)); main.body("received config"); smappee_conf=JSON.parse(decodeURIComponent(e.response)); Settings.data("smappee_conf",smappee_conf); Settings.data("smappee_conf").serviceLocationIndex=0; smappee.getToken(smappee_conf, once_token_obtained); });
main.on('longClick', 'select', function(e) { Settings.data({ player1Score: 0, player2Score: 0 }); main.body(getBody()); });
menu.on('select', function(e) { console.log('Selected item #' + e.itemIndex); console.log('The selection is titled "' + e.item.title + '"'); Settings.data('player2', e.item.title); main.body(getBody()); menu.hide(); });
function reportError( err ) { if(DEBUG) console.log( "Reporting Error" ); var today = new Date(); if( Settings.option( "reporting" ) ) { ajax( { url: reporting, type: "string", method: "post", data: { timestamp: today.toISOString(), error: err, identifier: Settings.data( "user" ).email, version: VERSION } }, function( data ) { if(DEBUG) console.log( "Error Reported: " + err ); if(DEBUG) console.log( data ); }, function( err ) { if(DEBUG) console.log( "Error Report Failed: " + JSON.stringify( err ) ); }); } else return false; }
var whatever = function() { console.log("whatever"); if (recentDrinks >= 7) { Settings.data('drinks', 0); setTimeout(function() { Vibe.vibrate('short'); var ordrinCard = new UI.Card({ title: "Want to Ordr.in some PIZZA?", body: '#HELLYEAH ->' }); ordrinCard.show(); card.hide(); ordrinCard.on('click', 'select', function() { var confirmationCard = new UI.Card({ title: "Ta Ta's Pizza is on its way!", body: ':P' }); confirmationCard.show(); ordrinCard.hide(); setTimeout(function() { confirmationCard.hide(); }, 2000); }); }, 3000); } else { console.log("test"); setTimeout(function() { console.log("k"); card.hide(); }, 3000); } };
// PROGRAM START function programStart() { if( typeof Settings.option( "token" ) !== "undefined" && Settings.option( "token" ) !== null ) { //splash.show(); noConfig.hide(); if( Settings.data( "user" ) === null ) getUserData(); try { getListPositions( function() { getShares( function() { getLists( null, function() { listMenu.show(); //splash.hide(); }); }); }); } catch( err ) { reportError( "Program Start: " + err.message ); } } else { noConfig.show(); } }
function fnFactory() { var items = Settings.data("buyList") || []; if (items.length === 0) { var aList = [ "Банани", "Огірки", "Помідори" ]; items = aList.map(function(el) { return { title: el }; }); Settings.data("buyList", items); } return items; }
var post_token_refresh=function(result) { if (typeof result.error == 'undefined') { console.log(JSON.stringify(result)); Settings.data("smappee_conf").refresh_token=result.refresh_token; Settings.data("smappee_conf").access_token=result.access_token; Settings.data("smappee_conf").expires_on=result.expires_on; console.log("REfresh is a success"); console.log(JSON.stringify(Settings.data("smappee_conf"))); smappee.getLocations(Settings.data("smappee_conf"),display_locations_ok); } else { main.body("Could not\r\nrefresh token"); } };
HoleController.prototype.saveData = function() { console.log('saving data'); console.log(JSON.stringify(this.data)); this.round[this.hole - 1] = this.data; Settings.data('round', this.round); };
loadThermostat: function(tstatId, onSuccess, onError) { //TODO: Add caching if (Date.now()>cacheExpiration) { console.log('Cache expired'); cache = null; } if (cache && cache!==null) { console.log('Data in cache: '+JSON.stringify(cache)); if (!tstatId || tstatId===cache.identifier) { console.log('Returning cached thermostat'); return cache; } } var token = Oauth.getAccessToken(false); var callUrl = Settings.data('ecobeeServerUrl')+ Settings.data('ecobeeApiEndpoint')+ '?json='+encodeURIComponent(JSON.stringify(jsonRequest)); console.log('GET '+callUrl+' with OAuth token: '+token); ajax( { url: callUrl, type: 'json', method: 'get', headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Authorization': 'Bearer '+token } }, function(data) { console.log('Received data: '+JSON.stringify(data)); if (data.status.code!==0) { onError(data.status.message); } else if (data.thermostatList.length===0) { onError('No thermostats linked to account'); } else { cache = data.thermostatList[0]; cacheExpiration = Date.now()+30*1000; onSuccess(cache); } }, function(error) { console.log('Error receiving ecobee data: '+JSON.stringify(error)); onError(error); } ); },
module.exports.send = function(method, params, callback, errorCallback) { if (require('./screen-main').DEMO_MODE) { return; } var kodiHost = Settings.data('activeHost'); callback = callback || function() {}; errorCallback = errorCallback || function() {}; if (!kodiHost) { return false; } var data = { "jsonrpc": "2.0", "method": method, "params": params, "id": Math.ceil(Math.random() * 10000) }; // Now comes the hacky party that works around a bug in Android webview URIdecoding strings twice var un; var pw; try { un = decodeURIComponent(kodiHost.username); pw = decodeURIComponent(kodiHost.password); } catch(e) { un = kodiHost.username; pw = kodiHost.password; } var authPart = (un && pw) ? encodeURIComponent(un) + ':' + encodeURIComponent(pw) + '@' : ''; if (SHOULD_LOG) console.log('Sending ' + (authPart ? 'with auth ' + un + ':' + pw : 'without auth') + ': ' + JSON.stringify(data, null, '')); ajax( { url: 'http://' + authPart + kodiHost.address + '/jsonrpc?Base', method: 'post', type: 'json', data: data }, function(data, status, request) { if (SHOULD_LOG) console.log(status + ': ' + JSON.stringify(data)); callback(data); }, function(error, status, request) { if (SHOULD_LOG) console.log('ajax error: ' + method); var newError = { httpStatusCode: status, serverMessage: error }; if (SHOULD_LOG) console.log(JSON.stringify(newError)); errorCallback(newError); } ); };
menu.on('select', function(e) { console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex); console.log('The item is titled "' + e.item.title + '"'); if (e.sectionIndex==MENU_LOCATION) { Settings.data("smappee_conf").serviceLocationIndex=e.itemIndex; refresh(); } menu.hide(); });
RoundController.prototype.items = function() { var round; if (Settings.data('round')) { round = Settings.data('round'); } else { round = []; } console.info('round'); console.log(JSON.stringify(round)); var items = round.map(function(elt, index) { console.log('map'); console.log(JSON.stringify(elt)); if (!elt) { elt = {}; } elt.throws = elt.throws || Settings.option('defaultThrows'); elt.par = elt.par || Settings.option('defaultpar'); return { title: '#' + (index+1) + '. ' + elt.throws + '/' + elt.par, }; }); items.push({ title: 'Add hole' }); console.info('items'); console.log(JSON.stringify(items)); return items; };
card.on('longClick', 'down', function(e){ var loser = ''; var winnerScore = loserScore = 0; if (winner === 'player1'){ loser = 'player2' winnerScore = 'player1Score'; loserScore = 'player2Score'; } else { loser = 'player1'; winnerScore = 'player2Score'; loserScore = 'player1Score'; } ajax({ url: config.WEBHOOK_URL + Settings.data(winner) + '/' + Settings.data(winnerScore) + '/' + Settings.data(loser) + '/' + Settings.data(loserScore), method: 'post' }); Vibe.vibrate('double'); card.hide(); });
menu.on('longSelect', function(e) { if (e.sectionIndex > 0) { // console.log('Adding ' + e.item.id + ' to favorites.'); favorites.push(e.item); storedLocations[e.item.id] = stopLocations[e.item.id]; menu.items(e.sectionIndex).splice(e.itemIndex, 1); } else { // console.log('Removing ' + e.item.id + ' from favorites.'); e.item.subtitle = e.item.dist; menu.items(1).push(e.item); favorites.splice(e.itemIndex, 1); storedLocations[e.item.id] = null; } menu.items(0, favorites); for (var f in favorites) { favorites[f].subtitle = favorites[f].addr; } Settings.data('favorites', favorites); Settings.data('storedLocations', storedLocations); });
card.on('click', 'select', function(e) { var tokenUrl = Settings.data('ecobeeServerUrl') + Settings.data('ecobeeTokenApi') + '?grant_type=ecobeePin&client_id=' + Settings.data('clientId') + "&code=" + code; console.log('Calling '+tokenUrl); ajax( { url: tokenUrl, type: 'json', method: 'post' }, function(data) { Vibe.vibrate('short'); console.log('Received AUTH data: '+JSON.stringify(data)); Settings.data('authPin', null); Settings.data('authCode', null); Settings.data('authExpires', null); Settings.data('paired', true); Settings.data('refreshToken', data.refresh_token); Settings.data('oauthToken', data.access_token); var tokenExpiresIn = Date.now()+data.expires_in*1000; console.log('Token '+data.access_token+' will expire at '+tokenExpiresIn); Settings.data('oauthTokenExpires', tokenExpiresIn); card.hide(); onSuccess(); }, function(error) { console.log('Error receiving AUTH data: '+JSON.stringify(error)); if (error.error === "authorization_pending") { card.hide(); this.authorizePin(pin, code); } else { ErrorWindow.show(); card = new UI.Card(error.error_description); } } ); });
rep_nums.on('select', function(j) { var reps = j.item.title; var time = print_time(); var date_and_time = today + " " + time; var date_time = date_and_time; //var sets_and_reps = sets + "-" + reps; save(date_time, {exercise: exer, weight: weight_choice, sets: sets, reps: reps, time: time, date: today}); console.log("This is where save should execute"); //var workout_record = Settings.data('workout_record'); //console.log(workout_record.time); var data = Settings.data(); console.log(JSON.stringify(data)); // date_and_time: date_and_time, , , sets_reps: sets_and_reps });
var update_location_menu=function() { var servLoc=Settings.data("smappee_conf").serviceLocations; if (typeof servLoc != 'undefined') { menu.items(MENU_LOCATION,new Array(servLoc.length)); for (var i=0;i<servLoc.length;i++) { menu.item(MENU_LOCATION, i, { title: servLoc[i].name, subtitle: 'ID = '+servLoc[i].locationID }); } } else { console.log("WARNING : no serviceLocation defined"); menu.items(MENU_LOCATION,[{title:'not defined'}]); } };
var refresh=function() { if (typeof smappee_conf.expires_on=="undefined") { main.body("First connection\r\nPlease configure"); } else { main.body("Checking token"); if (smappee_conf.expires_on<Date.now()) { console.log("Need to refresh token"); main.body("Refreshing token"); smappee.refreshToken(Settings.data("smappee_conf"),post_token_refresh); } else { main.body("Token fresh enough"); smappee.getLocations(Settings.data("smappee_conf"),display_locations_ok); } } };
main.on('select', function(e) { var recentDrinks = Settings.data('drinks') || 0; recentDrinks += 1; Settings.data('drinks', recentDrinks); console.log(recentDrinks); var bac = BACAt(recentDrinks, (new Date()).getTime() - Settings.data('startTime'), Settings.data('gender'), Settings.data('weight')); var timeTilSober = tForBAC(bac); var card = notify('Logging Drink', e.item.title, 'Your current BAC Level is: ' + bac.toFixed(3).toString() + '% and it will take you ' + timeTilSober.toFixed(1).toString() + ' hours to be totally sober.'); main.hide(); var whatever = function() { console.log("whatever"); if (recentDrinks >= 7) { Settings.data('drinks', 0); setTimeout(function() { Vibe.vibrate('short'); var ordrinCard = new UI.Card({ title: "Want to Ordr.in some PIZZA?", body: '#HELLYEAH ->' }); ordrinCard.show(); card.hide(); ordrinCard.on('click', 'select', function() { var confirmationCard = new UI.Card({ title: "Ta Ta's Pizza is on its way!", body: ':P' }); confirmationCard.show(); ordrinCard.hide(); setTimeout(function() { confirmationCard.hide(); }, 2000); }); }, 3000); } else { console.log("test"); setTimeout(function() { console.log("k"); card.hide(); }, 3000); } }; console.log("wat"); ajax({ url: mainURL + '/drink', method: 'POST', data: { drinkId: e.item.title, email: Settings.data('email') } }, whatever, whatever); });
Locations.urlStops = function(coords) { var region = Locations.geoRegion(coords); // console.log('reached Locations.urlStops! ' + region) var radius = Settings.data()["searchRadius"] || 260; var latlon = "&lat=" + coords.lat + "&lon=" + coords.lon; if (Helper.arrayContains(["pugetsound","newyork","tampa"], region)) { return Locations.urlBus("stopsForLocations", region) + KEY[region] + latlon + "&radius=" + radius; } else if (region === "boston") { return Locations.urlBus("stopsForLocations", region) + KEY[region] + latlon + "&format=json"; } else if (region === "portland") { return Locations.urlBus("stopsForLocations", region) + KEY[region] + "&ll=" + coords.lat + "," + coords.lon + "&json=true&meters=" + radius; } else if (region === "vancouver") { return Locations.urlBus("stopsForLocations", region) + KEY[region] + "&lat=" + coords.lat + "&long=" + coords.lon + "&radius=" + radius; } return null; }
}, function(e) { // close console.log(JSON.stringify(e.options)); if (!Settings.data('isLoggedIn')) { // first use, therefore data Settings.data('weight', e.options.weight); Settings.data('gender', e.options.gender === 'M'); Settings.data('email', e.options.email); Settings.data('isLoggedIn', true); } else { Settings.data('startTime', (new Date()).getTime()); Settings.data('drinks', 0); } });