Code Cleanup

This commit is contained in:
Juan Pablo Risso
2015-11-05 10:07:19 -05:00
committed by Yaima Valdivia
parent 4e203e8e13
commit 1039b65c81

View File

@@ -28,15 +28,12 @@ mappings {
path("/receivedToken") { action: [ POST: "receivedToken", GET: "receivedToken"] } path("/receivedToken") { action: [ POST: "receivedToken", GET: "receivedToken"] }
path("/receiveToken") { action: [ POST: "receiveToken", GET: "receiveToken"] } path("/receiveToken") { action: [ POST: "receiveToken", GET: "receiveToken"] }
path("/hookCallback") { action: [ POST: "hookEventHandler", GET: "hookEventHandler"] } path("/hookCallback") { action: [ POST: "hookEventHandler", GET: "hookEventHandler"] }
path("/oauth/initialize") {action: [GET: "oauthInitUrl"]} path("/oauth/initialize") {action: [GET: "oauthInitUrl"]}
path("/oauth/callback") { action: [ GET: "callback" ] } path("/oauth/callback") { action: [ GET: "callback" ] }
} }
def getSmartThingsClientId() { return appSettings.clientId }
def getSmartThingsClientSecret() { return appSettings.clientSecret }
def getServerUrl() { return "https://graph.api.smartthings.com" } def getServerUrl() { return "https://graph.api.smartthings.com" }
def getShardUrl() { return getApiServerUrl() } def getBuildRedirectUrl() { "${serverUrl}/oauth/initialize?appId=${app.id}&access_token=${state.accessToken}&apiServerUrl=${apiServerUrl}" }
def getBuildRedirectUrl() { "${serverUrl}/oauth/initialize?appId=${app.id}&access_token=${state.accessToken}&apiServerUrl=${shardUrl}" }
def buildRedirectUrl(page) { return buildActionUrl(page) } def buildRedirectUrl(page) { return buildActionUrl(page) }
def callback() { def callback() {
@@ -47,7 +44,7 @@ def callback() {
} else { } else {
log.warn "No authQueryString" log.warn "No authQueryString"
} }
if (state.JawboneAccessToken) { if (state.JawboneAccessToken) {
log.debug "Access token already exists" log.debug "Access token already exists"
setup() setup()
@@ -63,9 +60,8 @@ def callback() {
// SmartThings code, which we ignore, as we don't need to exchange for an access token. // SmartThings code, which we ignore, as we don't need to exchange for an access token.
// Instead, go initiate the Jawbone OAuth flow. // Instead, go initiate the Jawbone OAuth flow.
log.debug "Executing callback redirect to auth page" log.debug "Executing callback redirect to auth page"
def stcid = getSmartThingsClientId()
state.oauthInitState = UUID.randomUUID().toString() state.oauthInitState = UUID.randomUUID().toString()
def oauthParams = [response_type: "code", client_id: stcid, scope: "move_read sleep_read", redirect_uri: "${serverUrl}/oauth/callback"] def oauthParams = [response_type: "code", client_id: appSettings.clientId, scope: "move_read sleep_read", redirect_uri: "${serverUrl}/oauth/callback"]
redirect(location: "https://jawbone.com/auth/oauth2/auth?${toQueryString(oauthParams)}") redirect(location: "https://jawbone.com/auth/oauth2/auth?${toQueryString(oauthParams)}")
} }
} else { } else {
@@ -77,7 +73,7 @@ def callback() {
def authPage() { def authPage() {
log.debug "authPage" log.debug "authPage"
def description = null def description = null
if (state.JawboneAccessToken == null) { if (state.JawboneAccessToken == null) {
if (!state.accessToken) { if (!state.accessToken) {
log.debug "About to create access token" log.debug "About to create access token"
@@ -86,12 +82,12 @@ def authPage() {
description = "Click to enter Jawbone Credentials" description = "Click to enter Jawbone Credentials"
def redirectUrl = buildRedirectUrl def redirectUrl = buildRedirectUrl
log.debug "RedirectURL = ${redirectUrl}" log.debug "RedirectURL = ${redirectUrl}"
def donebutton= state.JawboneAccessToken != null def donebutton= state.JawboneAccessToken != null
return dynamicPage(name: "Credentials", title: "Jawbone UP", nextPage: null, uninstall: true, install: donebutton) { return dynamicPage(name: "Credentials", title: "Jawbone UP", nextPage: null, uninstall: true, install: donebutton) {
section { href url:redirectUrl, style:"embedded", required:true, title:"Jawbone UP", state: hast ,description:description } section { href url:redirectUrl, style:"embedded", required:true, title:"Jawbone UP", state: hast ,description:description }
} }
} else { } else {
description = "Jawbone Credentials Already Entered." description = "Jawbone Credentials Already Entered."
return dynamicPage(name: "Credentials", title: "Jawbone UP", uninstall: true, install:true) { return dynamicPage(name: "Credentials", title: "Jawbone UP", uninstall: true, install:true) {
section { href url: buildRedirectUrl("receivedToken"), style:"embedded", state: "complete", title:"Jawbone UP", description:description } section { href url: buildRedirectUrl("receivedToken"), style:"embedded", state: "complete", title:"Jawbone UP", description:description }
} }
@@ -100,21 +96,18 @@ def authPage() {
def oauthInitUrl() { def oauthInitUrl() {
log.debug "oauthInitUrl" log.debug "oauthInitUrl"
def stcid = getSmartThingsClientId()
state.oauthInitState = UUID.randomUUID().toString() state.oauthInitState = UUID.randomUUID().toString()
def oauthParams = [ response_type: "code", client_id: stcid, scope: "move_read sleep_read", redirect_uri: "${serverUrl}/oauth/callback" ] def oauthParams = [ response_type: "code", client_id: appSettings.clientId, scope: "move_read sleep_read", redirect_uri: "${serverUrl}/oauth/callback" ]
redirect(location: "https://jawbone.com/auth/oauth2/auth?${toQueryString(oauthParams)}") redirect(location: "https://jawbone.com/auth/oauth2/auth?${toQueryString(oauthParams)}")
} }
def receiveToken(redirectUrl = null) { def receiveToken(redirectUrl = null) {
log.debug "receiveToken" log.debug "receiveToken"
def stcid = getSmartThingsClientId() def oauthParams = [ client_id: appSettings.clientId, client_secret: appSettings.clientSecret, grant_type: "authorization_code", code: params.code ]
def oauthClientSecret = getSmartThingsClientSecret()
def oauthParams = [ client_id: stcid, client_secret: oauthClientSecret, grant_type: "authorization_code", code: params.code ]
def params = [ def params = [
uri: "https://jawbone.com/auth/oauth2/token?${toQueryString(oauthParams)}", uri: "https://jawbone.com/auth/oauth2/token?${toQueryString(oauthParams)}",
] ]
httpGet(params) { response -> httpGet(params) { response ->
log.debug "${response.data}" log.debug "${response.data}"
log.debug "Setting access token to ${response.data.access_token}, refresh token to ${response.data.refresh_token}" log.debug "Setting access token to ${response.data.access_token}, refresh token to ${response.data.refresh_token}"
state.JawboneAccessToken = response.data.access_token state.JawboneAccessToken = response.data.access_token
@@ -156,7 +149,7 @@ def connectionStatus(message, redirectUrl = null) {
<meta http-equiv="refresh" content="3; url=${redirectUrl}" /> <meta http-equiv="refresh" content="3; url=${redirectUrl}" />
""" """
} }
def html = """ def html = """
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -235,8 +228,8 @@ String toQueryString(Map m) {
def validateCurrentToken() { def validateCurrentToken() {
log.debug "validateCurrentToken" log.debug "validateCurrentToken"
def url = "https://jawbone.com/nudge/api/v.1.1/users/@me/refreshToken" def url = "https://jawbone.com/nudge/api/v.1.1/users/@me/refreshToken"
def requestBody = "secret=${getSmartThingsClientSecret()}" def requestBody = "secret=${appSettings.clientSecret}"
try { try {
httpPost(uri: url, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ], body: requestBody) {response -> httpPost(uri: url, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ], body: requestBody) {response ->
if (response.status == 200) { if (response.status == 200) {
@@ -249,9 +242,7 @@ def validateCurrentToken() {
if (e.statusCode == 401) { // token is expired if (e.statusCode == 401) { // token is expired
log.debug "Access token is expired" log.debug "Access token is expired"
if (state.refreshToken) { // if we have this we are okay if (state.refreshToken) { // if we have this we are okay
def stcid = getSmartThingsClientId() def oauthParams = [client_id: appSettings.clientId, client_secret: appSettings.clientSecret, grant_type: "refresh_token", refresh_token: state.refreshToken]
def oauthClientSecret = getSmartThingsClientSecret()
def oauthParams = [client_id: stcid, client_secret: oauthClientSecret, grant_type: "refresh_token", refresh_token: state.refreshToken]
def tokenUrl = "https://jawbone.com/auth/oauth2/token?${toQueryString(oauthParams)}" def tokenUrl = "https://jawbone.com/auth/oauth2/token?${toQueryString(oauthParams)}"
def params = [ def params = [
uri: tokenUrl uri: tokenUrl
@@ -280,10 +271,11 @@ def validateCurrentToken() {
} }
def initialize() { def initialize() {
log.debug "Callback URL - Webhook" log.debug "Callback URL - Webhook"
def hookUrl = buildActionUrl("hookCallback") def localServerUrl = getApiServerUrl()
def webhook = "https://jawbone.com/nudge/api/v.1.1/users/@me/pubsub?webhook=$hookUrl" def hookUrl = "${localServerUrl}/api/token/${state.accessToken}/smartapps/installations/${app.id}/hookCallback"
httpPost(uri: webhook, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) def webhook = "https://jawbone.com/nudge/api/v.1.1/users/@me/pubsub?webhook=$hookUrl"
httpPost(uri: webhook, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ])
} }
def setup() { def setup() {
@@ -292,16 +284,16 @@ def setup() {
if (state.JawboneAccessToken) { if (state.JawboneAccessToken) {
def urlmember = "https://jawbone.com/nudge/api/users/@me/" def urlmember = "https://jawbone.com/nudge/api/users/@me/"
def member = null def member = null
httpGet(uri: urlmember, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlmember, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
member = response.data.data member = response.data.data
} }
if (member) { if (member) {
state.member = member state.member = member
def externalId = "${app.id}.${member.xid}" def externalId = "${app.id}.${member.xid}"
// find the appropriate child device based on my app id and the device network id // find the appropriate child device based on my app id and the device network id
def deviceWrapper = getChildDevice("${externalId}") def deviceWrapper = getChildDevice("${externalId}")
// invoke the generatePresenceEvent method on the child device // invoke the generatePresenceEvent method on the child device
@@ -320,8 +312,7 @@ def setup() {
} }
def installed() { def installed() {
enableCallback()
if (!state.accessToken) { if (!state.accessToken) {
log.debug "About to create access token" log.debug "About to create access token"
createAccessToken() createAccessToken()
@@ -333,8 +324,7 @@ def installed() {
} }
def updated() { def updated() {
enableCallback()
if (!state.accessToken) { if (!state.accessToken) {
log.debug "About to create access token" log.debug "About to create access token"
createAccessToken() createAccessToken()
@@ -358,29 +348,29 @@ def uninstalled() {
} }
def pollChild(childDevice) { def pollChild(childDevice) {
def member = state.member def member = state.member
generatePollingEvents (member, childDevice) generatePollingEvents (member, childDevice)
} }
def generatePollingEvents (member, childDevice) { def generatePollingEvents (member, childDevice) {
// lets figure out if the member is currently "home" (At the place) // lets figure out if the member is currently "home" (At the place)
def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals" def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals"
def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves" def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves"
def urlsleeps = "https://jawbone.com/nudge/api/users/@me/sleeps" def urlsleeps = "https://jawbone.com/nudge/api/users/@me/sleeps"
def goals = null def goals = null
def moves = null def moves = null
def sleeps = null def sleeps = null
httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
goals = response.data.data goals = response.data.data
} }
httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
moves = response.data.data.items[0] moves = response.data.data.items[0]
} }
try { // we are going to just ignore any errors try { // we are going to just ignore any errors
log.debug "Member = ${member.first}" log.debug "Member = ${member.first}"
log.debug "Moves Goal = ${goals.move_steps} Steps" log.debug "Moves Goal = ${goals.move_steps} Steps"
log.debug "Moves = ${moves.details.steps} Steps" log.debug "Moves = ${moves.details.steps} Steps"
childDevice?.sendEvent(name:"steps", value: moves.details.steps) childDevice?.sendEvent(name:"steps", value: moves.details.steps)
childDevice?.sendEvent(name:"goal", value: goals.move_steps) childDevice?.sendEvent(name:"goal", value: goals.move_steps)
@@ -388,29 +378,29 @@ def generatePollingEvents (member, childDevice) {
} }
catch (e) { catch (e) {
// eat it // eat it
} }
} }
def generateInitialEvent (member, childDevice) { def generateInitialEvent (member, childDevice) {
// lets figure out if the member is currently "home" (At the place) // lets figure out if the member is currently "home" (At the place)
def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals" def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals"
def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves" def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves"
def urlsleeps = "https://jawbone.com/nudge/api/users/@me/sleeps" def urlsleeps = "https://jawbone.com/nudge/api/users/@me/sleeps"
def goals = null def goals = null
def moves = null def moves = null
def sleeps = null def sleeps = null
httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
goals = response.data.data goals = response.data.data
} }
httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
moves = response.data.data.items[0] moves = response.data.data.items[0]
} }
try { // we are going to just ignore any errors try { // we are going to just ignore any errors
log.debug "Member = ${member.first}" log.debug "Member = ${member.first}"
log.debug "Moves Goal = ${goals.move_steps} Steps" log.debug "Moves Goal = ${goals.move_steps} Steps"
log.debug "Moves = ${moves.details.steps} Steps" log.debug "Moves = ${moves.details.steps} Steps"
log.debug "Sleeping state = false" log.debug "Sleeping state = false"
childDevice?.generateSleepingEvent(false) childDevice?.generateSleepingEvent(false)
childDevice?.sendEvent(name:"steps", value: moves.details.steps) childDevice?.sendEvent(name:"steps", value: moves.details.steps)
childDevice?.sendEvent(name:"goal", value: goals.move_steps) childDevice?.sendEvent(name:"goal", value: goals.move_steps)
@@ -418,27 +408,27 @@ def generateInitialEvent (member, childDevice) {
} }
catch (e) { catch (e) {
// eat it // eat it
} }
} }
def setColor (steps,goal,childDevice) { def setColor (steps,goal,childDevice) {
def result = steps * 100 / goal def result = steps * 100 / goal
if (result < 25) if (result < 25)
childDevice?.sendEvent(name:"steps", value: "steps", label: steps) childDevice?.sendEvent(name:"steps", value: "steps", label: steps)
else if ((result >= 25) && (result < 50)) else if ((result >= 25) && (result < 50))
childDevice?.sendEvent(name:"steps", value: "steps1", label: steps) childDevice?.sendEvent(name:"steps", value: "steps1", label: steps)
else if ((result >= 50) && (result < 75)) else if ((result >= 50) && (result < 75))
childDevice?.sendEvent(name:"steps", value: "steps1", label: steps) childDevice?.sendEvent(name:"steps", value: "steps1", label: steps)
else if (result >= 75) else if (result >= 75)
childDevice?.sendEvent(name:"steps", value: "stepsgoal", label: steps) childDevice?.sendEvent(name:"steps", value: "stepsgoal", label: steps)
} }
def hookEventHandler() { def hookEventHandler() {
// log.debug "In hookEventHandler method." // log.debug "In hookEventHandler method."
log.debug "request = ${request}" log.debug "request = ${request}"
def json = request.JSON def json = request.JSON
// get some stuff we need // get some stuff we need
def userId = json.events.user_xid[0] def userId = json.events.user_xid[0]
def json_type = json.events.type[0] def json_type = json.events.type[0]
@@ -447,39 +437,39 @@ def hookEventHandler() {
//log.debug json //log.debug json
log.debug "Userid = ${userId}" log.debug "Userid = ${userId}"
log.debug "Notification Type: " + json_type log.debug "Notification Type: " + json_type
log.debug "Notification Action: " + json_action log.debug "Notification Action: " + json_action
// find the appropriate child device based on my app id and the device network id // find the appropriate child device based on my app id and the device network id
def externalId = "${app.id}.${userId}" def externalId = "${app.id}.${userId}"
def childDevice = getChildDevice("${externalId}") def childDevice = getChildDevice("${externalId}")
if (childDevice) { if (childDevice) {
switch (json_action) { switch (json_action) {
case "enter_sleep_mode": case "enter_sleep_mode":
childDevice?.generateSleepingEvent(true) childDevice?.generateSleepingEvent(true)
break break
case "exit_sleep_mode": case "exit_sleep_mode":
childDevice?.generateSleepingEvent(false) childDevice?.generateSleepingEvent(false)
break break
case "creation": case "creation":
childDevice?.sendEvent(name:"steps", value: 0) childDevice?.sendEvent(name:"steps", value: 0)
break break
case "updation": case "updation":
def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals" def urlgoals = "https://jawbone.com/nudge/api/users/@me/goals"
def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves" def urlmoves = "https://jawbone.com/nudge/api/users/@me/moves"
def goals = null def goals = null
def moves = null def moves = null
httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlgoals, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
goals = response.data.data goals = response.data.data
} }
httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response -> httpGet(uri: urlmoves, headers: ["Authorization": "Bearer ${state.JawboneAccessToken}" ]) {response ->
moves = response.data.data.items[0] moves = response.data.data.items[0]
} }
log.debug "Goal = ${goals.move_steps} Steps" log.debug "Goal = ${goals.move_steps} Steps"
log.debug "Steps = ${moves.details.steps} Steps" log.debug "Steps = ${moves.details.steps} Steps"
childDevice?.sendEvent(name:"steps", value: moves.details.steps) childDevice?.sendEvent(name:"steps", value: moves.details.steps)
childDevice?.sendEvent(name:"goal", value: goals.move_steps) childDevice?.sendEvent(name:"goal", value: goals.move_steps)
//setColor(moves.details.steps,goals.move_steps,childDevice) //setColor(moves.details.steps,goals.move_steps,childDevice)
break break
case "deletion": case "deletion":
app.delete() app.delete()