2 * Copyright (c) 2010-2021 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.nest.internal.sdm.api;
15 import static org.eclipse.jetty.http.HttpHeader.*;
16 import static org.eclipse.jetty.http.HttpMethod.POST;
17 import static org.openhab.binding.nest.internal.sdm.dto.SDMGson.GSON;
19 import java.io.IOException;
20 import java.time.Duration;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ScheduledThreadPoolExecutor;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import java.util.function.Consumer;
31 import java.util.stream.Collectors;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jetty.client.HttpClient;
35 import org.eclipse.jetty.client.util.StringContentProvider;
36 import org.eclipse.jetty.http.HttpMethod;
37 import org.openhab.binding.nest.internal.sdm.dto.PubSubRequestsResponses.PubSubAcknowledgeRequest;
38 import org.openhab.binding.nest.internal.sdm.dto.PubSubRequestsResponses.PubSubCreateRequest;
39 import org.openhab.binding.nest.internal.sdm.dto.PubSubRequestsResponses.PubSubPullRequest;
40 import org.openhab.binding.nest.internal.sdm.dto.PubSubRequestsResponses.PubSubPullResponse;
41 import org.openhab.binding.nest.internal.sdm.exception.FailedSendingPubSubDataException;
42 import org.openhab.binding.nest.internal.sdm.exception.InvalidPubSubAccessTokenException;
43 import org.openhab.binding.nest.internal.sdm.exception.InvalidPubSubAuthorizationCodeException;
44 import org.openhab.binding.nest.internal.sdm.listener.PubSubSubscriptionListener;
45 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
46 import org.openhab.core.auth.client.oauth2.OAuthClientService;
47 import org.openhab.core.auth.client.oauth2.OAuthException;
48 import org.openhab.core.auth.client.oauth2.OAuthFactory;
49 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
50 import org.openhab.core.common.NamedThreadFactory;
51 import org.openhab.core.io.net.http.HttpClientFactory;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * The {@link PubSubAPI} implements a subset of the Pub/Sub REST API which allows for subscribing to SDM events.
58 * @author Wouter Born - Initial contribution
60 * @see https://cloud.google.com/pubsub/docs/reference/rest
61 * @see https://developers.google.com/nest/device-access/api/events
64 public class PubSubAPI {
66 private class Subscriber implements Runnable {
68 private final String subscriptionId;
70 Subscriber(String subscriptionId) {
71 this.subscriptionId = subscriptionId;
76 if (!subscriptionListeners.containsKey(subscriptionId)) {
77 logger.debug("Stop receiving subscription '{}' messages since there are no listeners", subscriptionId);
82 String messages = pullSubscriptionMessages(subscriptionId);
84 PubSubPullResponse pullResponse = GSON.fromJson(messages, PubSubPullResponse.class);
86 if (pullResponse != null && pullResponse.receivedMessages != null) {
87 logger.debug("Subscription '{}' has {} new message(s)", subscriptionId,
88 pullResponse.receivedMessages.size());
89 forEachListener((listener) -> pullResponse.receivedMessages
90 .forEach((message) -> listener.onMessage(message.message)));
91 List<String> ackIds = pullResponse.receivedMessages.stream().map(message -> message.ackId)
92 .collect(Collectors.toList());
93 acknowledgeSubscriptionMessages(subscriptionId, ackIds);
95 forEachListener((listener) -> listener.onNoNewMessages());
98 scheduler.submit(this);
99 } catch (FailedSendingPubSubDataException e) {
100 logger.debug("Expected exception while pulling message for '{}' subscription", subscriptionId, e);
101 Throwable cause = e.getCause();
102 if (!(cause instanceof InterruptedException)) {
103 forEachListener((listener) -> listener.onError(e));
104 scheduler.schedule(this, RETRY_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS);
106 } catch (InvalidPubSubAccessTokenException e) {
107 logger.warn("Cannot pull messages for '{}' subscription (access token invalid)", subscriptionId, e);
108 forEachListener((listener) -> listener.onError(e));
109 } catch (Exception e) {
110 logger.warn("Unexpected exception while pulling message for '{}' subscription", subscriptionId, e);
111 forEachListener((listener) -> listener.onError(e));
112 scheduler.schedule(this, RETRY_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS);
116 private void forEachListener(Consumer<PubSubSubscriptionListener> consumer) {
117 Set<PubSubSubscriptionListener> listeners = subscriptionListeners.get(subscriptionId);
118 if (listeners != null) {
119 listeners.forEach(consumer::accept);
121 logger.debug("Subscription '{}' has no listeners", subscriptionId);
126 private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
127 private static final String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
128 private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
130 private static final String PUBSUB_HANDLE_FORMAT = "%s.pubsub";
131 private static final String PUBSUB_SCOPE = "https://www.googleapis.com/auth/pubsub";
133 private static final String PUBSUB_URL_PREFIX = "https://pubsub.googleapis.com/v1/";
134 private static final int PUBSUB_PULL_MAX_MESSAGES = 10;
136 private static final String APPLICATION_JSON = "application/json";
137 private static final String BEARER = "Bearer ";
139 private static final Duration REQUEST_TIMEOUT = Duration.ofMinutes(1);
140 private static final Duration RETRY_TIMEOUT = Duration.ofSeconds(30);
142 private final Logger logger = LoggerFactory.getLogger(PubSubAPI.class);
144 private final HttpClient httpClient;
145 private final OAuthClientService oAuthService;
146 private final String projectId;
147 private final ScheduledThreadPoolExecutor scheduler;
148 private final Map<String, Set<PubSubSubscriptionListener>> subscriptionListeners = new HashMap<>();
150 public PubSubAPI(HttpClientFactory httpClientFactory, OAuthFactory oAuthFactory, String ownerId, String projectId,
151 String clientId, String clientSecret) {
152 this.httpClient = httpClientFactory.getCommonHttpClient();
153 this.projectId = projectId;
154 this.oAuthService = oAuthFactory.createOAuthClientService(String.format(PUBSUB_HANDLE_FORMAT, ownerId),
155 TOKEN_URL, AUTH_URL, clientId, clientSecret, PUBSUB_SCOPE, false);
156 scheduler = new ScheduledThreadPoolExecutor(3, new NamedThreadFactory(ownerId, true));
159 public void dispose() {
160 subscriptionListeners.clear();
161 scheduler.shutdownNow();
164 public void authorizeClient(String authorizationCode) throws InvalidPubSubAuthorizationCodeException, IOException {
166 oAuthService.getAccessTokenResponseByAuthorizationCode(authorizationCode, REDIRECT_URI);
167 } catch (OAuthException | OAuthResponseException e) {
168 throw new InvalidPubSubAuthorizationCodeException(
169 "Failed to authorize Pub/Sub client. Check the authorization code or generate a new one.", e);
173 public void checkAccessTokenValidity() throws InvalidPubSubAccessTokenException, IOException {
174 getAuthorizationHeader();
177 private String acknowledgeSubscriptionMessages(String subscriptionId, List<String> ackIds)
178 throws FailedSendingPubSubDataException, InvalidPubSubAccessTokenException {
179 logger.debug("Acknowleding {} message(s) for '{}' subscription", ackIds.size(), subscriptionId);
180 String url = getSubscriptionUrl(subscriptionId) + ":acknowledge";
181 String requestContent = GSON.toJson(new PubSubAcknowledgeRequest(ackIds));
182 return postJson(url, requestContent);
185 public void addSubscriptionListener(String subscriptionId, PubSubSubscriptionListener listener) {
186 synchronized (subscriptionListeners) {
187 Set<PubSubSubscriptionListener> listeners = subscriptionListeners.get(subscriptionId);
188 if (listeners == null) {
189 listeners = new HashSet<>();
190 subscriptionListeners.put(subscriptionId, listeners);
192 listeners.add(listener);
193 if (listeners.size() == 1) {
194 scheduler.submit(new Subscriber(subscriptionId));
199 public void removeSubscriptionListener(String subscriptionId, PubSubSubscriptionListener listener) {
200 synchronized (subscriptionListeners) {
201 Set<PubSubSubscriptionListener> listeners = subscriptionListeners.get(subscriptionId);
202 if (listeners != null) {
203 listeners.remove(listener);
204 if (listeners.isEmpty()) {
205 subscriptionListeners.remove(subscriptionId);
206 scheduler.getQueue().removeIf((runnable) -> runnable instanceof Subscriber
207 && ((Subscriber) runnable).subscriptionId.equals(subscriptionId));
213 public void createSubscription(String subscriptionId, String topicName)
214 throws FailedSendingPubSubDataException, InvalidPubSubAccessTokenException {
215 logger.debug("Creating '{}' subscription", subscriptionId);
216 String url = getSubscriptionUrl(subscriptionId);
217 String requestContent = GSON.toJson(new PubSubCreateRequest(topicName, true));
218 putJson(url, requestContent);
221 private String getAuthorizationHeader() throws InvalidPubSubAccessTokenException, IOException {
223 AccessTokenResponse response = oAuthService.getAccessTokenResponse();
224 if (response == null || response.getAccessToken() == null || response.getAccessToken().isEmpty()) {
225 throw new InvalidPubSubAccessTokenException(
226 "No Pub/Sub access token. Client may not have been authorized.");
228 return BEARER + response.getAccessToken();
229 } catch (OAuthException | OAuthResponseException e) {
230 throw new InvalidPubSubAccessTokenException(
231 "Error fetching Pub/Sub access token. Check the authorization code or generate a new one.", e);
235 private String getSubscriptionUrl(String subscriptionId) {
236 return PUBSUB_URL_PREFIX + "projects/" + projectId + "/subscriptions/" + subscriptionId;
239 private String postJson(String url, String requestContent)
240 throws FailedSendingPubSubDataException, InvalidPubSubAccessTokenException {
242 logger.debug("Posting JSON to: {}", url);
243 String response = httpClient.newRequest(url) //
245 .header(ACCEPT, APPLICATION_JSON) //
246 .header(AUTHORIZATION, getAuthorizationHeader()) //
247 .content(new StringContentProvider(requestContent), APPLICATION_JSON) //
248 .timeout(REQUEST_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS) //
250 .getContentAsString();
251 logger.debug("Response: {}", response);
253 } catch (ExecutionException | InterruptedException | IOException | TimeoutException e) {
254 throw new FailedSendingPubSubDataException("Failed to send JSON POST request", e);
258 private String pullSubscriptionMessages(String subscriptionId)
259 throws FailedSendingPubSubDataException, InvalidPubSubAccessTokenException {
260 logger.debug("Pulling messages for '{}' subscription", subscriptionId);
261 String url = getSubscriptionUrl(subscriptionId) + ":pull";
262 String requestContent = GSON.toJson(new PubSubPullRequest(PUBSUB_PULL_MAX_MESSAGES));
263 return postJson(url, requestContent);
266 private String putJson(String url, String requestContent)
267 throws FailedSendingPubSubDataException, InvalidPubSubAccessTokenException {
269 logger.debug("Putting JSON to: {}", url);
270 String response = httpClient.newRequest(url) //
271 .method(HttpMethod.PUT) //
272 .header(ACCEPT, APPLICATION_JSON) //
273 .header(AUTHORIZATION, getAuthorizationHeader()) //
274 .content(new StringContentProvider(requestContent), APPLICATION_JSON) //
275 .timeout(REQUEST_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS) //
277 .getContentAsString();
278 logger.debug("Response: {}", response);
280 } catch (ExecutionException | InterruptedException | IOException | TimeoutException e) {
281 throw new FailedSendingPubSubDataException("Failed to send JSON PUT request", e);