]> git.basschouten.com Git - openhab-addons.git/blob
f5d63aa483753c9e73cc954298cb05948a839418
[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.myq.internal.handler;
14
15 import static org.openhab.binding.myq.internal.MyQBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.CookieStore;
19 import java.net.HttpCookie;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.nio.charset.StandardCharsets;
23 import java.security.MessageDigest;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.SecureRandom;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Base64;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Random;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.stream.Collectors;
40
41 import org.eclipse.jdt.annotation.NonNullByDefault;
42 import org.eclipse.jdt.annotation.Nullable;
43 import org.eclipse.jetty.client.HttpClient;
44 import org.eclipse.jetty.client.HttpContentResponse;
45 import org.eclipse.jetty.client.api.ContentProvider;
46 import org.eclipse.jetty.client.api.ContentResponse;
47 import org.eclipse.jetty.client.api.Request;
48 import org.eclipse.jetty.client.api.Response;
49 import org.eclipse.jetty.client.api.Result;
50 import org.eclipse.jetty.client.util.BufferingResponseListener;
51 import org.eclipse.jetty.client.util.FormContentProvider;
52 import org.eclipse.jetty.http.HttpMethod;
53 import org.eclipse.jetty.http.HttpStatus;
54 import org.eclipse.jetty.util.Fields;
55 import org.jsoup.Jsoup;
56 import org.jsoup.nodes.Document;
57 import org.jsoup.nodes.Element;
58 import org.openhab.binding.myq.internal.MyQDiscoveryService;
59 import org.openhab.binding.myq.internal.config.MyQAccountConfiguration;
60 import org.openhab.binding.myq.internal.dto.AccountDTO;
61 import org.openhab.binding.myq.internal.dto.AccountsDTO;
62 import org.openhab.binding.myq.internal.dto.DeviceDTO;
63 import org.openhab.binding.myq.internal.dto.DevicesDTO;
64 import org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener;
65 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
66 import org.openhab.core.auth.client.oauth2.OAuthClientService;
67 import org.openhab.core.auth.client.oauth2.OAuthException;
68 import org.openhab.core.auth.client.oauth2.OAuthFactory;
69 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
70 import org.openhab.core.thing.Bridge;
71 import org.openhab.core.thing.ChannelUID;
72 import org.openhab.core.thing.Thing;
73 import org.openhab.core.thing.ThingStatus;
74 import org.openhab.core.thing.ThingStatusDetail;
75 import org.openhab.core.thing.ThingTypeUID;
76 import org.openhab.core.thing.binding.BaseBridgeHandler;
77 import org.openhab.core.thing.binding.ThingHandler;
78 import org.openhab.core.thing.binding.ThingHandlerService;
79 import org.openhab.core.types.Command;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82
83 import com.google.gson.FieldNamingPolicy;
84 import com.google.gson.Gson;
85 import com.google.gson.GsonBuilder;
86 import com.google.gson.JsonSyntaxException;
87
88 /**
89  * The {@link MyQAccountHandler} is responsible for communicating with the MyQ API based on an account.
90  *
91  * @author Dan Cunningham - Initial contribution
92  */
93 @NonNullByDefault
94 public class MyQAccountHandler extends BaseBridgeHandler implements AccessTokenRefreshListener {
95     /*
96      * MyQ oAuth relate fields
97      */
98     private static final String CLIENT_SECRET = "VUQ0RFhuS3lQV3EyNUJTdw==";
99     private static final String CLIENT_ID = "IOS_CGI_MYQ";
100     private static final String REDIRECT_URI = "com.myqops://ios";
101     private static final String SCOPE = "MyQ_Residential offline_access";
102     /*
103      * MyQ authentication API endpoints
104      */
105     private static final String LOGIN_BASE_URL = "https://partner-identity.myq-cloud.com";
106     private static final String LOGIN_AUTHORIZE_URL = LOGIN_BASE_URL + "/connect/authorize";
107     private static final String LOGIN_TOKEN_URL = LOGIN_BASE_URL + "/connect/token";
108     // this should never happen, but lets be safe and give up after so many redirects
109     private static final int LOGIN_MAX_REDIRECTS = 30;
110     /*
111      * MyQ device and account API endpoints
112      */
113     private static final String ACCOUNTS_URL = "https://accounts.myq-cloud.com/api/v6.0/accounts";
114     private static final String DEVICES_URL = "https://devices.myq-cloud.com/api/v5.2/Accounts/%s/Devices";
115     private static final String CMD_LAMP_URL = "https://account-devices-lamp.myq-cloud.com/api/v5.2/Accounts/%s/lamps/%s/%s";
116     private static final String CMD_DOOR_URL = "https://account-devices-gdo.myq-cloud.com/api/v5.2/Accounts/%s/door_openers/%s/%s";
117
118     private static final Integer RAPID_REFRESH_SECONDS = 5;
119     private final Logger logger = LoggerFactory.getLogger(MyQAccountHandler.class);
120     private final Gson gsonLowerCase = new GsonBuilder()
121             .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
122     private final OAuthFactory oAuthFactory;
123     private @Nullable Future<?> normalPollFuture;
124     private @Nullable Future<?> rapidPollFuture;
125     private @Nullable AccountsDTO accounts;
126
127     private List<DeviceDTO> devicesCache = new ArrayList<DeviceDTO>();
128     private @Nullable OAuthClientService oAuthService;
129     private Integer normalRefreshSeconds = 60;
130     private HttpClient httpClient;
131     private String username = "";
132     private String password = "";
133     private String userAgent = "";
134     // force login, even if we have a token
135     private boolean needsLogin = false;
136
137     public MyQAccountHandler(Bridge bridge, HttpClient httpClient, final OAuthFactory oAuthFactory) {
138         super(bridge);
139         this.httpClient = httpClient;
140         this.oAuthFactory = oAuthFactory;
141     }
142
143     @Override
144     public void handleCommand(ChannelUID channelUID, Command command) {
145     }
146
147     @Override
148     public void initialize() {
149         MyQAccountConfiguration config = getConfigAs(MyQAccountConfiguration.class);
150         normalRefreshSeconds = config.refreshInterval;
151         username = config.username;
152         password = config.password;
153         // MyQ can get picky about blocking user agents apparently
154         userAgent = MyQAccountHandler.randomString(20);
155         needsLogin = true;
156         updateStatus(ThingStatus.UNKNOWN);
157         restartPolls(false);
158     }
159
160     @Override
161     public void dispose() {
162         stopPolls();
163         OAuthClientService oAuthService = this.oAuthService;
164         if (oAuthService != null) {
165             oAuthService.close();
166         }
167     }
168
169     @Override
170     public Collection<Class<? extends ThingHandlerService>> getServices() {
171         return Collections.singleton(MyQDiscoveryService.class);
172     }
173
174     @Override
175     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
176         List<DeviceDTO> localDeviceCaches = devicesCache;
177         if (childHandler instanceof MyQDeviceHandler) {
178             MyQDeviceHandler handler = (MyQDeviceHandler) childHandler;
179             localDeviceCaches.stream()
180                     .filter(d -> ((MyQDeviceHandler) childHandler).getSerialNumber().equalsIgnoreCase(d.serialNumber))
181                     .findFirst().ifPresent(handler::handleDeviceUpdate);
182         }
183     }
184
185     @Override
186     public void onAccessTokenResponse(AccessTokenResponse tokenResponse) {
187         logger.debug("Auth Token Refreshed, expires in {}", tokenResponse.getExpiresIn());
188     }
189
190     /**
191      * Sends a door action to the MyQ API
192      *
193      * @param device
194      * @param action
195      */
196     public void sendDoorAction(DeviceDTO device, String action) {
197         sendAction(device, action, CMD_DOOR_URL);
198     }
199
200     /**
201      * Sends a lamp action to the MyQ API
202      *
203      * @param device
204      * @param action
205      */
206     public void sendLampAction(DeviceDTO device, String action) {
207         sendAction(device, action, CMD_LAMP_URL);
208     }
209
210     private void sendAction(DeviceDTO device, String action, String urlFormat) {
211         if (getThing().getStatus() != ThingStatus.ONLINE) {
212             logger.debug("Account offline, ignoring action {}", action);
213             return;
214         }
215
216         try {
217             ContentResponse response = sendRequest(
218                     String.format(urlFormat, device.accountId, device.serialNumber, action), HttpMethod.PUT, null,
219                     null);
220             if (HttpStatus.isSuccess(response.getStatus())) {
221                 restartPolls(true);
222             } else {
223                 logger.debug("Failed to send action {} : {}", action, response.getContentAsString());
224             }
225         } catch (InterruptedException | MyQCommunicationException | MyQAuthenticationException e) {
226             logger.debug("Could not send action", e);
227         }
228     }
229
230     /**
231      * Last known state of MyQ Devices
232      *
233      * @return cached MyQ devices
234      */
235     public @Nullable List<DeviceDTO> devicesCache() {
236         return devicesCache;
237     }
238
239     private void stopPolls() {
240         stopNormalPoll();
241         stopRapidPoll();
242     }
243
244     private synchronized void stopNormalPoll() {
245         stopFuture(normalPollFuture);
246         normalPollFuture = null;
247     }
248
249     private synchronized void stopRapidPoll() {
250         stopFuture(rapidPollFuture);
251         rapidPollFuture = null;
252     }
253
254     private void stopFuture(@Nullable Future<?> future) {
255         if (future != null) {
256             future.cancel(true);
257         }
258     }
259
260     private synchronized void restartPolls(boolean rapid) {
261         stopPolls();
262         if (rapid) {
263             normalPollFuture = scheduler.scheduleWithFixedDelay(this::normalPoll, 35, normalRefreshSeconds,
264                     TimeUnit.SECONDS);
265             rapidPollFuture = scheduler.scheduleWithFixedDelay(this::rapidPoll, 3, RAPID_REFRESH_SECONDS,
266                     TimeUnit.SECONDS);
267         } else {
268             normalPollFuture = scheduler.scheduleWithFixedDelay(this::normalPoll, 0, normalRefreshSeconds,
269                     TimeUnit.SECONDS);
270         }
271     }
272
273     private void normalPoll() {
274         stopRapidPoll();
275         fetchData();
276     }
277
278     private void rapidPoll() {
279         fetchData();
280     }
281
282     private synchronized void fetchData() {
283         try {
284             if (accounts == null) {
285                 getAccounts();
286             }
287             getDevices();
288         } catch (MyQCommunicationException e) {
289             logger.debug("MyQ communication error", e);
290             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
291         } catch (MyQAuthenticationException e) {
292             logger.debug("MyQ authentication error", e);
293             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
294             stopPolls();
295         } catch (InterruptedException e) {
296             // we were shut down, ignore
297         }
298     }
299
300     /**
301      * This attempts to navigate the MyQ oAuth login flow in order to obtain a @AccessTokenResponse
302      *
303      * @return AccessTokenResponse token
304      * @throws InterruptedException
305      * @throws MyQCommunicationException
306      * @throws MyQAuthenticationException
307      */
308     private AccessTokenResponse login()
309             throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
310         try {
311             // make sure we have a fresh session
312             URI authUri = new URI(LOGIN_BASE_URL);
313             CookieStore store = httpClient.getCookieStore();
314             store.get(authUri).forEach(cookie -> {
315                 store.remove(authUri, cookie);
316             });
317
318             String codeVerifier = generateCodeVerifier();
319
320             ContentResponse loginPageResponse = getLoginPage(codeVerifier);
321
322             // load the login page to get cookies and form parameters
323             Document loginPage = Jsoup.parse(loginPageResponse.getContentAsString());
324             Element form = loginPage.select("form").first();
325             Element requestToken = loginPage.select("input[name=__RequestVerificationToken]").first();
326             Element returnURL = loginPage.select("input[name=ReturnUrl]").first();
327
328             if (form == null || requestToken == null) {
329                 throw new MyQCommunicationException("Could not load login page");
330             }
331
332             // url that the form will submit to
333             String action = LOGIN_BASE_URL + form.attr("action");
334
335             // post our user name and password along with elements from the scraped form
336             String location = postLogin(action, requestToken.attr("value"), returnURL.attr("value"));
337             if (location == null) {
338                 throw new MyQAuthenticationException("Could not login with credentials");
339             }
340
341             // finally complete the oAuth flow and retrieve a JSON oAuth token response
342             ContentResponse tokenResponse = getLoginToken(location, codeVerifier);
343             String loginToken = tokenResponse.getContentAsString();
344
345             AccessTokenResponse accessTokenResponse = gsonLowerCase.fromJson(loginToken, AccessTokenResponse.class);
346             if (accessTokenResponse == null) {
347                 throw new MyQAuthenticationException("Could not parse token response");
348             }
349             getOAuthService().importAccessTokenResponse(accessTokenResponse);
350             return accessTokenResponse;
351         } catch (IOException | ExecutionException | TimeoutException | OAuthException | URISyntaxException e) {
352             throw new MyQCommunicationException(e.getMessage());
353         }
354     }
355
356     private void getAccounts() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
357         ContentResponse response = sendRequest(ACCOUNTS_URL, HttpMethod.GET, null, null);
358         accounts = parseResultAndUpdateStatus(response, gsonLowerCase, AccountsDTO.class);
359     }
360
361     private void getDevices() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
362         AccountsDTO localAccounts = accounts;
363         if (localAccounts == null) {
364             return;
365         }
366
367         List<DeviceDTO> currentDevices = new ArrayList<DeviceDTO>();
368
369         for (AccountDTO account : localAccounts.accounts) {
370             ContentResponse response = sendRequest(String.format(DEVICES_URL, account.id), HttpMethod.GET, null, null);
371             DevicesDTO devices = parseResultAndUpdateStatus(response, gsonLowerCase, DevicesDTO.class);
372             currentDevices.addAll(devices.items);
373             devices.items.forEach(device -> {
374                 ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, device.deviceFamily);
375                 if (SUPPORTED_DISCOVERY_THING_TYPES_UIDS.contains(thingTypeUID)) {
376                     for (Thing thing : getThing().getThings()) {
377                         ThingHandler handler = thing.getHandler();
378                         if (handler != null && ((MyQDeviceHandler) handler).getSerialNumber()
379                                 .equalsIgnoreCase(device.serialNumber)) {
380                             ((MyQDeviceHandler) handler).handleDeviceUpdate(device);
381                         }
382                     }
383                 }
384             });
385         }
386         devicesCache = currentDevices;
387     }
388
389     private synchronized ContentResponse sendRequest(String url, HttpMethod method, @Nullable ContentProvider content,
390             @Nullable String contentType)
391             throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
392         AccessTokenResponse tokenResponse = null;
393         // if we don't need to force a login, attempt to use the token we have
394         if (!needsLogin) {
395             try {
396                 tokenResponse = getOAuthService().getAccessTokenResponse();
397             } catch (OAuthException | IOException | OAuthResponseException e) {
398                 // ignore error, will try to login below
399                 logger.debug("Error accessing token, will attempt to login again", e);
400             }
401         }
402
403         // if no token, or we need to login, do so now
404         if (tokenResponse == null) {
405             tokenResponse = login();
406             needsLogin = false;
407         }
408
409         Request request = httpClient.newRequest(url).method(method).agent(userAgent).timeout(10, TimeUnit.SECONDS)
410                 .header("Authorization", authTokenHeader(tokenResponse));
411         if (content != null & contentType != null) {
412             request = request.content(content, contentType);
413         }
414
415         // use asyc jetty as the API service will response with a 401 error when credentials are wrong,
416         // but not a WWW-Authenticate header which causes Jetty to throw a generic execution exception which
417         // prevents us from knowing the response code
418         logger.trace("Sending {} to {}", request.getMethod(), request.getURI());
419         final CompletableFuture<ContentResponse> futureResult = new CompletableFuture<>();
420         request.send(new BufferingResponseListener() {
421             @NonNullByDefault({})
422             @Override
423             public void onComplete(Result result) {
424                 Response response = result.getResponse();
425                 futureResult.complete(new HttpContentResponse(response, getContent(), getMediaType(), getEncoding()));
426             }
427         });
428
429         try {
430             ContentResponse result = futureResult.get();
431             logger.trace("Account Response - status: {} content: {}", result.getStatus(), result.getContentAsString());
432             return result;
433         } catch (ExecutionException e) {
434             throw new MyQCommunicationException(e.getMessage());
435         }
436     }
437
438     private <T> T parseResultAndUpdateStatus(ContentResponse response, Gson parser, Class<T> classOfT)
439             throws MyQCommunicationException {
440         if (HttpStatus.isSuccess(response.getStatus())) {
441             try {
442                 T responseObject = parser.fromJson(response.getContentAsString(), classOfT);
443                 if (responseObject != null) {
444                     if (getThing().getStatus() != ThingStatus.ONLINE) {
445                         updateStatus(ThingStatus.ONLINE);
446                     }
447                     return responseObject;
448                 } else {
449                     throw new MyQCommunicationException("Bad response from server");
450                 }
451             } catch (JsonSyntaxException e) {
452                 throw new MyQCommunicationException("Invalid JSON Response " + response.getContentAsString());
453             }
454         } else if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
455             // our tokens no longer work, will need to login again
456             needsLogin = true;
457             throw new MyQCommunicationException("Token was rejected for request");
458         } else {
459             throw new MyQCommunicationException(
460                     "Invalid Response Code " + response.getStatus() + " : " + response.getContentAsString());
461         }
462     }
463
464     /**
465      * Returns the MyQ login page which contains form elements and cookies needed to login
466      *
467      * @param codeVerifier
468      * @return
469      * @throws InterruptedException
470      * @throws ExecutionException
471      * @throws TimeoutException
472      */
473     private ContentResponse getLoginPage(String codeVerifier)
474             throws InterruptedException, ExecutionException, TimeoutException {
475         try {
476             Request request = httpClient.newRequest(LOGIN_AUTHORIZE_URL) //
477                     .param("client_id", CLIENT_ID) //
478                     .param("code_challenge", generateCodeChallange(codeVerifier)) //
479                     .param("code_challenge_method", "S256") //
480                     .param("redirect_uri", REDIRECT_URI) //
481                     .param("response_type", "code") //
482                     .param("scope", SCOPE) //
483                     .agent(userAgent).followRedirects(true);
484             logger.debug("Sending {} to {}", request.getMethod(), request.getURI());
485             ContentResponse response = request.send();
486             logger.debug("Login Code {} Response {}", response.getStatus(), response.getContentAsString());
487             return response;
488         } catch (NoSuchAlgorithmException e) {
489             throw new ExecutionException(e.getCause());
490         }
491     }
492
493     /**
494      * Sends configured credentials and elements from the login page in order to obtain a redirect location header value
495      *
496      * @param url
497      * @param requestToken
498      * @param returnURL
499      * @return The location header value
500      * @throws InterruptedException
501      * @throws ExecutionException
502      * @throws TimeoutException
503      */
504     @Nullable
505     private String postLogin(String url, String requestToken, String returnURL)
506             throws InterruptedException, ExecutionException, TimeoutException {
507         /*
508          * on a successful post to this page we will get several redirects, and a final 301 to:
509          * com.myqops://ios?code=0123456789&scope=MyQ_Residential%20offline_access&iss=https%3A%2F%2Fpartner-identity.
510          * myq-cloud.com
511          *
512          * We can then take the parameters out of this location and continue the process
513          */
514         Fields fields = new Fields();
515         fields.add("Email", username);
516         fields.add("Password", password);
517         fields.add("__RequestVerificationToken", requestToken);
518         fields.add("ReturnUrl", returnURL);
519
520         Request request = httpClient.newRequest(url).method(HttpMethod.POST) //
521                 .content(new FormContentProvider(fields)) //
522                 .agent(userAgent) //
523                 .followRedirects(false);
524         setCookies(request);
525
526         logger.debug("Posting Login to {}", url);
527         ContentResponse response = request.send();
528
529         String location = null;
530
531         // follow redirects until we match our REDIRECT_URI or hit a redirect safety limit
532         for (int i = 0; i < LOGIN_MAX_REDIRECTS && HttpStatus.isRedirection(response.getStatus()); i++) {
533
534             String loc = response.getHeaders().get("location");
535             if (logger.isTraceEnabled()) {
536                 logger.trace("Redirect Login: Code {} Location Header: {} Response {}", response.getStatus(), loc,
537                         response.getContentAsString());
538             }
539             if (loc == null) {
540                 logger.debug("No location value");
541                 break;
542             }
543             if (loc.indexOf(REDIRECT_URI) == 0) {
544                 location = loc;
545                 break;
546             }
547             request = httpClient.newRequest(LOGIN_BASE_URL + loc).agent(userAgent).followRedirects(false);
548             setCookies(request);
549             response = request.send();
550         }
551         return location;
552     }
553
554     /**
555      * Final step of the login process to get a oAuth access response token
556      *
557      * @param redirectLocation
558      * @param codeVerifier
559      * @return
560      * @throws InterruptedException
561      * @throws ExecutionException
562      * @throws TimeoutException
563      */
564     private ContentResponse getLoginToken(String redirectLocation, String codeVerifier)
565             throws InterruptedException, ExecutionException, TimeoutException {
566         try {
567             Map<String, String> params = parseLocationQuery(redirectLocation);
568
569             Fields fields = new Fields();
570             fields.add("client_id", CLIENT_ID);
571             fields.add("client_secret", Base64.getEncoder().encodeToString(CLIENT_SECRET.getBytes()));
572             fields.add("code", params.get("code"));
573             fields.add("code_verifier", codeVerifier);
574             fields.add("grant_type", "authorization_code");
575             fields.add("redirect_uri", REDIRECT_URI);
576             fields.add("scope", params.get("scope"));
577
578             Request request = httpClient.newRequest(LOGIN_TOKEN_URL) //
579                     .content(new FormContentProvider(fields)) //
580                     .method(HttpMethod.POST) //
581                     .agent(userAgent).followRedirects(true);
582             setCookies(request);
583
584             ContentResponse response = request.send();
585             if (logger.isTraceEnabled()) {
586                 logger.trace("Login Code {} Response {}", response.getStatus(), response.getContentAsString());
587             }
588             return response;
589         } catch (URISyntaxException e) {
590             throw new ExecutionException(e.getCause());
591         }
592     }
593
594     private OAuthClientService getOAuthService() {
595         OAuthClientService oAuthService = this.oAuthService;
596         if (oAuthService == null || oAuthService.isClosed()) {
597             oAuthService = oAuthFactory.createOAuthClientService(getThing().toString(), LOGIN_TOKEN_URL,
598                     LOGIN_AUTHORIZE_URL, CLIENT_ID, CLIENT_SECRET, SCOPE, false);
599             oAuthService.addAccessTokenRefreshListener(this);
600             this.oAuthService = oAuthService;
601         }
602         return oAuthService;
603     }
604
605     private static String randomString(int length) {
606         int low = 97; // a-z
607         int high = 122; // A-Z
608         StringBuilder sb = new StringBuilder(length);
609         Random random = new Random();
610         for (int i = 0; i < length; i++) {
611             sb.append((char) (low + (int) (random.nextFloat() * (high - low + 1))));
612         }
613         return sb.toString();
614     }
615
616     private String generateCodeVerifier() {
617         SecureRandom secureRandom = new SecureRandom();
618         byte[] codeVerifier = new byte[32];
619         secureRandom.nextBytes(codeVerifier);
620         return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifier);
621     }
622
623     private String generateCodeChallange(String codeVerifier) throws NoSuchAlgorithmException {
624         byte[] bytes = codeVerifier.getBytes(StandardCharsets.US_ASCII);
625         MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
626         messageDigest.update(bytes, 0, bytes.length);
627         byte[] digest = messageDigest.digest();
628         return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
629     }
630
631     private Map<String, String> parseLocationQuery(String location) throws URISyntaxException {
632         URI uri = new URI(location);
633         return Arrays.stream(uri.getQuery().split("&")).map(str -> str.split("="))
634                 .collect(Collectors.toMap(str -> str[0], str -> str[1]));
635     }
636
637     private void setCookies(Request request) {
638         for (HttpCookie c : httpClient.getCookieStore().getCookies()) {
639             request.cookie(c);
640         }
641     }
642
643     private String authTokenHeader(AccessTokenResponse tokenResponse) {
644         return tokenResponse.getTokenType() + " " + tokenResponse.getAccessToken();
645     }
646
647     /**
648      * Exception for authenticated related errors
649      */
650     class MyQAuthenticationException extends Exception {
651         private static final long serialVersionUID = 1L;
652
653         public MyQAuthenticationException(String message) {
654             super(message);
655         }
656     }
657
658     /**
659      * Generic exception for non authentication related errors when communicating with the MyQ service.
660      */
661     class MyQCommunicationException extends IOException {
662         private static final long serialVersionUID = 1L;
663
664         public MyQCommunicationException(@Nullable String message) {
665             super(message);
666         }
667     }
668 }