2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.myq.internal.handler;
15 import static org.openhab.binding.myq.internal.MyQBindingConstants.*;
17 import java.io.IOException;
18 import java.net.CookieStore;
19 import java.net.HttpCookie;
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.List;
32 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;
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;
83 import com.google.gson.FieldNamingPolicy;
84 import com.google.gson.Gson;
85 import com.google.gson.GsonBuilder;
86 import com.google.gson.JsonSyntaxException;
89 * The {@link MyQAccountHandler} is responsible for communicating with the MyQ API based on an account.
91 * @author Dan Cunningham - Initial contribution
94 public class MyQAccountHandler extends BaseBridgeHandler implements AccessTokenRefreshListener {
96 * MyQ oAuth relate fields
98 private static final String CLIENT_SECRET = "VUQ0RFhuS3lQV3EyNUJTdw==";
99 private static final String CLIENT_ID = "ANDROID_CGI_MYQ";
100 private static final String REDIRECT_URI = "com.myqops://android";
101 private static final String SCOPE = "MyQ_Residential offline_access";
103 * MyQ authentication API endpoints
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;
111 * MyQ device and account API endpoints
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";
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;
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;
137 public MyQAccountHandler(Bridge bridge, HttpClient httpClient, final OAuthFactory oAuthFactory) {
139 this.httpClient = httpClient;
140 this.oAuthFactory = oAuthFactory;
144 public void handleCommand(ChannelUID channelUID, Command command) {
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 = ""; // no agent string
156 updateStatus(ThingStatus.UNKNOWN);
161 public void dispose() {
163 OAuthClientService oAuthService = this.oAuthService;
164 if (oAuthService != null) {
165 oAuthService.removeAccessTokenRefreshListener(this);
166 oAuthFactory.ungetOAuthService(getThing().toString());
167 this.oAuthService = null;
172 public void handleRemoval() {
173 oAuthFactory.deleteServiceAndAccessToken(getThing().toString());
174 super.handleRemoval();
178 public Collection<Class<? extends ThingHandlerService>> getServices() {
179 return Set.of(MyQDiscoveryService.class);
183 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
184 List<DeviceDTO> localDeviceCaches = devicesCache;
185 if (childHandler instanceof MyQDeviceHandler deviceHandler) {
186 localDeviceCaches.stream().filter(d -> deviceHandler.getSerialNumber().equalsIgnoreCase(d.serialNumber))
187 .findFirst().ifPresent(deviceHandler::handleDeviceUpdate);
192 public void onAccessTokenResponse(AccessTokenResponse tokenResponse) {
193 logger.debug("Auth Token Refreshed, expires in {}", tokenResponse.getExpiresIn());
197 * Sends a door action to the MyQ API
202 public void sendDoorAction(DeviceDTO device, String action) {
203 sendAction(device, action, CMD_DOOR_URL);
207 * Sends a lamp action to the MyQ API
212 public void sendLampAction(DeviceDTO device, String action) {
213 sendAction(device, action, CMD_LAMP_URL);
216 private void sendAction(DeviceDTO device, String action, String urlFormat) {
217 if (getThing().getStatus() != ThingStatus.ONLINE) {
218 logger.debug("Account offline, ignoring action {}", action);
223 ContentResponse response = sendRequest(
224 String.format(urlFormat, device.accountId, device.serialNumber, action), HttpMethod.PUT, null,
226 if (HttpStatus.isSuccess(response.getStatus())) {
229 logger.debug("Failed to send action {} : {}", action, response.getContentAsString());
231 } catch (InterruptedException | MyQCommunicationException | MyQAuthenticationException e) {
232 logger.debug("Could not send action", e);
237 * Last known state of MyQ Devices
239 * @return cached MyQ devices
241 public @Nullable List<DeviceDTO> devicesCache() {
245 private void stopPolls() {
250 private synchronized void stopNormalPoll() {
251 stopFuture(normalPollFuture);
252 normalPollFuture = null;
255 private synchronized void stopRapidPoll() {
256 stopFuture(rapidPollFuture);
257 rapidPollFuture = null;
260 private void stopFuture(@Nullable Future<?> future) {
261 if (future != null) {
266 private synchronized void restartPolls(boolean rapid) {
269 normalPollFuture = scheduler.scheduleWithFixedDelay(this::normalPoll, 35, normalRefreshSeconds,
271 rapidPollFuture = scheduler.scheduleWithFixedDelay(this::rapidPoll, 3, RAPID_REFRESH_SECONDS,
274 normalPollFuture = scheduler.scheduleWithFixedDelay(this::normalPoll, 0, normalRefreshSeconds,
279 private void normalPoll() {
284 private void rapidPoll() {
288 private synchronized void fetchData() {
290 if (accounts == null) {
294 } catch (MyQCommunicationException e) {
295 logger.debug("MyQ communication error", e);
296 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
297 } catch (MyQAuthenticationException e) {
298 logger.debug("MyQ authentication error", e);
299 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
301 } catch (InterruptedException e) {
302 // we were shut down, ignore
307 * This attempts to navigate the MyQ oAuth login flow in order to obtain a @AccessTokenResponse
309 * @return AccessTokenResponse token
310 * @throws InterruptedException
311 * @throws MyQCommunicationException
312 * @throws MyQAuthenticationException
314 private AccessTokenResponse login()
315 throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
317 // make sure we have a fresh session
318 URI authUri = new URI(LOGIN_BASE_URL);
319 CookieStore store = httpClient.getCookieStore();
320 store.get(authUri).forEach(cookie -> {
321 store.remove(authUri, cookie);
324 String codeVerifier = generateCodeVerifier();
326 ContentResponse loginPageResponse = getLoginPage(codeVerifier);
328 // load the login page to get cookies and form parameters
329 Document loginPage = Jsoup.parse(loginPageResponse.getContentAsString());
330 Element form = loginPage.select("form").first();
331 Element requestToken = loginPage.select("input[name=__RequestVerificationToken]").first();
332 Element returnURL = loginPage.select("input[name=ReturnUrl]").first();
334 if (form == null || requestToken == null) {
335 throw new MyQCommunicationException("Could not load login page");
338 // url that the form will submit to
339 String action = LOGIN_BASE_URL + form.attr("action");
341 // post our user name and password along with elements from the scraped form
342 String location = postLogin(action, requestToken.attr("value"), returnURL.attr("value"));
343 if (location == null) {
344 throw new MyQAuthenticationException("Could not login with credentials");
347 // finally complete the oAuth flow and retrieve a JSON oAuth token response
348 ContentResponse tokenResponse = getLoginToken(location, codeVerifier);
349 String loginToken = tokenResponse.getContentAsString();
352 AccessTokenResponse accessTokenResponse = gsonLowerCase.fromJson(loginToken, AccessTokenResponse.class);
353 if (accessTokenResponse == null) {
354 throw new MyQAuthenticationException("Could not parse token response");
356 getOAuthService().importAccessTokenResponse(accessTokenResponse);
357 return accessTokenResponse;
358 } catch (JsonSyntaxException e) {
359 throw new MyQCommunicationException("Invalid Token Response " + loginToken);
361 } catch (IOException | ExecutionException | TimeoutException | OAuthException | URISyntaxException e) {
362 throw new MyQCommunicationException(e.getMessage());
366 private void getAccounts() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
367 ContentResponse response = sendRequest(ACCOUNTS_URL, HttpMethod.GET, null, null);
368 accounts = parseResultAndUpdateStatus(response, gsonLowerCase, AccountsDTO.class);
371 private void getDevices() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
372 AccountsDTO localAccounts = accounts;
373 if (localAccounts == null) {
377 List<DeviceDTO> currentDevices = new ArrayList<DeviceDTO>();
379 for (AccountDTO account : localAccounts.accounts) {
380 ContentResponse response = sendRequest(String.format(DEVICES_URL, account.id), HttpMethod.GET, null, null);
381 DevicesDTO devices = parseResultAndUpdateStatus(response, gsonLowerCase, DevicesDTO.class);
382 currentDevices.addAll(devices.items);
383 devices.items.forEach(device -> {
384 ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, device.deviceFamily);
385 if (SUPPORTED_DISCOVERY_THING_TYPES_UIDS.contains(thingTypeUID)) {
386 for (Thing thing : getThing().getThings()) {
387 ThingHandler handler = thing.getHandler();
388 if (handler != null && ((MyQDeviceHandler) handler).getSerialNumber()
389 .equalsIgnoreCase(device.serialNumber)) {
390 ((MyQDeviceHandler) handler).handleDeviceUpdate(device);
396 devicesCache = currentDevices;
399 private synchronized ContentResponse sendRequest(String url, HttpMethod method, @Nullable ContentProvider content,
400 @Nullable String contentType)
401 throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
402 AccessTokenResponse tokenResponse = null;
403 // if we don't need to force a login, attempt to use the token we have
406 tokenResponse = getOAuthService().getAccessTokenResponse();
407 } catch (OAuthException | IOException | OAuthResponseException e) {
408 // ignore error, will try to login below
409 logger.debug("Error accessing token, will attempt to login again", e);
413 // if no token, or we need to login, do so now
414 if (tokenResponse == null) {
415 tokenResponse = login();
419 Request request = httpClient.newRequest(url).method(method).agent(userAgent).timeout(10, TimeUnit.SECONDS)
420 .header("Authorization", authTokenHeader(tokenResponse));
421 if (content != null & contentType != null) {
422 request = request.content(content, contentType);
425 // use asyc jetty as the API service will response with a 401 error when credentials are wrong,
426 // but not a WWW-Authenticate header which causes Jetty to throw a generic execution exception which
427 // prevents us from knowing the response code
428 logger.trace("Sending {} to {}", request.getMethod(), request.getURI());
429 final CompletableFuture<ContentResponse> futureResult = new CompletableFuture<>();
430 request.send(new BufferingResponseListener() {
431 @NonNullByDefault({})
433 public void onComplete(Result result) {
434 Response response = result.getResponse();
435 futureResult.complete(new HttpContentResponse(response, getContent(), getMediaType(), getEncoding()));
440 ContentResponse result = futureResult.get();
441 logger.trace("Account Response - status: {} content: {}", result.getStatus(), result.getContentAsString());
443 } catch (ExecutionException e) {
444 throw new MyQCommunicationException(e.getMessage());
448 private <T> T parseResultAndUpdateStatus(ContentResponse response, Gson parser, Class<T> classOfT)
449 throws MyQCommunicationException {
450 if (HttpStatus.isSuccess(response.getStatus())) {
452 T responseObject = parser.fromJson(response.getContentAsString(), classOfT);
453 if (responseObject != null) {
454 if (getThing().getStatus() != ThingStatus.ONLINE) {
455 updateStatus(ThingStatus.ONLINE);
457 return responseObject;
459 throw new MyQCommunicationException("Bad response from server");
461 } catch (JsonSyntaxException e) {
462 throw new MyQCommunicationException("Invalid JSON Response " + response.getContentAsString());
464 } else if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
465 // our tokens no longer work, will need to login again
467 throw new MyQCommunicationException("Token was rejected for request");
469 throw new MyQCommunicationException(
470 "Invalid Response Code " + response.getStatus() + " : " + response.getContentAsString());
475 * Returns the MyQ login page which contains form elements and cookies needed to login
477 * @param codeVerifier
479 * @throws InterruptedException
480 * @throws ExecutionException
481 * @throws TimeoutException
483 private ContentResponse getLoginPage(String codeVerifier)
484 throws InterruptedException, ExecutionException, TimeoutException {
486 Request request = httpClient.newRequest(LOGIN_AUTHORIZE_URL) //
487 .param("client_id", CLIENT_ID) //
488 .param("code_challenge", generateCodeChallange(codeVerifier)) //
489 .param("code_challenge_method", "S256") //
490 .param("redirect_uri", REDIRECT_URI) //
491 .param("response_type", "code") //
492 .param("scope", SCOPE) //
493 .agent(userAgent).followRedirects(true);
494 request.header("Accept", "\"*/*\"");
495 request.header("Authorization",
496 "Basic " + Base64.getEncoder().encodeToString((CLIENT_ID + ":").getBytes()));
497 logger.debug("Sending {} to {}", request.getMethod(), request.getURI());
498 ContentResponse response = request.send();
499 logger.debug("Login Code {} Response {}", response.getStatus(), response.getContentAsString());
501 } catch (NoSuchAlgorithmException e) {
502 throw new ExecutionException(e.getCause());
507 * Sends configured credentials and elements from the login page in order to obtain a redirect location header value
510 * @param requestToken
512 * @return The location header value
513 * @throws InterruptedException
514 * @throws ExecutionException
515 * @throws TimeoutException
518 private String postLogin(String url, String requestToken, String returnURL)
519 throws InterruptedException, ExecutionException, TimeoutException {
521 * on a successful post to this page we will get several redirects, and a final 301 to:
522 * com.myqops://ios?code=0123456789&scope=MyQ_Residential%20offline_access&iss=https%3A%2F%2Fpartner-identity.
525 * We can then take the parameters out of this location and continue the process
527 Fields fields = new Fields();
528 fields.add("Email", username);
529 fields.add("Password", password);
530 fields.add("__RequestVerificationToken", requestToken);
531 fields.add("ReturnUrl", returnURL);
533 Request request = httpClient.newRequest(url).method(HttpMethod.POST) //
534 .content(new FormContentProvider(fields)) //
536 .followRedirects(false);
539 logger.debug("Posting Login to {}", url);
540 ContentResponse response = request.send();
542 String location = null;
544 // follow redirects until we match our REDIRECT_URI or hit a redirect safety limit
545 for (int i = 0; i < LOGIN_MAX_REDIRECTS && HttpStatus.isRedirection(response.getStatus()); i++) {
547 String loc = response.getHeaders().get("location");
548 if (logger.isTraceEnabled()) {
549 logger.trace("Redirect Login: Code {} Location Header: {} Response {}", response.getStatus(), loc,
550 response.getContentAsString());
553 logger.debug("No location value");
556 if (loc.indexOf(REDIRECT_URI) == 0) {
560 request = httpClient.newRequest(LOGIN_BASE_URL + loc).agent(userAgent).followRedirects(false);
562 response = request.send();
568 * Final step of the login process to get an oAuth access response token
570 * @param redirectLocation
571 * @param codeVerifier
573 * @throws InterruptedException
574 * @throws ExecutionException
575 * @throws TimeoutException
577 private ContentResponse getLoginToken(String redirectLocation, String codeVerifier)
578 throws InterruptedException, ExecutionException, TimeoutException {
580 Map<String, String> params = parseLocationQuery(redirectLocation);
582 Fields fields = new Fields();
583 fields.add("client_id", CLIENT_ID);
584 fields.add("client_secret", Base64.getEncoder().encodeToString(CLIENT_SECRET.getBytes()));
585 fields.add("code", params.get("code"));
586 fields.add("code_verifier", codeVerifier);
587 fields.add("grant_type", "authorization_code");
588 fields.add("redirect_uri", REDIRECT_URI);
589 fields.add("scope", params.get("scope"));
591 Request request = httpClient.newRequest(LOGIN_TOKEN_URL) //
592 .content(new FormContentProvider(fields)) //
593 .method(HttpMethod.POST) //
594 .agent(userAgent).followRedirects(true);
597 ContentResponse response = request.send();
598 if (logger.isTraceEnabled()) {
599 logger.trace("Login Code {} Response {}", response.getStatus(), response.getContentAsString());
602 } catch (URISyntaxException e) {
603 throw new ExecutionException(e.getCause());
607 private OAuthClientService getOAuthService() {
608 OAuthClientService oAuthService = this.oAuthService;
609 if (oAuthService == null || oAuthService.isClosed()) {
610 oAuthService = oAuthFactory.createOAuthClientService(getThing().toString(), LOGIN_TOKEN_URL,
611 LOGIN_AUTHORIZE_URL, CLIENT_ID, CLIENT_SECRET, SCOPE, false);
612 oAuthService.addAccessTokenRefreshListener(this);
613 this.oAuthService = oAuthService;
618 private static String randomString(int length) {
620 int high = 122; // A-Z
621 StringBuilder sb = new StringBuilder(length);
622 Random random = new Random();
623 for (int i = 0; i < length; i++) {
624 sb.append((char) (low + (int) (random.nextFloat() * (high - low + 1))));
626 return sb.toString();
629 private String generateCodeVerifier() {
630 SecureRandom secureRandom = new SecureRandom();
631 byte[] codeVerifier = new byte[32];
632 secureRandom.nextBytes(codeVerifier);
633 return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifier);
636 private String generateCodeChallange(String codeVerifier) throws NoSuchAlgorithmException {
637 byte[] bytes = codeVerifier.getBytes(StandardCharsets.US_ASCII);
638 MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
639 messageDigest.update(bytes, 0, bytes.length);
640 byte[] digest = messageDigest.digest();
641 return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
644 private Map<String, String> parseLocationQuery(String location) throws URISyntaxException {
645 URI uri = new URI(location);
646 return Arrays.stream(uri.getQuery().split("&")).map(str -> str.split("="))
647 .collect(Collectors.toMap(str -> str[0], str -> str[1]));
650 private void setCookies(Request request) {
651 for (HttpCookie c : httpClient.getCookieStore().getCookies()) {
656 private String authTokenHeader(AccessTokenResponse tokenResponse) {
657 return tokenResponse.getTokenType() + " " + tokenResponse.getAccessToken();
661 * Exception for authenticated related errors
663 class MyQAuthenticationException extends Exception {
664 private static final long serialVersionUID = 1L;
666 public MyQAuthenticationException(String message) {
672 * Generic exception for non authentication related errors when communicating with the MyQ service.
674 class MyQCommunicationException extends IOException {
675 private static final long serialVersionUID = 1L;
677 public MyQCommunicationException(@Nullable String message) {