]> git.basschouten.com Git - openhab-addons.git/blob
79371d2d46dbde020e6ae77bae1a5b397578ffad
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ecobee.internal.api;
14
15 import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.*;
16
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20
21 import org.apache.commons.lang.StringUtils;
22 import org.apache.commons.lang.exception.ExceptionUtils;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.eclipse.jetty.client.HttpResponseException;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.client.api.Request;
29 import org.eclipse.jetty.http.HttpStatus;
30 import org.openhab.binding.ecobee.internal.dto.oauth.AuthorizeResponseDTO;
31 import org.openhab.binding.ecobee.internal.dto.oauth.TokenResponseDTO;
32 import org.openhab.binding.ecobee.internal.handler.EcobeeAccountBridgeHandler;
33 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
34 import org.openhab.core.auth.client.oauth2.OAuthClientService;
35 import org.openhab.core.auth.client.oauth2.OAuthException;
36 import org.openhab.core.thing.ThingStatus;
37 import org.openhab.core.thing.ThingStatusDetail;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.gson.JsonSyntaxException;
42
43 /**
44  * The {@link EcobeeAuth} performs the initial OAuth authorization
45  * with the Ecobee authorization servers. Once this process is complete, the
46  * AccessTokenResponse will be imported into the OHC OAuth Client Service. At
47  * that point, the OHC OAuth service will be responsible for refreshing tokens.
48  *
49  * @author Mark Hilbush - Initial contribution
50  */
51 @NonNullByDefault
52 public class EcobeeAuth {
53
54     private final Logger logger = LoggerFactory.getLogger(EcobeeAuth.class);
55
56     private final EcobeeAccountBridgeHandler bridgeHandler;
57     private final String apiKey;
58     private final int apiTimeout;
59     private final OAuthClientService oAuthClientService;
60     private final HttpClient httpClient;
61
62     private EcobeeAuthState state;
63
64     private @Nullable AuthorizeResponseDTO authResponse;
65
66     private long pinExpirationTime;
67
68     /**
69      * The authorization code needed to make the first-time request
70      * of the refresh and access tokens. Obtained from the call to {@code authorize()}.
71      */
72     private @Nullable String code;
73
74     public EcobeeAuth(EcobeeAccountBridgeHandler bridgeHandler, String apiKey, int apiTimeout,
75             OAuthClientService oAuthClientService, HttpClient httpClient) {
76         this.apiKey = apiKey;
77         this.apiTimeout = apiTimeout;
78         this.oAuthClientService = oAuthClientService;
79         this.httpClient = httpClient;
80         this.bridgeHandler = bridgeHandler;
81         pinExpirationTime = 0;
82         state = EcobeeAuthState.NEED_PIN;
83     }
84
85     public void setState(EcobeeAuthState newState) {
86         if (newState != state) {
87             logger.debug("EcobeeAuth: Change state from {} to {}", state, newState);
88             state = newState;
89         }
90     }
91
92     public boolean isComplete() {
93         return state == EcobeeAuthState.COMPLETE;
94     }
95
96     public EcobeeAuthState doAuthorization() throws EcobeeAuthException {
97         switch (state) {
98             case NEED_PIN:
99                 authorize();
100                 break;
101             case NEED_TOKEN:
102                 getTokens();
103                 break;
104             case COMPLETE:
105                 bridgeHandler.updateBridgeStatus(ThingStatus.ONLINE);
106                 break;
107         }
108         return state;
109     }
110
111     /**
112      * Call the Ecobee authorize endpoint to get the authorization code and PIN
113      * that will be used a) validate the application in the the Ecobee user web portal,
114      * and b) make the first time request for the access and refresh tokens.
115      * Warnings are suppressed to avoid the Gson.fromJson warnings.
116      */
117     @SuppressWarnings({ "null", "unused" })
118     private void authorize() throws EcobeeAuthException {
119         logger.debug("EcobeeAuth: State is {}: Executing step: 'authorize'", state);
120         StringBuilder url = new StringBuilder(ECOBEE_AUTHORIZE_URL);
121         url.append("?response_type=ecobeePin");
122         url.append("&client_id=").append(apiKey);
123         url.append("&scope=").append(ECOBEE_SCOPE);
124
125         logger.trace("EcobeeAuth: Getting authorize URL={}", url);
126         String response = executeUrl("GET", url.toString());
127         logger.trace("EcobeeAuth: Auth response: {}", response);
128
129         try {
130             authResponse = EcobeeApi.getGson().fromJson(response, AuthorizeResponseDTO.class);
131             if (authResponse == null) {
132                 logger.debug("EcobeeAuth: Got null authorize response from Ecobee API");
133                 setState(EcobeeAuthState.NEED_PIN);
134             } else {
135                 if (StringUtils.isNotEmpty(authResponse.error)) {
136                     throw new EcobeeAuthException(authResponse.error + ": " + authResponse.errorDescription);
137                 }
138                 code = authResponse.code;
139                 writeLogMessage(authResponse.pin, authResponse.expiresIn);
140                 setPinExpirationTime(authResponse.expiresIn.longValue());
141                 updateBridgeStatus();
142                 setState(EcobeeAuthState.NEED_TOKEN);
143             }
144         } catch (JsonSyntaxException e) {
145             logger.info("EcobeeAuth: Exception while parsing authorize response: {}", e.getMessage());
146             setState(EcobeeAuthState.NEED_PIN);
147         }
148     }
149
150     /**
151      * Call the Ecobee token endpoint to get the access and refresh tokens. Once successfully retrieved,
152      * the access and refresh tokens will be injected into the OHC OAuth service.
153      * Warnings are suppressed to avoid the Gson.fromJson warnings.
154      */
155     @SuppressWarnings({ "null", "unused" })
156     private void getTokens() throws EcobeeAuthException {
157         logger.debug("EcobeeAuth: State is {}: Executing step: 'getToken'", state);
158         StringBuilder url = new StringBuilder(ECOBEE_TOKEN_URL);
159         url.append("?grant_type=ecobeePin");
160         url.append("&code=").append(code);
161         url.append("&client_id=").append(apiKey);
162
163         logger.trace("EcobeeAuth: Posting token URL={}", url);
164         String response = executeUrl("POST", url.toString());
165         logger.trace("EcobeeAuth: Got a valid token response: {}", response);
166
167         TokenResponseDTO tokenResponse = EcobeeApi.getGson().fromJson(response, TokenResponseDTO.class);
168         if (tokenResponse == null) {
169             logger.debug("EcobeeAuth: Got null token response from Ecobee API");
170             updateBridgeStatus();
171             setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
172             return;
173         }
174         if (StringUtils.isNotEmpty(tokenResponse.error)) {
175             throw new EcobeeAuthException(tokenResponse.error + ": " + tokenResponse.errorDescription);
176         }
177         AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
178         accessTokenResponse.setRefreshToken(tokenResponse.refreshToken);
179         accessTokenResponse.setAccessToken(tokenResponse.accessToken);
180         accessTokenResponse.setScope(tokenResponse.scope);
181         accessTokenResponse.setTokenType(tokenResponse.tokenType);
182         accessTokenResponse.setExpiresIn(tokenResponse.expiresIn);
183         try {
184             logger.debug("EcobeeAuth: Importing AccessTokenResponse into oAuthClientService!!!");
185             oAuthClientService.importAccessTokenResponse(accessTokenResponse);
186             bridgeHandler.updateBridgeStatus(ThingStatus.ONLINE);
187             setState(EcobeeAuthState.COMPLETE);
188             return;
189         } catch (OAuthException e) {
190             logger.info("EcobeeAuth: Got OAuthException", e);
191             // No other processing needed here
192         }
193         updateBridgeStatus();
194         setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
195     }
196
197     private void writeLogMessage(String pin, Integer expiresIn) {
198         logger.info("#################################################################");
199         logger.info("# Ecobee: U S E R   I N T E R A C T I O N   R E Q U I R E D !!");
200         logger.info("# Go to the Ecobee web portal, then:");
201         logger.info("# Enter PIN '{}' in My Apps within {} minutes.", pin, expiresIn);
202         logger.info("# NOTE: All API attempts will fail in the meantime.");
203         logger.info("#################################################################");
204     }
205
206     private void updateBridgeStatus() {
207         AuthorizeResponseDTO response = authResponse;
208         if (response != null) {
209             bridgeHandler.updateBridgeStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
210                     String.format("Enter PIN '%s' in MyApps. PIN expires in %d minutes", response.pin,
211                             getMinutesUntilPinExpiration()));
212         }
213     }
214
215     private void setPinExpirationTime(long expiresIn) {
216         pinExpirationTime = expiresIn + TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
217     }
218
219     private long getMinutesUntilPinExpiration() {
220         return pinExpirationTime - TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
221     }
222
223     private boolean isPinExpired() {
224         return getMinutesUntilPinExpiration() <= 0;
225     }
226
227     private @Nullable String executeUrl(String method, String url) {
228         Request request = httpClient.newRequest(url);
229         request.timeout(apiTimeout, TimeUnit.MILLISECONDS);
230         request.method(method);
231         EcobeeApi.HTTP_HEADERS.forEach((k, v) -> request.header((String) k, (String) v));
232
233         try {
234             ContentResponse contentResponse = request.send();
235             switch (contentResponse.getStatus()) {
236                 case HttpStatus.OK_200:
237                     return contentResponse.getContentAsString();
238                 case HttpStatus.BAD_REQUEST_400:
239                     logger.debug("BAD REQUEST(400) response received: {}", contentResponse.getContentAsString());
240                     return contentResponse.getContentAsString();
241                 case HttpStatus.UNAUTHORIZED_401:
242                     logger.debug("UNAUTHORIZED(401) response received: {}", contentResponse.getContentAsString());
243                     return contentResponse.getContentAsString();
244                 case HttpStatus.NO_CONTENT_204:
245                     logger.debug("HTTP response 204: No content. Check configuration");
246                     break;
247                 default:
248                     logger.debug("HTTP {} failed: {}, {}", method, contentResponse.getStatus(),
249                             contentResponse.getReason());
250                     break;
251             }
252         } catch (TimeoutException e) {
253             logger.debug("TimeoutException: Call to Ecobee API timed out");
254         } catch (ExecutionException e) {
255             if (ExceptionUtils.getRootCause(e) instanceof HttpResponseException) {
256                 logger.info("Awaiting entry of PIN in Ecobee portal. Expires in {} minutes",
257                         getMinutesUntilPinExpiration());
258             } else {
259                 logger.debug("ExecutionException on call to Ecobee authorization API", e);
260             }
261         } catch (InterruptedException e) {
262             logger.debug("InterruptedException on call to Ecobee authorization API: {}", e.getMessage());
263         }
264         return null;
265     }
266 }