2 * Copyright (c) 2010-2022 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.pushover.internal.connection;
15 import static org.openhab.binding.pushover.internal.PushoverBindingConstants.*;
17 import java.net.URLEncoder;
18 import java.nio.charset.StandardCharsets;
19 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.eclipse.jetty.client.api.ContentProvider;
30 import org.eclipse.jetty.client.api.ContentResponse;
31 import org.eclipse.jetty.client.api.Request;
32 import org.eclipse.jetty.http.HttpMethod;
33 import org.eclipse.jetty.http.HttpStatus;
34 import org.openhab.binding.pushover.internal.config.PushoverAccountConfiguration;
35 import org.openhab.binding.pushover.internal.dto.Sound;
36 import org.openhab.core.cache.ExpiringCache;
37 import org.openhab.core.i18n.CommunicationException;
38 import org.openhab.core.i18n.ConfigurationException;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.gson.JsonElement;
43 import com.google.gson.JsonObject;
44 import com.google.gson.JsonParser;
45 import com.google.gson.JsonSyntaxException;
48 * The {@link PushoverAPIConnection} is responsible for handling the connections to Pushover Messages API.
50 * @author Christoph Weitkamp - Initial contribution
53 public class PushoverAPIConnection {
55 private static final String JSON_VALUE_ERRORS = "errors";
56 private static final String JSON_VALUE_RECEIPT = "receipt";
57 private static final String JSON_VALUE_SOUNDS = "sounds";
58 private static final String JSON_VALUE_STATUS = "status";
60 private final Logger logger = LoggerFactory.getLogger(PushoverAPIConnection.class);
62 private static final String VALIDATE_URL = "https://api.pushover.net/1/users/validate.json";
63 private static final String MESSAGE_URL = "https://api.pushover.net/1/messages.json";
64 private static final String CANCEL_MESSAGE_URL = "https://api.pushover.net/1/receipts/%s/cancel.json";
65 private static final String SOUNDS_URL = "https://api.pushover.net/1/sounds.json";
67 private final HttpClient httpClient;
68 private final PushoverAccountConfiguration config;
70 private final ExpiringCache<List<Sound>> cache = new ExpiringCache<>(TimeUnit.DAYS.toMillis(1),
71 this::getSoundsFromSource);
73 public PushoverAPIConnection(HttpClient httpClient, PushoverAccountConfiguration config) {
74 this.httpClient = httpClient;
78 public boolean validateUser() throws CommunicationException, ConfigurationException {
79 return getMessageStatus(
80 post(VALIDATE_URL, PushoverMessageBuilder.getInstance(config.apikey, config.user).build()));
83 public boolean sendMessage(PushoverMessageBuilder message) throws CommunicationException, ConfigurationException {
84 return getMessageStatus(post(MESSAGE_URL, message.build()));
87 public String sendPriorityMessage(PushoverMessageBuilder message)
88 throws CommunicationException, ConfigurationException {
89 final JsonObject json = JsonParser.parseString(post(MESSAGE_URL, message.build())).getAsJsonObject();
90 return getMessageStatus(json) && json.has(JSON_VALUE_RECEIPT) ? json.get(JSON_VALUE_RECEIPT).getAsString() : "";
93 public boolean cancelPriorityMessage(String receipt) throws CommunicationException, ConfigurationException {
94 return getMessageStatus(post(String.format(CANCEL_MESSAGE_URL, receipt),
95 PushoverMessageBuilder.getInstance(config.apikey, config.user).build()));
98 public @Nullable List<Sound> getSounds() {
99 return cache.getValue();
102 private List<Sound> getSoundsFromSource() throws CommunicationException, ConfigurationException {
103 final String localApikey = config.apikey;
104 if (localApikey == null || localApikey.isBlank()) {
105 throw new ConfigurationException(TEXT_OFFLINE_CONF_ERROR_MISSING_APIKEY);
109 final String content = get(
110 buildURL(SOUNDS_URL, Map.of(PushoverMessageBuilder.MESSAGE_KEY_TOKEN, localApikey)));
111 final JsonObject json = JsonParser.parseString(content).getAsJsonObject();
112 final JsonObject sounds = json.has(JSON_VALUE_SOUNDS) ? json.get(JSON_VALUE_SOUNDS).getAsJsonObject()
114 if (sounds != null) {
115 return sounds.entrySet().stream()
116 .map(entry -> new Sound(entry.getKey(), entry.getValue().getAsString()))
117 .collect(Collectors.toUnmodifiableList());
119 } catch (JsonSyntaxException e) {
125 private String buildURL(String url, Map<String, String> requestParams) {
126 return requestParams.keySet().stream().map(key -> key + "=" + encodeParam(requestParams.get(key)))
127 .collect(Collectors.joining("&", url + "?", ""));
130 private String encodeParam(@Nullable String value) {
131 return value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8);
134 private String get(String url) throws CommunicationException, ConfigurationException {
135 return executeRequest(HttpMethod.GET, url, null);
138 private String post(String url, ContentProvider body) throws CommunicationException, ConfigurationException {
139 return executeRequest(HttpMethod.POST, url, body);
142 private synchronized String executeRequest(HttpMethod httpMethod, String url, @Nullable ContentProvider body)
143 throws CommunicationException, ConfigurationException {
144 logger.trace("Pushover request: {} - URL = '{}'", httpMethod, url);
146 final Request request = httpClient.newRequest(url).method(httpMethod).timeout(config.timeout,
150 if (logger.isTraceEnabled()) {
151 logger.trace("Pushover request body: '{}'", body);
153 request.content(body);
156 final ContentResponse contentResponse = request.send();
158 final int httpStatus = contentResponse.getStatus();
159 final String content = contentResponse.getContentAsString();
160 logger.trace("Pushover response: status = {}, content = '{}'", httpStatus, content);
161 switch (httpStatus) {
162 case HttpStatus.OK_200:
164 case HttpStatus.BAD_REQUEST_400:
165 logger.debug("Pushover server responded with status code {}: {}", httpStatus, content);
166 throw new ConfigurationException(getMessageError(content));
168 logger.debug("Pushover server responded with status code {}: {}", httpStatus, content);
169 throw new CommunicationException(content);
171 } catch (ExecutionException e) {
172 String message = e.getMessage();
173 logger.debug("ExecutionException occurred during execution: {}", message, e);
174 throw new CommunicationException(message == null ? TEXT_OFFLINE_COMMUNICATION_ERROR : message,
176 } catch (TimeoutException e) {
177 String message = e.getMessage();
178 logger.debug("TimeoutException occurred during execution: {}", message, e);
179 throw new CommunicationException(message == null ? TEXT_OFFLINE_COMMUNICATION_ERROR : message);
180 } catch (InterruptedException e) {
181 Thread.currentThread().interrupt();
182 String message = e.getMessage();
183 logger.debug("InterruptedException occurred during execution: {}", message, e);
184 throw new CommunicationException(message == null ? TEXT_OFFLINE_COMMUNICATION_ERROR : message);
188 private String getMessageError(String content) {
189 final JsonObject json = JsonParser.parseString(content).getAsJsonObject();
190 final JsonElement errorsElement = json.get(JSON_VALUE_ERRORS);
191 if (errorsElement != null && errorsElement.isJsonArray()) {
192 return errorsElement.getAsJsonArray().toString();
194 return TEXT_OFFLINE_CONF_ERROR_UNKNOWN;
197 private boolean getMessageStatus(String content) {
198 final JsonObject json = JsonParser.parseString(content).getAsJsonObject();
199 return json.has(JSON_VALUE_STATUS) ? json.get(JSON_VALUE_STATUS).getAsInt() == 1 : false;
202 private boolean getMessageStatus(JsonObject json) {
203 return json.has(JSON_VALUE_STATUS) ? json.get(JSON_VALUE_STATUS).getAsInt() == 1 : false;