]> git.basschouten.com Git - openhab-addons.git/blob
c7101a3540b7234abc1c1a66727c4f111f4d073b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.nest.internal.sdm.api;
14
15 import static org.eclipse.jetty.http.HttpHeader.*;
16 import static org.eclipse.jetty.http.HttpMethod.*;
17 import static org.openhab.binding.nest.internal.sdm.dto.SDMGson.GSON;
18
19 import java.io.IOException;
20 import java.math.BigDecimal;
21 import java.time.Duration;
22 import java.util.List;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.eclipse.jetty.client.api.ContentResponse;
33 import org.eclipse.jetty.client.api.Request;
34 import org.eclipse.jetty.client.util.StringContentProvider;
35 import org.openhab.binding.nest.internal.sdm.dto.SDMCommands.SDMCommandRequest;
36 import org.openhab.binding.nest.internal.sdm.dto.SDMCommands.SDMCommandResponse;
37 import org.openhab.binding.nest.internal.sdm.dto.SDMDevice;
38 import org.openhab.binding.nest.internal.sdm.dto.SDMError;
39 import org.openhab.binding.nest.internal.sdm.dto.SDMError.SDMErrorDetails;
40 import org.openhab.binding.nest.internal.sdm.dto.SDMListDevicesResponse;
41 import org.openhab.binding.nest.internal.sdm.dto.SDMListRoomsResponse;
42 import org.openhab.binding.nest.internal.sdm.dto.SDMListStructuresResponse;
43 import org.openhab.binding.nest.internal.sdm.dto.SDMRoom;
44 import org.openhab.binding.nest.internal.sdm.dto.SDMStructure;
45 import org.openhab.binding.nest.internal.sdm.exception.FailedSendingSDMDataException;
46 import org.openhab.binding.nest.internal.sdm.exception.InvalidSDMAccessTokenException;
47 import org.openhab.binding.nest.internal.sdm.exception.InvalidSDMAuthorizationCodeException;
48 import org.openhab.binding.nest.internal.sdm.listener.SDMAPIRequestListener;
49 import org.openhab.core.auth.client.oauth2.AccessTokenResponse;
50 import org.openhab.core.auth.client.oauth2.OAuthClientService;
51 import org.openhab.core.auth.client.oauth2.OAuthException;
52 import org.openhab.core.auth.client.oauth2.OAuthFactory;
53 import org.openhab.core.auth.client.oauth2.OAuthResponseException;
54 import org.openhab.core.io.net.http.HttpClientFactory;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * The {@link SDMAPI} implements the SDM REST API which allows for querying Nest device, structure and room information
60  * as well as executing device commands.
61  *
62  * @author Wouter Born - Initial contribution
63  *
64  * @see https://developers.google.com/nest/device-access/reference/rest
65  */
66 @NonNullByDefault
67 public class SDMAPI {
68
69     private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
70     private static final String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
71     private static final String REDIRECT_URI = "https://www.google.com";
72
73     private static final String SDM_HANDLE_FORMAT = "%s.sdm";
74     private static final String SDM_SCOPE = "https://www.googleapis.com/auth/sdm.service";
75
76     private static final String SDM_URL_PREFIX = "https://smartdevicemanagement.googleapis.com/v1/enterprises/";
77
78     private static final String APPLICATION_JSON = "application/json";
79     private static final String BEARER = "Bearer ";
80     private static final String IMAGE_JPEG = "image/jpeg";
81
82     private static final Duration REQUEST_TIMEOUT = Duration.ofMinutes(1);
83
84     private final Logger logger = LoggerFactory.getLogger(SDMAPI.class);
85
86     private final HttpClient httpClient;
87     private final OAuthClientService oAuthService;
88     private final String projectId;
89
90     private final Set<SDMAPIRequestListener> requestListeners = ConcurrentHashMap.newKeySet();
91
92     public SDMAPI(HttpClientFactory httpClientFactory, OAuthFactory oAuthFactory, String ownerId, String projectId,
93             String clientId, String clientSecret) {
94         this.httpClient = httpClientFactory.getCommonHttpClient();
95         this.oAuthService = oAuthFactory.createOAuthClientService(String.format(SDM_HANDLE_FORMAT, ownerId), TOKEN_URL,
96                 AUTH_URL, clientId, clientSecret, SDM_SCOPE, false);
97         this.projectId = projectId;
98     }
99
100     public void dispose() {
101         requestListeners.clear();
102     }
103
104     public void authorizeClient(String authorizationCode) throws InvalidSDMAuthorizationCodeException, IOException {
105         try {
106             oAuthService.getAccessTokenResponseByAuthorizationCode(authorizationCode, REDIRECT_URI);
107         } catch (OAuthException | OAuthResponseException e) {
108             throw new InvalidSDMAuthorizationCodeException(
109                     "Failed to authorize SDM client. Check the authorization code or generate a new one.", e);
110         }
111     }
112
113     public void checkAccessTokenValidity() throws InvalidSDMAccessTokenException, IOException {
114         getAuthorizationHeader();
115     }
116
117     public void addRequestListener(SDMAPIRequestListener listener) {
118         requestListeners.add(listener);
119     }
120
121     public void removeRequestListener(SDMAPIRequestListener listener) {
122         requestListeners.remove(listener);
123     }
124
125     public <T extends SDMCommandResponse> @Nullable T executeDeviceCommand(String deviceId,
126             SDMCommandRequest<T> request) throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
127         logger.debug("Executing device command for: {}", deviceId);
128         String requestContent = GSON.toJson(request);
129         String responseContent = postJson(getDeviceUrl(deviceId) + ":executeCommand", requestContent);
130         return GSON.fromJson(responseContent, request.getResponseClass());
131     }
132
133     private String getAuthorizationHeader() throws InvalidSDMAccessTokenException, IOException {
134         try {
135             AccessTokenResponse response = oAuthService.getAccessTokenResponse();
136             if (response == null || response.getAccessToken() == null || response.getAccessToken().isEmpty()) {
137                 throw new InvalidSDMAccessTokenException("No SDM access token. Client may not have been authorized.");
138             }
139             if (response.getRefreshToken() == null || response.getRefreshToken().isEmpty()) {
140                 throw new InvalidSDMAccessTokenException(
141                         "No SDM refresh token. Delete and readd credentials, then reauthorize.");
142             }
143             return BEARER + response.getAccessToken();
144         } catch (OAuthException | OAuthResponseException e) {
145             throw new InvalidSDMAccessTokenException(
146                     "Error fetching SDM access token. Check the authorization code or generate a new one.", e);
147         }
148     }
149
150     public byte[] getCameraImage(String url, String token, @Nullable BigDecimal imageWidth,
151             @Nullable BigDecimal imageHeight) throws FailedSendingSDMDataException {
152         try {
153             logger.debug("Getting camera image from: {}", url);
154
155             Request request = httpClient.newRequest(url) //
156                     .method(GET) //
157                     .header(ACCEPT, IMAGE_JPEG) //
158                     .header(AUTHORIZATION, token) //
159                     .timeout(REQUEST_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS);
160
161             if (imageWidth != null) {
162                 request = request.param("width", Long.toString(imageWidth.longValue()));
163             } else if (imageHeight != null) {
164                 request = request.param("height", Long.toString(imageHeight.longValue()));
165             }
166
167             ContentResponse contentResponse = request.send();
168             logResponseErrors(contentResponse);
169             logger.debug("Retrieved camera image from: {}", url);
170             requestListeners.forEach(SDMAPIRequestListener::onSuccess);
171             return contentResponse.getContent();
172         } catch (ExecutionException | InterruptedException | TimeoutException e) {
173             logger.debug("Failed to get camera image", e);
174             FailedSendingSDMDataException exception = new FailedSendingSDMDataException("Failed to get camera image",
175                     e);
176             requestListeners.forEach(listener -> listener.onError(exception));
177             throw exception;
178         }
179     }
180
181     public @Nullable SDMDevice getDevice(String deviceId)
182             throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
183         logger.debug("Getting device: {}", deviceId);
184         return GSON.fromJson(getJson(getDeviceUrl(deviceId)), SDMDevice.class);
185     }
186
187     public @Nullable SDMStructure getStructure(String structureId)
188             throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
189         logger.debug("Getting structure: {}", structureId);
190         return GSON.fromJson(getJson(getStructureUrl(structureId)), SDMStructure.class);
191     }
192
193     public @Nullable SDMRoom getRoom(String structureId, String roomId)
194             throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
195         logger.debug("Getting structure {} room: {}", structureId, roomId);
196         return GSON.fromJson(getJson(getRoomUrl(structureId, roomId)), SDMRoom.class);
197     }
198
199     private String getProjectUrl() {
200         return SDM_URL_PREFIX + projectId;
201     }
202
203     private String getDevicesUrl() {
204         return getProjectUrl() + "/devices";
205     }
206
207     private String getDevicesUrl(String pageToken) {
208         return getDevicesUrl() + "?pageToken=" + pageToken;
209     }
210
211     private String getDeviceUrl(String deviceId) {
212         return getDevicesUrl() + "/" + deviceId;
213     }
214
215     private String getStructuresUrl() {
216         return getProjectUrl() + "/structures";
217     }
218
219     private String getStructuresUrl(String pageToken) {
220         return getStructuresUrl() + "?pageToken=" + pageToken;
221     }
222
223     private String getStructureUrl(String structureId) {
224         return getStructuresUrl() + "/" + structureId;
225     }
226
227     private String getRoomsUrl(String structureId) {
228         return getStructureUrl(structureId) + "/rooms";
229     }
230
231     private String getRoomsUrl(String structureId, String pageToken) {
232         return getRoomsUrl(structureId) + "?pageToken=" + pageToken;
233     }
234
235     private String getRoomUrl(String structureId, String roomId) {
236         return getRoomsUrl(structureId) + "/" + roomId;
237     }
238
239     public List<SDMDevice> listDevices() throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
240         logger.debug("Listing devices");
241         SDMListDevicesResponse response = GSON.fromJson(getJson(getDevicesUrl()), SDMListDevicesResponse.class);
242         List<SDMDevice> result = response == null ? List.of() : response.devices;
243         while (response != null && !response.nextPageToken.isEmpty()) {
244             response = GSON.fromJson(getJson(getDevicesUrl(response.nextPageToken)), SDMListDevicesResponse.class);
245             if (response != null) {
246                 result.addAll(response.devices);
247             }
248         }
249         return result;
250     }
251
252     public List<SDMStructure> listStructures() throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
253         logger.debug("Listing structures");
254         SDMListStructuresResponse response = GSON.fromJson(getJson(getStructuresUrl()),
255                 SDMListStructuresResponse.class);
256         List<SDMStructure> result = response == null ? List.of() : response.structures;
257         while (response != null && !response.nextPageToken.isEmpty()) {
258             response = GSON.fromJson(getJson(getStructuresUrl(response.nextPageToken)),
259                     SDMListStructuresResponse.class);
260             if (response != null) {
261                 result.addAll(response.structures);
262             }
263         }
264         return result;
265     }
266
267     public List<SDMRoom> listRooms(String structureId)
268             throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
269         logger.debug("Listing rooms for structure: {}", structureId);
270         SDMListRoomsResponse response = GSON.fromJson(getJson(getRoomsUrl(structureId)), SDMListRoomsResponse.class);
271         List<SDMRoom> result = response == null ? List.of() : response.rooms;
272         while (response != null && !response.nextPageToken.isEmpty()) {
273             response = GSON.fromJson(getJson(getRoomsUrl(structureId, response.nextPageToken)),
274                     SDMListRoomsResponse.class);
275             if (response != null) {
276                 result.addAll(response.rooms);
277             }
278         }
279         return result;
280     }
281
282     private void logResponseErrors(ContentResponse contentResponse) {
283         if (contentResponse.getStatus() >= 400) {
284             logger.debug("SDM API error: {}", contentResponse.getContentAsString());
285
286             SDMError error = GSON.fromJson(contentResponse.getContentAsString(), SDMError.class);
287             SDMErrorDetails details = error == null ? null : error.error;
288
289             if (details != null && !details.message.isBlank()) {
290                 logger.warn("SDM API error: {}", details.message);
291             } else {
292                 logger.warn("SDM API error: {} (HTTP {})", contentResponse.getReason(), contentResponse.getStatus());
293             }
294         }
295     }
296
297     private String getJson(String url) throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
298         try {
299             logger.debug("Getting JSON from: {}", url);
300             ContentResponse contentResponse = httpClient.newRequest(url) //
301                     .method(GET) //
302                     .header(ACCEPT, APPLICATION_JSON) //
303                     .header(AUTHORIZATION, getAuthorizationHeader()) //
304                     .timeout(REQUEST_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS) //
305                     .send();
306             logResponseErrors(contentResponse);
307             String response = contentResponse.getContentAsString();
308             logger.debug("Response: {}", response);
309             requestListeners.forEach(SDMAPIRequestListener::onSuccess);
310             return response;
311         } catch (ExecutionException | InterruptedException | IOException | TimeoutException e) {
312             logger.debug("Failed to send JSON GET request", e);
313             FailedSendingSDMDataException exception = new FailedSendingSDMDataException(
314                     "Failed to send JSON GET request", e);
315             requestListeners.forEach(listener -> listener.onError(exception));
316             throw exception;
317         }
318     }
319
320     private String postJson(String url, String requestContent)
321             throws FailedSendingSDMDataException, InvalidSDMAccessTokenException {
322         try {
323             logger.debug("Posting JSON to: {}", url);
324             ContentResponse contentResponse = httpClient.newRequest(url) //
325                     .method(POST) //
326                     .header(ACCEPT, APPLICATION_JSON) //
327                     .header(AUTHORIZATION, getAuthorizationHeader()) //
328                     .content(new StringContentProvider(requestContent), APPLICATION_JSON) //
329                     .timeout(REQUEST_TIMEOUT.toNanos(), TimeUnit.NANOSECONDS) //
330                     .send();
331             logResponseErrors(contentResponse);
332             String response = contentResponse.getContentAsString();
333             logger.debug("Response: {}", response);
334             requestListeners.forEach(SDMAPIRequestListener::onSuccess);
335             return response;
336         } catch (ExecutionException | InterruptedException | IOException | TimeoutException e) {
337             logger.debug("Failed to send JSON POST request", e);
338             FailedSendingSDMDataException exception = new FailedSendingSDMDataException(
339                     "Failed to send JSON POST request", e);
340             requestListeners.forEach(listener -> listener.onError(exception));
341             throw exception;
342         }
343     }
344 }