]> git.basschouten.com Git - openhab-addons.git/blob
e3aa1853277e266b53dbcb698cd2352f0e614beb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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         authResponse = null;
84     }
85
86     public void setState(EcobeeAuthState newState) {
87         if (newState != state) {
88             logger.debug("EcobeeAuth: Change state from {} to {}", state, newState);
89             state = newState;
90         }
91     }
92
93     public boolean isComplete() {
94         return state == EcobeeAuthState.COMPLETE;
95     }
96
97     public EcobeeAuthState doAuthorization() throws EcobeeAuthException {
98         switch (state) {
99             case NEED_PIN:
100                 authorize();
101                 break;
102             case NEED_TOKEN:
103                 getTokens();
104                 break;
105             case COMPLETE:
106                 bridgeHandler.updateBridgeStatus(ThingStatus.ONLINE);
107                 break;
108         }
109         return state;
110     }
111
112     /**
113      * Call the Ecobee authorize endpoint to get the authorization code and PIN
114      * that will be used a) validate the application in the the Ecobee user web portal,
115      * and b) make the first time request for the access and refresh tokens.
116      * Warnings are suppressed to avoid the Gson.fromJson warnings.
117      */
118     @SuppressWarnings({ "null", "unused" })
119     private void authorize() throws EcobeeAuthException {
120         logger.debug("EcobeeAuth: State is {}: Executing step: 'authorize'", state);
121         StringBuilder url = new StringBuilder(ECOBEE_AUTHORIZE_URL);
122         url.append("?response_type=ecobeePin");
123         url.append("&client_id=").append(apiKey);
124         url.append("&scope=").append(ECOBEE_SCOPE);
125
126         logger.trace("EcobeeAuth: Getting authorize URL={}", url);
127         String response = executeUrl("GET", url.toString());
128         logger.trace("EcobeeAuth: Auth response: {}", response);
129
130         try {
131             authResponse = EcobeeApi.getGson().fromJson(response, AuthorizeResponseDTO.class);
132             if (authResponse == null) {
133                 logger.debug("EcobeeAuth: Got null authorize response from Ecobee API");
134                 setState(EcobeeAuthState.NEED_PIN);
135             } else {
136                 if (StringUtils.isNotEmpty(authResponse.error)) {
137                     throw new EcobeeAuthException(authResponse.error + ": " + authResponse.errorDescription);
138                 }
139                 code = authResponse.code;
140                 writeLogMessage(authResponse.pin, authResponse.expiresIn);
141                 setPinExpirationTime(authResponse.expiresIn.longValue());
142                 updateBridgeStatus();
143                 setState(EcobeeAuthState.NEED_TOKEN);
144             }
145         } catch (JsonSyntaxException e) {
146             logger.info("EcobeeAuth: Exception while parsing authorize response: {}", e.getMessage());
147             setState(EcobeeAuthState.NEED_PIN);
148         }
149     }
150
151     /**
152      * Call the Ecobee token endpoint to get the access and refresh tokens. Once successfully retrieved,
153      * the access and refresh tokens will be injected into the OHC OAuth service.
154      * Warnings are suppressed to avoid the Gson.fromJson warnings.
155      */
156     @SuppressWarnings({ "null", "unused" })
157     private void getTokens() throws EcobeeAuthException {
158         logger.debug("EcobeeAuth: State is {}: Executing step: 'getToken'", state);
159         StringBuilder url = new StringBuilder(ECOBEE_TOKEN_URL);
160         url.append("?grant_type=ecobeePin");
161         url.append("&code=").append(code);
162         url.append("&client_id=").append(apiKey);
163
164         logger.trace("EcobeeAuth: Posting token URL={}", url);
165         String response = executeUrl("POST", url.toString());
166         logger.trace("EcobeeAuth: Got a valid token response: {}", response);
167
168         TokenResponseDTO tokenResponse = EcobeeApi.getGson().fromJson(response, TokenResponseDTO.class);
169         if (tokenResponse == null) {
170             logger.debug("EcobeeAuth: Got null token response from Ecobee API");
171             updateBridgeStatus();
172             setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
173             return;
174         }
175         if (StringUtils.isNotEmpty(tokenResponse.error)) {
176             throw new EcobeeAuthException(tokenResponse.error + ": " + tokenResponse.errorDescription);
177         }
178         AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
179         accessTokenResponse.setRefreshToken(tokenResponse.refreshToken);
180         accessTokenResponse.setAccessToken(tokenResponse.accessToken);
181         accessTokenResponse.setScope(tokenResponse.scope);
182         accessTokenResponse.setTokenType(tokenResponse.tokenType);
183         accessTokenResponse.setExpiresIn(tokenResponse.expiresIn);
184         try {
185             logger.debug("EcobeeAuth: Importing AccessTokenResponse into oAuthClientService!!!");
186             oAuthClientService.importAccessTokenResponse(accessTokenResponse);
187             bridgeHandler.updateBridgeStatus(ThingStatus.ONLINE);
188             setState(EcobeeAuthState.COMPLETE);
189             return;
190         } catch (OAuthException e) {
191             logger.info("EcobeeAuth: Got OAuthException", e);
192             // No other processing needed here
193         }
194         updateBridgeStatus();
195         setState(isPinExpired() ? EcobeeAuthState.NEED_PIN : EcobeeAuthState.NEED_TOKEN);
196     }
197
198     private void writeLogMessage(String pin, Integer expiresIn) {
199         logger.info("#################################################################");
200         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 !!");
201         logger.info("# Go to the Ecobee web portal, then:");
202         logger.info("# Enter PIN '{}' in My Apps within {} minutes.", pin, expiresIn);
203         logger.info("# NOTE: All API attempts will fail in the meantime.");
204         logger.info("#################################################################");
205     }
206
207     private void updateBridgeStatus() {
208         AuthorizeResponseDTO response = authResponse;
209         if (response != null) {
210             bridgeHandler.updateBridgeStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
211                     String.format("Enter PIN '%s' in MyApps. PIN expires in %d minutes", response.pin,
212                             getMinutesUntilPinExpiration()));
213         }
214     }
215
216     private void setPinExpirationTime(long expiresIn) {
217         pinExpirationTime = expiresIn + TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
218     }
219
220     private long getMinutesUntilPinExpiration() {
221         return pinExpirationTime - TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
222     }
223
224     private boolean isPinExpired() {
225         return getMinutesUntilPinExpiration() <= 0;
226     }
227
228     private @Nullable String executeUrl(String method, String url) {
229         Request request = httpClient.newRequest(url);
230         request.timeout(apiTimeout, TimeUnit.MILLISECONDS);
231         request.method(method);
232         EcobeeApi.HTTP_HEADERS.forEach((k, v) -> request.header((String) k, (String) v));
233
234         try {
235             ContentResponse contentResponse = request.send();
236             switch (contentResponse.getStatus()) {
237                 case HttpStatus.OK_200:
238                     return contentResponse.getContentAsString();
239                 case HttpStatus.BAD_REQUEST_400:
240                     logger.debug("BAD REQUEST(400) response received: {}", contentResponse.getContentAsString());
241                     return contentResponse.getContentAsString();
242                 case HttpStatus.UNAUTHORIZED_401:
243                     logger.debug("UNAUTHORIZED(401) response received: {}", contentResponse.getContentAsString());
244                     return contentResponse.getContentAsString();
245                 case HttpStatus.NO_CONTENT_204:
246                     logger.debug("HTTP response 204: No content. Check configuration");
247                     break;
248                 default:
249                     logger.debug("HTTP {} failed: {}, {}", method, contentResponse.getStatus(),
250                             contentResponse.getReason());
251                     break;
252             }
253         } catch (TimeoutException e) {
254             logger.debug("TimeoutException: Call to Ecobee API timed out");
255         } catch (ExecutionException e) {
256             if (ExceptionUtils.getRootCause(e) instanceof HttpResponseException) {
257                 logger.info("Awaiting entry of PIN in Ecobee portal. Expires in {} minutes",
258                         getMinutesUntilPinExpiration());
259             } else {
260                 logger.debug("ExecutionException on call to Ecobee authorization API", e);
261             }
262         } catch (InterruptedException e) {
263             logger.debug("InterruptedException on call to Ecobee authorization API: {}", e.getMessage());
264         }
265         return null;
266     }
267 }