]> git.basschouten.com Git - openhab-addons.git/blob
8f84241d44ba4658a655e895c12a484db8dd087e
[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.pushover.internal.connection;
14
15 import java.net.URLEncoder;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
25
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.ExpiringCacheMap;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.gson.JsonElement;
41 import com.google.gson.JsonObject;
42 import com.google.gson.JsonParser;
43
44 /**
45  * The {@link PushoverAPIConnection} is responsible for handling the connections to Pushover Messages API.
46  *
47  * @author Christoph Weitkamp - Initial contribution
48  */
49 @NonNullByDefault
50 public class PushoverAPIConnection {
51
52     private final Logger logger = LoggerFactory.getLogger(PushoverAPIConnection.class);
53
54     private static final String VALIDATE_URL = "https://api.pushover.net/1/users/validate.json";
55     private static final String MESSAGE_URL = "https://api.pushover.net/1/messages.json";
56     private static final String CANCEL_MESSAGE_URL = "https://api.pushover.net/1/receipts/{receipt}/cancel.json";
57     private static final String SOUNDS_URL = "https://api.pushover.net/1/sounds.json";
58
59     private final HttpClient httpClient;
60     private final PushoverAccountConfiguration config;
61
62     private final ExpiringCacheMap<String, String> cache = new ExpiringCacheMap<>(TimeUnit.DAYS.toMillis(1));
63
64     public PushoverAPIConnection(HttpClient httpClient, PushoverAccountConfiguration config) {
65         this.httpClient = httpClient;
66         this.config = config;
67     }
68
69     public boolean validateUser() throws PushoverCommunicationException, PushoverConfigurationException {
70         return getMessageStatus(
71                 post(VALIDATE_URL, PushoverMessageBuilder.getInstance(config.apikey, config.user).build()));
72     }
73
74     public boolean sendMessage(PushoverMessageBuilder message)
75             throws PushoverCommunicationException, PushoverConfigurationException {
76         return getMessageStatus(post(MESSAGE_URL, message.build()));
77     }
78
79     public String sendPriorityMessage(PushoverMessageBuilder message)
80             throws PushoverCommunicationException, PushoverConfigurationException {
81         final JsonObject json = JsonParser.parseString(post(MESSAGE_URL, message.build())).getAsJsonObject();
82         return getMessageStatus(json) && json.has("receipt") ? json.get("receipt").getAsString() : "";
83     }
84
85     public boolean cancelPriorityMessage(String receipt)
86             throws PushoverCommunicationException, PushoverConfigurationException {
87         return getMessageStatus(post(CANCEL_MESSAGE_URL.replace("{receipt}", receipt),
88                 PushoverMessageBuilder.getInstance(config.apikey, config.user).build()));
89     }
90
91     public List<Sound> getSounds() throws PushoverCommunicationException, PushoverConfigurationException {
92         final String localApikey = config.apikey;
93         if (localApikey == null || localApikey.isEmpty()) {
94             throw new PushoverConfigurationException("@text/offline.conf-error-missing-apikey");
95         }
96
97         final Map<String, String> params = new HashMap<>(1);
98         params.put(PushoverMessageBuilder.MESSAGE_KEY_TOKEN, localApikey);
99
100         // TODO do not cache the response, cache the parsed list of sounds
101         final String content = getFromCache(buildURL(SOUNDS_URL, params));
102         final JsonObject json = content == null ? null : JsonParser.parseString(content).getAsJsonObject();
103         final JsonObject sounds = json == null || !json.has("sounds") ? null : json.get("sounds").getAsJsonObject();
104
105         return sounds == null ? List.of()
106                 : Collections.unmodifiableList(sounds.entrySet().stream()
107                         .map(entry -> new Sound(entry.getKey(), entry.getValue().getAsString()))
108                         .collect(Collectors.toList()));
109     }
110
111     private String buildURL(String url, Map<String, String> requestParams) {
112         return requestParams.keySet().stream().map(key -> key + "=" + encodeParam(requestParams.get(key)))
113                 .collect(Collectors.joining("&", url + "?", ""));
114     }
115
116     private String encodeParam(@Nullable String value) {
117         return value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8);
118     }
119
120     private @Nullable String getFromCache(String url) {
121         return cache.putIfAbsentAndGet(url, () -> get(url));
122     }
123
124     private String get(String url) throws PushoverCommunicationException, PushoverConfigurationException {
125         return executeRequest(HttpMethod.GET, url, null);
126     }
127
128     private String post(String url, ContentProvider body)
129             throws PushoverCommunicationException, PushoverConfigurationException {
130         return executeRequest(HttpMethod.POST, url, body);
131     }
132
133     private synchronized String executeRequest(HttpMethod httpMethod, String url, @Nullable ContentProvider body)
134             throws PushoverCommunicationException, PushoverConfigurationException {
135         logger.trace("Pushover request: {} - URL = '{}'", httpMethod, url);
136         try {
137             final Request request = httpClient.newRequest(url).method(httpMethod).timeout(config.timeout,
138                     TimeUnit.SECONDS);
139
140             if (body != null) {
141                 if (logger.isTraceEnabled()) {
142                     logger.trace("Pushover request body: '{}'", body);
143                 }
144                 request.content(body);
145             }
146
147             final ContentResponse contentResponse = request.send();
148
149             final int httpStatus = contentResponse.getStatus();
150             final String content = contentResponse.getContentAsString();
151             logger.trace("Pushover response: status = {}, content = '{}'", httpStatus, content);
152             switch (httpStatus) {
153                 case HttpStatus.OK_200:
154                     return content;
155                 case HttpStatus.BAD_REQUEST_400:
156                     logger.debug("Pushover server responded with status code {}: {}", httpStatus, content);
157                     throw new PushoverConfigurationException(getMessageError(content));
158                 default:
159                     logger.debug("Pushover server responded with status code {}: {}", httpStatus, content);
160                     throw new PushoverCommunicationException(content);
161             }
162         } catch (ExecutionException e) {
163             logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
164             throw new PushoverCommunicationException(e.getLocalizedMessage(), e.getCause());
165         } catch (InterruptedException | TimeoutException e) {
166             logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
167             throw new PushoverCommunicationException(e.getLocalizedMessage());
168         }
169     }
170
171     private String getMessageError(String content) {
172         final JsonObject json = JsonParser.parseString(content).getAsJsonObject();
173         final JsonElement errorsElement = json.get("errors");
174         if (errorsElement != null && errorsElement.isJsonArray()) {
175             return errorsElement.getAsJsonArray().toString();
176         }
177         return "@text/offline.conf-error-unknown";
178     }
179
180     private boolean getMessageStatus(String content) {
181         final JsonObject json = JsonParser.parseString(content).getAsJsonObject();
182         return json.has("status") ? json.get("status").getAsInt() == 1 : false;
183     }
184
185     private boolean getMessageStatus(JsonObject json) {
186         return json.has("status") ? json.get("status").getAsInt() == 1 : false;
187     }
188 }