]> git.basschouten.com Git - openhab-addons.git/blob
958ab6e2392c3e650094bf7b0a06321d38f53f6a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.amazonechocontrol.internal;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InterruptedIOException;
18 import java.io.OutputStream;
19 import java.net.CookieManager;
20 import java.net.CookieStore;
21 import java.net.HttpCookie;
22 import java.net.URI;
23 import java.net.URISyntaxException;
24 import java.net.URL;
25 import java.net.URLDecoder;
26 import java.net.URLEncoder;
27 import java.nio.charset.StandardCharsets;
28 import java.text.SimpleDateFormat;
29 import java.util.*;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.Future;
32 import java.util.concurrent.LinkedBlockingQueue;
33 import java.util.concurrent.ScheduledExecutorService;
34 import java.util.concurrent.ScheduledFuture;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.locks.Lock;
37 import java.util.concurrent.locks.ReentrantLock;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import java.util.stream.Collectors;
41 import java.util.stream.StreamSupport;
42 import java.util.zip.GZIPInputStream;
43
44 import javax.net.ssl.HttpsURLConnection;
45
46 import org.eclipse.jdt.annotation.NonNullByDefault;
47 import org.eclipse.jdt.annotation.Nullable;
48 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonActivities;
49 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonActivities.Activity;
50 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAnnouncementContent;
51 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAnnouncementTarget;
52 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm;
53 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm.AscendingAlarmModel;
54 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation;
55 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation.Payload;
56 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation.Trigger;
57 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
58 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult;
59 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult.Authentication;
60 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDeviceNotificationState;
61 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDeviceNotificationState.DeviceNotificationState;
62 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices;
63 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonDevices.Device;
64 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonEnabledFeeds;
65 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonEqualizer;
66 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse;
67 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Cookie;
68 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonFeed;
69 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMediaState;
70 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonMusicProvider;
71 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNetworkDetails;
72 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationRequest;
73 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationResponse;
74 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSound;
75 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationSounds;
76 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonNotificationsResponse;
77 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaySearchPhraseOperationPayload;
78 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlayValidationResult;
79 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlayerState;
80 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPlaylists;
81 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppRequest;
82 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse;
83 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.Bearer;
84 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.DeviceInfo;
85 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.Extensions;
86 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.Response;
87 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.Success;
88 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRegisterAppResponse.Tokens;
89 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonRenewTokenResponse;
90 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
91 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroups.SmartHomeGroup;
92 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonStartRoutineRequest;
93 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonUsersMeResponse;
94 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonWakeWords;
95 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonWakeWords.WakeWord;
96 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonWebSiteCookie;
97 import org.openhab.binding.amazonechocontrol.internal.jsons.SmartHomeBaseDevice;
98 import org.openhab.core.common.ThreadPoolManager;
99 import org.openhab.core.library.types.QuantityType;
100 import org.openhab.core.library.unit.SIUnits;
101 import org.openhab.core.util.HexUtils;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
104
105 import com.google.gson.Gson;
106 import com.google.gson.GsonBuilder;
107 import com.google.gson.JsonArray;
108 import com.google.gson.JsonElement;
109 import com.google.gson.JsonObject;
110 import com.google.gson.JsonParseException;
111 import com.google.gson.JsonSyntaxException;
112
113 /**
114  * The {@link Connection} is responsible for the connection to the amazon server
115  * and handling of the commands
116  *
117  * @author Michael Geramb - Initial contribution
118  */
119 @NonNullByDefault
120 public class Connection {
121     private static final String THING_THREADPOOL_NAME = "thingHandler";
122     private static final long EXPIRES_IN = 432000; // five days
123     private static final Pattern CHARSET_PATTERN = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)");
124     private static final String DEVICE_TYPE = "A2IVLV5VM2W81";
125
126     private final Logger logger = LoggerFactory.getLogger(Connection.class);
127
128     protected final ScheduledExecutorService scheduler = ThreadPoolManager.getScheduledPool(THING_THREADPOOL_NAME);
129
130     private final Random rand = new Random();
131     private final CookieManager cookieManager = new CookieManager();
132     private final Gson gson;
133     private final Gson gsonWithNullSerialization;
134
135     private String amazonSite = "amazon.com";
136     private String alexaServer = "https://alexa.amazon.com";
137     private final String userAgent;
138     private String frc;
139     private String serial;
140     private String deviceId;
141
142     private @Nullable String refreshToken;
143     private @Nullable Date loginTime;
144     private @Nullable Date verifyTime;
145     private long renewTime = 0;
146     private @Nullable String deviceName;
147     private @Nullable String accountCustomerId;
148     private @Nullable String customerName;
149
150     private Map<Integer, AnnouncementWrapper> announcements = Collections.synchronizedMap(new LinkedHashMap<>());
151     private Map<Integer, TextToSpeech> textToSpeeches = Collections.synchronizedMap(new LinkedHashMap<>());
152     private Map<Integer, TextCommand> textCommands = Collections.synchronizedMap(new LinkedHashMap<>());
153
154     private Map<Integer, Volume> volumes = Collections.synchronizedMap(new LinkedHashMap<>());
155     private Map<String, LinkedBlockingQueue<QueueObject>> devices = Collections.synchronizedMap(new LinkedHashMap<>());
156
157     private final Map<TimerType, ScheduledFuture<?>> timers = new ConcurrentHashMap<>();
158     private final Map<TimerType, Lock> locks = new ConcurrentHashMap<>();
159
160     private enum TimerType {
161         ANNOUNCEMENT,
162         TTS,
163         VOLUME,
164         DEVICES,
165         TEXT_COMMAND
166     }
167
168     public Connection(@Nullable Connection oldConnection, Gson gson) {
169         this.gson = gson;
170         String frc = null;
171         String serial = null;
172         String deviceId = null;
173         if (oldConnection != null) {
174             deviceId = oldConnection.getDeviceId();
175             frc = oldConnection.getFrc();
176             serial = oldConnection.getSerial();
177         }
178         if (frc != null) {
179             this.frc = frc;
180         } else {
181             // generate frc
182             byte[] frcBinary = new byte[313];
183             rand.nextBytes(frcBinary);
184             this.frc = Base64.getEncoder().encodeToString(frcBinary);
185         }
186         if (serial != null) {
187             this.serial = serial;
188         } else {
189             // generate serial
190             byte[] serialBinary = new byte[16];
191             rand.nextBytes(serialBinary);
192             this.serial = HexUtils.bytesToHex(serialBinary);
193         }
194         if (deviceId != null) {
195             this.deviceId = deviceId;
196         } else {
197             this.deviceId = generateDeviceId();
198         }
199
200         // build user agent
201         this.userAgent = "AmazonWebView/Amazon Alexa/2.2.223830.0/iOS/11.4.1/iPhone";
202         GsonBuilder gsonBuilder = new GsonBuilder();
203         gsonWithNullSerialization = gsonBuilder.create();
204
205         replaceTimer(TimerType.DEVICES,
206                 scheduler.scheduleWithFixedDelay(this::handleExecuteSequenceNode, 0, 500, TimeUnit.MILLISECONDS));
207     }
208
209     /**
210      * Generate a new device id
211      * <p>
212      * The device id consists of 16 random bytes in upper-case hex format, a # as separator and a fixed DEVICE_TYPE
213      *
214      * @return a string containing the new device-id
215      */
216     private String generateDeviceId() {
217         byte[] bytes = new byte[16];
218         rand.nextBytes(bytes);
219         String hexStr = HexUtils.bytesToHex(bytes).toUpperCase() + "#" + DEVICE_TYPE;
220         return HexUtils.bytesToHex(hexStr.getBytes());
221     }
222
223     /**
224      * Check if deviceId is valid (consisting of hex(hex(16 random bytes)) + "#" + DEVICE_TYPE)
225      *
226      * @param deviceId the deviceId
227      * @return true if valid, false if invalid
228      */
229     private boolean checkDeviceIdIsValid(@Nullable String deviceId) {
230         if (deviceId != null && deviceId.matches("^[0-9a-fA-F]{92}$")) {
231             String hexString = new String(HexUtils.hexToBytes(deviceId));
232             if (hexString.matches("^[0-9A-F]{32}#" + DEVICE_TYPE + "$")) {
233                 return true;
234             }
235         }
236         return false;
237     }
238
239     private void setAmazonSite(@Nullable String amazonSite) {
240         String correctedAmazonSite = amazonSite != null ? amazonSite : "amazon.com";
241         if (correctedAmazonSite.toLowerCase().startsWith("http://")) {
242             correctedAmazonSite = correctedAmazonSite.substring(7);
243         }
244         if (correctedAmazonSite.toLowerCase().startsWith("https://")) {
245             correctedAmazonSite = correctedAmazonSite.substring(8);
246         }
247         if (correctedAmazonSite.toLowerCase().startsWith("www.")) {
248             correctedAmazonSite = correctedAmazonSite.substring(4);
249         }
250         if (correctedAmazonSite.toLowerCase().startsWith("alexa.")) {
251             correctedAmazonSite = correctedAmazonSite.substring(6);
252         }
253         this.amazonSite = correctedAmazonSite;
254         alexaServer = "https://alexa." + this.amazonSite;
255     }
256
257     public @Nullable Date tryGetLoginTime() {
258         return loginTime;
259     }
260
261     public @Nullable Date tryGetVerifyTime() {
262         return verifyTime;
263     }
264
265     public String getFrc() {
266         return frc;
267     }
268
269     public String getSerial() {
270         return serial;
271     }
272
273     public String getDeviceId() {
274         return deviceId;
275     }
276
277     public String getAmazonSite() {
278         return amazonSite;
279     }
280
281     public String getAlexaServer() {
282         return alexaServer;
283     }
284
285     public String getDeviceName() {
286         String deviceName = this.deviceName;
287         if (deviceName == null) {
288             return "Unknown";
289         }
290         return deviceName;
291     }
292
293     public String getCustomerId() {
294         String customerId = this.accountCustomerId;
295         if (customerId == null) {
296             return "Unknown";
297         }
298         return customerId;
299     }
300
301     public String getCustomerName() {
302         String customerName = this.customerName;
303         if (customerName == null) {
304             return "Unknown";
305         }
306         return customerName;
307     }
308
309     public boolean isSequenceNodeQueueRunning() {
310         return devices.values().stream().anyMatch(
311                 (queueObjects) -> (queueObjects.stream().anyMatch(queueObject -> queueObject.future != null)));
312     }
313
314     public String serializeLoginData() {
315         Date loginTime = this.loginTime;
316         if (refreshToken == null || loginTime == null) {
317             return "";
318         }
319         StringBuilder builder = new StringBuilder();
320         builder.append("7\n"); // version
321         builder.append(frc);
322         builder.append("\n");
323         builder.append(serial);
324         builder.append("\n");
325         builder.append(deviceId);
326         builder.append("\n");
327         builder.append(refreshToken);
328         builder.append("\n");
329         builder.append(amazonSite);
330         builder.append("\n");
331         builder.append(deviceName);
332         builder.append("\n");
333         builder.append(accountCustomerId);
334         builder.append("\n");
335         builder.append(loginTime.getTime());
336         builder.append("\n");
337         List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
338         builder.append(cookies.size());
339         builder.append("\n");
340         for (HttpCookie cookie : cookies) {
341             writeValue(builder, cookie.getName());
342             writeValue(builder, cookie.getValue());
343             writeValue(builder, cookie.getComment());
344             writeValue(builder, cookie.getCommentURL());
345             writeValue(builder, cookie.getDomain());
346             writeValue(builder, cookie.getMaxAge());
347             writeValue(builder, cookie.getPath());
348             writeValue(builder, cookie.getPortlist());
349             writeValue(builder, cookie.getVersion());
350             writeValue(builder, cookie.getSecure());
351             writeValue(builder, cookie.getDiscard());
352         }
353         return builder.toString();
354     }
355
356     private void writeValue(StringBuilder builder, @Nullable Object value) {
357         if (value == null) {
358             builder.append('0');
359         } else {
360             builder.append('1');
361             builder.append("\n");
362             builder.append(value.toString());
363         }
364         builder.append("\n");
365     }
366
367     private String readValue(Scanner scanner) {
368         if (scanner.nextLine().equals("1")) {
369             String result = scanner.nextLine();
370             if (result != null) {
371                 return result;
372             }
373         }
374         return "";
375     }
376
377     public boolean tryRestoreLogin(@Nullable String data, @Nullable String overloadedDomain) {
378         Date loginTime = tryRestoreSessionData(data, overloadedDomain);
379         if (loginTime != null) {
380             try {
381                 if (verifyLogin()) {
382                     this.loginTime = loginTime;
383                     return true;
384                 }
385             } catch (IOException e) {
386                 return false;
387             } catch (URISyntaxException | InterruptedException e) {
388             }
389         }
390         return false;
391     }
392
393     private @Nullable Date tryRestoreSessionData(@Nullable String data, @Nullable String overloadedDomain) {
394         // verify store data
395         if (data == null || data.isEmpty()) {
396             return null;
397         }
398         Scanner scanner = new Scanner(data);
399         String version = scanner.nextLine();
400         // check if serialize version is supported
401         if (!"5".equals(version) && !"6".equals(version) && !"7".equals(version)) {
402             scanner.close();
403             return null;
404         }
405         int intVersion = Integer.parseInt(version);
406
407         frc = scanner.nextLine();
408         serial = scanner.nextLine();
409         deviceId = scanner.nextLine();
410
411         // Recreate session and cookies
412         refreshToken = scanner.nextLine();
413         String domain = scanner.nextLine();
414         if (overloadedDomain != null) {
415             domain = overloadedDomain;
416         }
417         setAmazonSite(domain);
418
419         deviceName = scanner.nextLine();
420
421         if (intVersion > 5) {
422             String accountCustomerId = scanner.nextLine();
423             // Note: version 5 have wrong customer id serialized.
424             // Only use it, if it at least version 6 of serialization
425             if (intVersion > 6) {
426                 if (!"null".equals(accountCustomerId)) {
427                     this.accountCustomerId = accountCustomerId;
428                 }
429             }
430         }
431
432         Date loginTime = new Date(Long.parseLong(scanner.nextLine()));
433         CookieStore cookieStore = cookieManager.getCookieStore();
434         cookieStore.removeAll();
435
436         Integer numberOfCookies = Integer.parseInt(scanner.nextLine());
437         for (Integer i = 0; i < numberOfCookies; i++) {
438             String name = readValue(scanner);
439             String value = readValue(scanner);
440
441             HttpCookie clientCookie = new HttpCookie(name, value);
442             clientCookie.setComment(readValue(scanner));
443             clientCookie.setCommentURL(readValue(scanner));
444             clientCookie.setDomain(readValue(scanner));
445             clientCookie.setMaxAge(Long.parseLong(readValue(scanner)));
446             clientCookie.setPath(readValue(scanner));
447             clientCookie.setPortlist(readValue(scanner));
448             clientCookie.setVersion(Integer.parseInt(readValue(scanner)));
449             clientCookie.setSecure(Boolean.parseBoolean(readValue(scanner)));
450             clientCookie.setDiscard(Boolean.parseBoolean(readValue(scanner)));
451
452             cookieStore.add(null, clientCookie);
453         }
454         scanner.close();
455         try {
456             checkRenewSession();
457
458             String accountCustomerId = this.accountCustomerId;
459             if (accountCustomerId == null || accountCustomerId.isEmpty()) {
460                 List<Device> devices = this.getDeviceList();
461                 accountCustomerId = devices.stream().filter(device -> serial.equals(device.serialNumber)).findAny()
462                         .map(device -> device.deviceOwnerCustomerId).orElse(null);
463                 if (accountCustomerId == null || accountCustomerId.isEmpty()) {
464                     accountCustomerId = devices.stream().filter(device -> "This Device".equals(device.accountName))
465                             .findAny().map(device -> {
466                                 serial = Objects.requireNonNullElse(device.serialNumber, serial);
467                                 return device.deviceOwnerCustomerId;
468                             }).orElse(null);
469                 }
470                 this.accountCustomerId = accountCustomerId;
471             }
472         } catch (URISyntaxException | IOException | InterruptedException | ConnectionException e) {
473             logger.debug("Getting account customer Id failed", e);
474         }
475         return loginTime;
476     }
477
478     private @Nullable Authentication tryGetBootstrap() throws IOException, URISyntaxException, InterruptedException {
479         HttpsURLConnection connection = makeRequest("GET", alexaServer + "/api/bootstrap", null, false, false, null, 0);
480         String contentType = connection.getContentType();
481         if (connection.getResponseCode() == 200 && contentType != null
482                 && contentType.toLowerCase().startsWith("application/json")) {
483             try {
484                 String bootstrapResultJson = convertStream(connection);
485                 JsonBootstrapResult result = parseJson(bootstrapResultJson, JsonBootstrapResult.class);
486                 if (result != null) {
487                     Authentication authentication = result.authentication;
488                     if (authentication != null && authentication.authenticated) {
489                         this.customerName = authentication.customerName;
490                         if (this.accountCustomerId == null) {
491                             this.accountCustomerId = authentication.customerId;
492                         }
493                         return authentication;
494                     }
495                 }
496             } catch (JsonSyntaxException | IllegalStateException e) {
497                 logger.info("No valid json received", e);
498                 return null;
499             }
500         }
501         return null;
502     }
503
504     public String convertStream(HttpsURLConnection connection) throws IOException {
505         InputStream input = connection.getInputStream();
506         if (input == null) {
507             return "";
508         }
509
510         InputStream readerStream;
511         if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) {
512             readerStream = new GZIPInputStream(connection.getInputStream());
513         } else {
514             readerStream = input;
515         }
516         String contentType = connection.getContentType();
517         String charSet = null;
518         if (contentType != null) {
519             Matcher m = CHARSET_PATTERN.matcher(contentType);
520             if (m.find()) {
521                 charSet = m.group(1).trim().toUpperCase();
522             }
523         }
524
525         Scanner inputScanner = charSet == null || charSet.isEmpty()
526                 ? new Scanner(readerStream, StandardCharsets.UTF_8.name())
527                 : new Scanner(readerStream, charSet);
528         Scanner scannerWithoutDelimiter = inputScanner.useDelimiter("\\A");
529         String result = scannerWithoutDelimiter.hasNext() ? scannerWithoutDelimiter.next() : null;
530         inputScanner.close();
531         scannerWithoutDelimiter.close();
532         input.close();
533         if (result == null) {
534             result = "";
535         }
536         return result;
537     }
538
539     public String makeRequestAndReturnString(String url) throws IOException, URISyntaxException, InterruptedException {
540         return makeRequestAndReturnString("GET", url, null, false, null);
541     }
542
543     public String makeRequestAndReturnString(String verb, String url, @Nullable String postData, boolean json,
544             @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException, InterruptedException {
545         HttpsURLConnection connection = makeRequest(verb, url, postData, json, true, customHeaders, 3);
546         String result = convertStream(connection);
547         logger.debug("Result of {} {}:{}", verb, url, result);
548         return result;
549     }
550
551     public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json,
552             boolean autoredirect, @Nullable Map<String, String> customHeaders, int badRequestRepeats)
553             throws IOException, URISyntaxException, InterruptedException {
554         String currentUrl = url;
555         int redirectCounter = 0;
556         int retryCounter = 0;
557         // loop for handling redirect and bad request, using automatic redirect is not
558         // possible, because all response headers must be catched
559         while (true) {
560             int code;
561             HttpsURLConnection connection = null;
562             try {
563                 logger.debug("Make request to {}", url);
564                 connection = (HttpsURLConnection) new URL(currentUrl).openConnection();
565                 connection.setRequestMethod(verb);
566                 connection.setRequestProperty("Accept-Language", "en-US");
567                 if (customHeaders == null || !customHeaders.containsKey("User-Agent")) {
568                     connection.setRequestProperty("User-Agent", userAgent);
569                 }
570                 connection.setRequestProperty("Accept-Encoding", "gzip");
571                 connection.setRequestProperty("DNT", "1");
572                 connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
573                 if (customHeaders != null) {
574                     for (String key : customHeaders.keySet()) {
575                         String value = customHeaders.get(key);
576                         if (value != null && !value.isEmpty()) {
577                             connection.setRequestProperty(key, value);
578                         }
579                     }
580                 }
581                 connection.setInstanceFollowRedirects(false);
582
583                 // add cookies
584                 URI uri = connection.getURL().toURI();
585
586                 if (customHeaders == null || !customHeaders.containsKey("Cookie")) {
587                     StringBuilder cookieHeaderBuilder = new StringBuilder();
588                     for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) {
589                         if (cookieHeaderBuilder.length() > 0) {
590                             cookieHeaderBuilder.append(";");
591                         }
592                         cookieHeaderBuilder.append(cookie.getName());
593                         cookieHeaderBuilder.append("=");
594                         cookieHeaderBuilder.append(cookie.getValue());
595                         if (cookie.getName().equals("csrf")) {
596                             connection.setRequestProperty("csrf", cookie.getValue());
597                         }
598
599                     }
600                     if (cookieHeaderBuilder.length() > 0) {
601                         String cookies = cookieHeaderBuilder.toString();
602                         connection.setRequestProperty("Cookie", cookies);
603                     }
604                 }
605                 if (postData != null) {
606                     logger.debug("{}: {}", verb, postData);
607                     // post data
608                     byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
609                     int postDataLength = postDataBytes.length;
610
611                     connection.setFixedLengthStreamingMode(postDataLength);
612
613                     if (json) {
614                         connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
615                     } else {
616                         connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
617                     }
618                     connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
619                     if ("POST".equals(verb)) {
620                         connection.setRequestProperty("Expect", "100-continue");
621                     }
622
623                     connection.setDoOutput(true);
624                     OutputStream outputStream = connection.getOutputStream();
625                     outputStream.write(postDataBytes);
626                     outputStream.close();
627                 }
628                 // handle result
629                 code = connection.getResponseCode();
630                 String location = null;
631
632                 // handle response headers
633                 Map<@Nullable String, List<String>> headerFields = connection.getHeaderFields();
634                 for (Map.Entry<@Nullable String, List<String>> header : headerFields.entrySet()) {
635                     String key = header.getKey();
636                     if (key != null && !key.isEmpty()) {
637                         if (key.equalsIgnoreCase("Set-Cookie")) {
638                             // store cookie
639                             for (String cookieHeader : header.getValue()) {
640                                 if (!cookieHeader.isEmpty()) {
641                                     List<HttpCookie> cookies = HttpCookie.parse(cookieHeader);
642                                     for (HttpCookie cookie : cookies) {
643                                         cookieManager.getCookieStore().add(uri, cookie);
644                                     }
645                                 }
646                             }
647                         }
648                         if (key.equalsIgnoreCase("Location")) {
649                             // get redirect location
650                             location = header.getValue().get(0);
651                             if (!location.isEmpty()) {
652                                 location = uri.resolve(location).toString();
653                                 // check for https
654                                 if (location.toLowerCase().startsWith("http://")) {
655                                     // always use https
656                                     location = "https://" + location.substring(7);
657                                     logger.debug("Redirect corrected to {}", location);
658                                 }
659                             }
660                         }
661                     }
662                 }
663                 if (code == 200) {
664                     logger.debug("Call to {} succeeded", url);
665                     return connection;
666                 } else if (code == 302 && location != null) {
667                     logger.debug("Redirected to {}", location);
668                     redirectCounter++;
669                     if (redirectCounter > 30) {
670                         throw new ConnectionException("Too many redirects");
671                     }
672                     currentUrl = location;
673                     if (autoredirect) {
674                         continue; // repeat with new location
675                     }
676                     return connection;
677                 } else {
678                     logger.debug("Retry call to {}", url);
679                     retryCounter++;
680                     if (retryCounter > badRequestRepeats) {
681                         throw new HttpException(code,
682                                 verb + " url '" + url + "' failed: " + connection.getResponseMessage());
683                     }
684                     Thread.sleep(2000);
685                 }
686             } catch (InterruptedException | InterruptedIOException e) {
687                 if (connection != null) {
688                     connection.disconnect();
689                 }
690                 logger.warn("Unable to wait for next call to {}", url, e);
691                 throw e;
692             } catch (IOException e) {
693                 if (connection != null) {
694                     connection.disconnect();
695                 }
696                 logger.warn("Request to url '{}' fails with unknown error", url, e);
697                 throw e;
698             } catch (Exception e) {
699                 if (connection != null) {
700                     connection.disconnect();
701                 }
702                 throw e;
703             }
704         }
705     }
706
707     public String registerConnectionAsApp(String oAutRedirectUrl)
708             throws ConnectionException, IOException, URISyntaxException, InterruptedException {
709         URI oAutRedirectUri = new URI(oAutRedirectUrl);
710
711         Map<String, String> queryParameters = new LinkedHashMap<>();
712         String query = oAutRedirectUri.getQuery();
713         String[] pairs = query.split("&");
714         for (String pair : pairs) {
715             int idx = pair.indexOf("=");
716             queryParameters.put(URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()),
717                     URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()));
718         }
719         String accessToken = queryParameters.get("openid.oa2.access_token");
720
721         Map<String, String> cookieMap = new HashMap<>();
722
723         List<JsonWebSiteCookie> webSiteCookies = new ArrayList<>();
724         for (HttpCookie cookie : getSessionCookies("https://www.amazon.com")) {
725             cookieMap.put(cookie.getName(), cookie.getValue());
726             webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue()));
727         }
728
729         JsonWebSiteCookie[] webSiteCookiesArray = new JsonWebSiteCookie[webSiteCookies.size()];
730         webSiteCookiesArray = webSiteCookies.toArray(webSiteCookiesArray);
731
732         JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc,
733                 webSiteCookiesArray);
734         String registerAppRequestJson = gson.toJson(registerAppRequest);
735
736         HashMap<String, String> registerHeaders = new HashMap<>();
737         registerHeaders.put("x-amzn-identity-auth-domain", "api.amazon.com");
738
739         String registerAppResultJson = makeRequestAndReturnString("POST", "https://api.amazon.com/auth/register",
740                 registerAppRequestJson, true, registerHeaders);
741         JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson, JsonRegisterAppResponse.class);
742
743         if (registerAppResponse == null) {
744             throw new ConnectionException("Error: No response received from register application");
745         }
746         Response response = registerAppResponse.response;
747         if (response == null) {
748             throw new ConnectionException("Error: No response received from register application");
749         }
750         Success success = response.success;
751         if (success == null) {
752             throw new ConnectionException("Error: No success received from register application");
753         }
754         Tokens tokens = success.tokens;
755         if (tokens == null) {
756             throw new ConnectionException("Error: No tokens received from register application");
757         }
758         Bearer bearer = tokens.bearer;
759         if (bearer == null) {
760             throw new ConnectionException("Error: No bearer received from register application");
761         }
762         String refreshToken = bearer.refreshToken;
763         this.refreshToken = refreshToken;
764         if (refreshToken == null || refreshToken.isEmpty()) {
765             throw new ConnectionException("Error: No refresh token received");
766         }
767         try {
768             exchangeToken();
769             // Check which is the owner domain
770             String usersMeResponseJson = makeRequestAndReturnString("GET",
771                     "https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null);
772             JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class);
773             if (usersMeResponse == null) {
774                 throw new IllegalArgumentException("Received no response on me-request");
775             }
776             URI uri = new URI(usersMeResponse.marketPlaceDomainName);
777             String host = uri.getHost();
778
779             // Switch to owner domain
780             setAmazonSite(host);
781             exchangeToken();
782             tryGetBootstrap();
783         } catch (Exception e) {
784             logout();
785             throw e;
786         }
787         String deviceName = null;
788         Extensions extensions = success.extensions;
789         if (extensions != null) {
790             DeviceInfo deviceInfo = extensions.deviceInfo;
791             if (deviceInfo != null) {
792                 deviceName = deviceInfo.deviceName;
793             }
794         }
795         if (deviceName == null) {
796             deviceName = "Unknown";
797         }
798         this.deviceName = deviceName;
799         return deviceName;
800     }
801
802     private void exchangeToken() throws IOException, URISyntaxException, InterruptedException {
803         this.renewTime = 0;
804         String cookiesJson = "{\"cookies\":{\"." + getAmazonSite() + "\":[]}}";
805         String cookiesBase64 = Base64.getEncoder().encodeToString(cookiesJson.getBytes());
806
807         String exchangePostData = "di.os.name=iOS&app_version=2.2.223830.0&domain=." + getAmazonSite()
808                 + "&source_token=" + URLEncoder.encode(this.refreshToken, "UTF8")
809                 + "&requested_token_type=auth_cookies&source_token_type=refresh_token&di.hw.version=iPhone&di.sdk.version=6.10.0&cookies="
810                 + cookiesBase64 + "&app_name=Amazon%20Alexa&di.os.version=11.4.1";
811
812         HashMap<String, String> exchangeTokenHeader = new HashMap<>();
813         exchangeTokenHeader.put("Cookie", "");
814
815         String exchangeTokenJson = makeRequestAndReturnString("POST",
816                 "https://www." + getAmazonSite() + "/ap/exchangetoken", exchangePostData, false, exchangeTokenHeader);
817         JsonExchangeTokenResponse exchangeTokenResponse = Objects
818                 .requireNonNull(gson.fromJson(exchangeTokenJson, JsonExchangeTokenResponse.class));
819
820         org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Response response = exchangeTokenResponse.response;
821         if (response != null) {
822             org.openhab.binding.amazonechocontrol.internal.jsons.JsonExchangeTokenResponse.Tokens tokens = response.tokens;
823             if (tokens != null) {
824                 Map<String, Cookie[]> cookiesMap = tokens.cookies;
825                 if (cookiesMap != null) {
826                     for (String domain : cookiesMap.keySet()) {
827                         Cookie[] cookies = cookiesMap.get(domain);
828                         if (cookies != null) {
829                             for (Cookie cookie : cookies) {
830                                 if (cookie != null) {
831                                     HttpCookie httpCookie = new HttpCookie(cookie.name, cookie.value);
832                                     httpCookie.setPath(cookie.path);
833                                     httpCookie.setDomain(domain);
834                                     Boolean secure = cookie.secure;
835                                     if (secure != null) {
836                                         httpCookie.setSecure(secure);
837                                     }
838                                     this.cookieManager.getCookieStore().add(null, httpCookie);
839                                 }
840                             }
841                         }
842                     }
843                 }
844             }
845         }
846         if (!verifyLogin()) {
847             throw new ConnectionException("Verify login failed after token exchange");
848         }
849         this.renewTime = (long) (System.currentTimeMillis() + Connection.EXPIRES_IN * 1000d / 0.8d); // start renew at
850     }
851
852     public boolean checkRenewSession() throws URISyntaxException, IOException, InterruptedException {
853         if (System.currentTimeMillis() >= this.renewTime) {
854             String renewTokenPostData = "app_name=Amazon%20Alexa&app_version=2.2.223830.0&di.sdk.version=6.10.0&source_token="
855                     + URLEncoder.encode(refreshToken, StandardCharsets.UTF_8.name())
856                     + "&package_name=com.amazon.echo&di.hw.version=iPhone&platform=iOS&requested_token_type=access_token&source_token_type=refresh_token&di.os.name=iOS&di.os.version=11.4.1&current_version=6.10.0";
857             String renewTokenResponseJson = makeRequestAndReturnString("POST", "https://api.amazon.com/auth/token",
858                     renewTokenPostData, false, null);
859             parseJson(renewTokenResponseJson, JsonRenewTokenResponse.class);
860
861             exchangeToken();
862             return true;
863         }
864         return false;
865     }
866
867     public boolean getIsLoggedIn() {
868         return loginTime != null;
869     }
870
871     public String getLoginPage() throws IOException, URISyntaxException, InterruptedException {
872         // clear session data
873         logout();
874
875         logger.debug("Start Login to {}", alexaServer);
876
877         if (!checkDeviceIdIsValid(deviceId)) {
878             deviceId = generateDeviceId();
879             logger.debug("Generating new device id (old device id had invalid format).");
880         }
881
882         String mapMdJson = "{\"device_user_dictionary\":[],\"device_registration_data\":{\"software_version\":\"1\"},\"app_identifier\":{\"app_version\":\"2.2.223830\",\"bundle_id\":\"com.amazon.echo\"}}";
883         String mapMdCookie = Base64.getEncoder().encodeToString(mapMdJson.getBytes());
884
885         cookieManager.getCookieStore().add(new URI("https://www.amazon.com"), new HttpCookie("map-md", mapMdCookie));
886         cookieManager.getCookieStore().add(new URI("https://www.amazon.com"), new HttpCookie("frc", frc));
887
888         Map<String, String> customHeaders = new HashMap<>();
889         customHeaders.put("authority", "www.amazon.com");
890         String loginFormHtml = makeRequestAndReturnString("GET", "https://www.amazon.com"
891                 + "/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:"
892                 + deviceId
893                 + "&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=token&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access",
894                 null, false, customHeaders);
895
896         logger.debug("Received login form {}", loginFormHtml);
897         return loginFormHtml;
898     }
899
900     public boolean verifyLogin() throws IOException, URISyntaxException, InterruptedException {
901         if (this.refreshToken == null) {
902             return false;
903         }
904         Authentication authentication = tryGetBootstrap();
905         if (authentication != null && authentication.authenticated) {
906             verifyTime = new Date();
907             if (loginTime == null) {
908                 loginTime = verifyTime;
909             }
910             return true;
911         }
912         return false;
913     }
914
915     public List<HttpCookie> getSessionCookies() {
916         try {
917             return cookieManager.getCookieStore().get(new URI(alexaServer));
918         } catch (URISyntaxException e) {
919             return new ArrayList<>();
920         }
921     }
922
923     public List<HttpCookie> getSessionCookies(String server) {
924         try {
925             return cookieManager.getCookieStore().get(new URI(server));
926         } catch (URISyntaxException e) {
927             return new ArrayList<>();
928         }
929     }
930
931     private void replaceTimer(TimerType type, @Nullable ScheduledFuture<?> newTimer) {
932         timers.compute(type, (timerType, oldTimer) -> {
933             if (oldTimer != null) {
934                 oldTimer.cancel(true);
935             }
936             return newTimer;
937         });
938     }
939
940     public void logout() {
941         cookieManager.getCookieStore().removeAll();
942         // reset all members
943         refreshToken = null;
944         loginTime = null;
945         verifyTime = null;
946         deviceName = null;
947
948         replaceTimer(TimerType.ANNOUNCEMENT, null);
949         announcements.clear();
950         replaceTimer(TimerType.TTS, null);
951         textToSpeeches.clear();
952         replaceTimer(TimerType.VOLUME, null);
953         volumes.clear();
954         replaceTimer(TimerType.DEVICES, null);
955         textCommands.clear();
956         replaceTimer(TimerType.TTS, null);
957
958         devices.values().forEach((queueObjects) -> {
959             queueObjects.forEach((queueObject) -> {
960                 Future<?> future = queueObject.future;
961                 if (future != null) {
962                     future.cancel(true);
963                     queueObject.future = null;
964                 }
965             });
966         });
967     }
968
969     // parser
970     private <T> @Nullable T parseJson(String json, Class<T> type) throws JsonSyntaxException, IllegalStateException {
971         try {
972             return gson.fromJson(json, type);
973         } catch (JsonParseException | IllegalStateException e) {
974             logger.warn("Parsing json failed: {}", json, e);
975             throw e;
976         }
977     }
978
979     // commands and states
980     public WakeWord[] getWakeWords() {
981         String json;
982         try {
983             json = makeRequestAndReturnString(alexaServer + "/api/wake-word?cached=true");
984             JsonWakeWords wakeWords = parseJson(json, JsonWakeWords.class);
985             if (wakeWords != null) {
986                 WakeWord[] result = wakeWords.wakeWords;
987                 if (result != null) {
988                     return result;
989                 }
990             }
991         } catch (IOException | URISyntaxException | InterruptedException e) {
992             logger.info("getting wakewords failed", e);
993         }
994         return new WakeWord[0];
995     }
996
997     public List<SmartHomeBaseDevice> getSmarthomeDeviceList()
998             throws IOException, URISyntaxException, InterruptedException {
999         try {
1000             String json = makeRequestAndReturnString(alexaServer + "/api/phoenix");
1001             logger.debug("getSmartHomeDevices result: {}", json);
1002
1003             JsonNetworkDetails networkDetails = parseJson(json, JsonNetworkDetails.class);
1004             if (networkDetails == null) {
1005                 throw new IllegalArgumentException("received no response on network detail request");
1006             }
1007             Object jsonObject = gson.fromJson(networkDetails.networkDetail, Object.class);
1008             List<SmartHomeBaseDevice> result = new ArrayList<>();
1009             searchSmartHomeDevicesRecursive(jsonObject, result);
1010
1011             return result;
1012         } catch (Exception e) {
1013             logger.warn("getSmartHomeDevices fails: {}", e.getMessage());
1014             throw e;
1015         }
1016     }
1017
1018     private void searchSmartHomeDevicesRecursive(@Nullable Object jsonNode, List<SmartHomeBaseDevice> devices) {
1019         if (jsonNode instanceof Map) {
1020             @SuppressWarnings("rawtypes")
1021             Map<String, Object> map = (Map) jsonNode;
1022             if (map.containsKey("entityId") && map.containsKey("friendlyName") && map.containsKey("actions")) {
1023                 // device node found, create type element and add it to the results
1024                 JsonElement element = gson.toJsonTree(jsonNode);
1025                 SmartHomeDevice shd = parseJson(element.toString(), SmartHomeDevice.class);
1026                 if (shd != null) {
1027                     devices.add(shd);
1028                 }
1029             } else if (map.containsKey("applianceGroupName")) {
1030                 JsonElement element = gson.toJsonTree(jsonNode);
1031                 SmartHomeGroup shg = parseJson(element.toString(), SmartHomeGroup.class);
1032                 if (shg != null) {
1033                     devices.add(shg);
1034                 }
1035             } else {
1036                 map.values().forEach(value -> searchSmartHomeDevicesRecursive(value, devices));
1037             }
1038         }
1039     }
1040
1041     public List<Device> getDeviceList() throws IOException, URISyntaxException, InterruptedException {
1042         JsonDevices devices = Objects.requireNonNull(parseJson(getDeviceListJson(), JsonDevices.class));
1043         logger.trace("Devices {}", devices.devices);
1044
1045         // @Nullable because of a limitation of the null-checker, we filter null-serialNumbers before
1046         Set<@Nullable String> serialNumbers = ConcurrentHashMap.newKeySet();
1047         return devices.devices.stream().filter(d -> d.serialNumber != null && serialNumbers.add(d.serialNumber))
1048                 .collect(Collectors.toList());
1049     }
1050
1051     public String getDeviceListJson() throws IOException, URISyntaxException, InterruptedException {
1052         String json = makeRequestAndReturnString(alexaServer + "/api/devices-v2/device?cached=false");
1053         return json;
1054     }
1055
1056     public Map<String, JsonArray> getSmartHomeDeviceStatesJson(Set<String> applianceIds)
1057             throws IOException, URISyntaxException, InterruptedException {
1058         JsonObject requestObject = new JsonObject();
1059         JsonArray stateRequests = new JsonArray();
1060         for (String applianceId : applianceIds) {
1061             JsonObject stateRequest = new JsonObject();
1062             stateRequest.addProperty("entityId", applianceId);
1063             stateRequest.addProperty("entityType", "APPLIANCE");
1064             stateRequests.add(stateRequest);
1065         }
1066         requestObject.add("stateRequests", stateRequests);
1067         String requestBody = requestObject.toString();
1068         String json = makeRequestAndReturnString("POST", alexaServer + "/api/phoenix/state", requestBody, true, null);
1069         logger.trace("Requested {} and received {}", requestBody, json);
1070
1071         JsonObject responseObject = Objects.requireNonNull(gson.fromJson(json, JsonObject.class));
1072         JsonArray deviceStates = (JsonArray) responseObject.get("deviceStates");
1073         Map<String, JsonArray> result = new HashMap<>();
1074         for (JsonElement deviceState : deviceStates) {
1075             JsonObject deviceStateObject = deviceState.getAsJsonObject();
1076             JsonObject entity = deviceStateObject.get("entity").getAsJsonObject();
1077             String applicanceId = entity.get("entityId").getAsString();
1078             JsonElement capabilityState = deviceStateObject.get("capabilityStates");
1079             if (capabilityState != null && capabilityState.isJsonArray()) {
1080                 result.put(applicanceId, capabilityState.getAsJsonArray());
1081             }
1082         }
1083         return result;
1084     }
1085
1086     public @Nullable JsonPlayerState getPlayer(Device device)
1087             throws IOException, URISyntaxException, InterruptedException {
1088         String json = makeRequestAndReturnString(alexaServer + "/api/np/player?deviceSerialNumber="
1089                 + device.serialNumber + "&deviceType=" + device.deviceType + "&screenWidth=1440");
1090         JsonPlayerState playerState = parseJson(json, JsonPlayerState.class);
1091         return playerState;
1092     }
1093
1094     public @Nullable JsonMediaState getMediaState(Device device)
1095             throws IOException, URISyntaxException, InterruptedException {
1096         String json = makeRequestAndReturnString(alexaServer + "/api/media/state?deviceSerialNumber="
1097                 + device.serialNumber + "&deviceType=" + device.deviceType);
1098         JsonMediaState mediaState = parseJson(json, JsonMediaState.class);
1099         return mediaState;
1100     }
1101
1102     public Activity[] getActivities(int number, @Nullable Long startTime) {
1103         String json;
1104         try {
1105             json = makeRequestAndReturnString(alexaServer + "/api/activities?startTime="
1106                     + (startTime != null ? startTime : "") + "&size=" + number + "&offset=1");
1107             JsonActivities activities = parseJson(json, JsonActivities.class);
1108             if (activities != null) {
1109                 Activity[] activiesArray = activities.activities;
1110                 if (activiesArray != null) {
1111                     return activiesArray;
1112                 }
1113             }
1114         } catch (IOException | URISyntaxException | InterruptedException e) {
1115             logger.info("getting activities failed", e);
1116         }
1117         return new Activity[0];
1118     }
1119
1120     public @Nullable JsonBluetoothStates getBluetoothConnectionStates() {
1121         String json;
1122         try {
1123             json = makeRequestAndReturnString(alexaServer + "/api/bluetooth?cached=true");
1124         } catch (IOException | URISyntaxException | InterruptedException e) {
1125             logger.debug("failed to get bluetooth state: {}", e.getMessage());
1126             return new JsonBluetoothStates();
1127         }
1128         JsonBluetoothStates bluetoothStates = parseJson(json, JsonBluetoothStates.class);
1129         return bluetoothStates;
1130     }
1131
1132     public @Nullable JsonPlaylists getPlaylists(Device device)
1133             throws IOException, URISyntaxException, InterruptedException {
1134         String json = makeRequestAndReturnString(
1135                 alexaServer + "/api/cloudplayer/playlists?deviceSerialNumber=" + device.serialNumber + "&deviceType="
1136                         + device.deviceType + "&mediaOwnerCustomerId=" + getCustomerId(device.deviceOwnerCustomerId));
1137         JsonPlaylists playlists = parseJson(json, JsonPlaylists.class);
1138         return playlists;
1139     }
1140
1141     public void command(Device device, String command) throws IOException, URISyntaxException, InterruptedException {
1142         String url = alexaServer + "/api/np/command?deviceSerialNumber=" + device.serialNumber + "&deviceType="
1143                 + device.deviceType;
1144         makeRequest("POST", url, command, true, true, null, 0);
1145     }
1146
1147     public void smartHomeCommand(String entityId, String action) throws IOException, InterruptedException {
1148         smartHomeCommand(entityId, action, null, null);
1149     }
1150
1151     public void smartHomeCommand(String entityId, String action, @Nullable String property, @Nullable Object value)
1152             throws IOException, InterruptedException {
1153         String url = alexaServer + "/api/phoenix/state";
1154
1155         JsonObject json = new JsonObject();
1156         JsonArray controlRequests = new JsonArray();
1157         JsonObject controlRequest = new JsonObject();
1158         controlRequest.addProperty("entityId", entityId);
1159         controlRequest.addProperty("entityType", "APPLIANCE");
1160         JsonObject parameters = new JsonObject();
1161         parameters.addProperty("action", action);
1162         if (property != null) {
1163             if (value instanceof QuantityType<?>) {
1164                 parameters.addProperty(property + ".value", ((QuantityType<?>) value).floatValue());
1165                 parameters.addProperty(property + ".scale",
1166                         ((QuantityType<?>) value).getUnit().equals(SIUnits.CELSIUS) ? "celsius" : "fahrenheit");
1167             } else if (value instanceof Boolean) {
1168                 parameters.addProperty(property, (boolean) value);
1169             } else if (value instanceof String) {
1170                 parameters.addProperty(property, (String) value);
1171             } else if (value instanceof Number) {
1172                 parameters.addProperty(property, (Number) value);
1173             } else if (value instanceof Character) {
1174                 parameters.addProperty(property, (Character) value);
1175             } else if (value instanceof JsonElement) {
1176                 parameters.add(property, (JsonElement) value);
1177             }
1178         }
1179         controlRequest.add("parameters", parameters);
1180         controlRequests.add(controlRequest);
1181         json.add("controlRequests", controlRequests);
1182
1183         String requestBody = json.toString();
1184         try {
1185             String resultBody = makeRequestAndReturnString("PUT", url, requestBody, true, null);
1186             logger.trace("Request '{}' resulted in '{}", requestBody, resultBody);
1187             JsonObject result = parseJson(resultBody, JsonObject.class);
1188             if (result != null) {
1189                 JsonElement errors = result.get("errors");
1190                 if (errors != null && errors.isJsonArray()) {
1191                     JsonArray errorList = errors.getAsJsonArray();
1192                     if (errorList.size() > 0) {
1193                         logger.warn("Smart home device command failed. The request '{}' resulted in error(s): {}",
1194                                 requestBody, StreamSupport.stream(errorList.spliterator(), false)
1195                                         .map(JsonElement::toString).collect(Collectors.joining(" / ")));
1196                     }
1197                 }
1198             }
1199         } catch (URISyntaxException e) {
1200             logger.warn("URL '{}' has invalid format for request '{}': {}", url, requestBody, e.getMessage());
1201         }
1202     }
1203
1204     public void notificationVolume(Device device, int volume)
1205             throws IOException, URISyntaxException, InterruptedException {
1206         String url = alexaServer + "/api/device-notification-state/" + device.deviceType + "/" + device.softwareVersion
1207                 + "/" + device.serialNumber;
1208         String command = "{\"deviceSerialNumber\":\"" + device.serialNumber + "\",\"deviceType\":\"" + device.deviceType
1209                 + "\",\"softwareVersion\":\"" + device.softwareVersion + "\",\"volumeLevel\":" + volume + "}";
1210         makeRequest("PUT", url, command, true, true, null, 0);
1211     }
1212
1213     public void ascendingAlarm(Device device, boolean ascendingAlarm)
1214             throws IOException, URISyntaxException, InterruptedException {
1215         String url = alexaServer + "/api/ascending-alarm/" + device.serialNumber;
1216         String command = "{\"ascendingAlarmEnabled\":" + (ascendingAlarm ? "true" : "false")
1217                 + ",\"deviceSerialNumber\":\"" + device.serialNumber + "\",\"deviceType\":\"" + device.deviceType
1218                 + "\",\"deviceAccountId\":null}";
1219         makeRequest("PUT", url, command, true, true, null, 0);
1220     }
1221
1222     public DeviceNotificationState[] getDeviceNotificationStates() {
1223         String json;
1224         try {
1225             json = makeRequestAndReturnString(alexaServer + "/api/device-notification-state");
1226             JsonDeviceNotificationState result = parseJson(json, JsonDeviceNotificationState.class);
1227             if (result != null) {
1228                 DeviceNotificationState[] deviceNotificationStates = result.deviceNotificationStates;
1229                 if (deviceNotificationStates != null) {
1230                     return deviceNotificationStates;
1231                 }
1232             }
1233         } catch (IOException | URISyntaxException | InterruptedException e) {
1234             logger.info("Error getting device notification states", e);
1235         }
1236         return new DeviceNotificationState[0];
1237     }
1238
1239     public AscendingAlarmModel[] getAscendingAlarm() {
1240         String json;
1241         try {
1242             json = makeRequestAndReturnString(alexaServer + "/api/ascending-alarm");
1243             JsonAscendingAlarm result = parseJson(json, JsonAscendingAlarm.class);
1244             if (result != null) {
1245                 AscendingAlarmModel[] ascendingAlarmModelList = result.ascendingAlarmModelList;
1246                 if (ascendingAlarmModelList != null) {
1247                     return ascendingAlarmModelList;
1248                 }
1249             }
1250         } catch (IOException | URISyntaxException | InterruptedException e) {
1251             logger.info("Error getting device notification states", e);
1252         }
1253         return new AscendingAlarmModel[0];
1254     }
1255
1256     public void bluetooth(Device device, @Nullable String address)
1257             throws IOException, URISyntaxException, InterruptedException {
1258         if (address == null || address.isEmpty()) {
1259             // disconnect
1260             makeRequest("POST",
1261                     alexaServer + "/api/bluetooth/disconnect-sink/" + device.deviceType + "/" + device.serialNumber, "",
1262                     true, true, null, 0);
1263         } else {
1264             makeRequest("POST",
1265                     alexaServer + "/api/bluetooth/pair-sink/" + device.deviceType + "/" + device.serialNumber,
1266                     "{\"bluetoothDeviceAddress\":\"" + address + "\"}", true, true, null, 0);
1267         }
1268     }
1269
1270     private @Nullable String getCustomerId(@Nullable String defaultId) {
1271         String accountCustomerId = this.accountCustomerId;
1272         return accountCustomerId == null || accountCustomerId.isEmpty() ? defaultId : accountCustomerId;
1273     }
1274
1275     public void playRadio(Device device, @Nullable String stationId)
1276             throws IOException, URISyntaxException, InterruptedException {
1277         if (stationId == null || stationId.isEmpty()) {
1278             command(device, "{\"type\":\"PauseCommand\"}");
1279         } else {
1280             makeRequest("POST",
1281                     alexaServer + "/api/tunein/queue-and-play?deviceSerialNumber=" + device.serialNumber
1282                             + "&deviceType=" + device.deviceType + "&guideId=" + stationId
1283                             + "&contentType=station&callSign=&mediaOwnerCustomerId="
1284                             + getCustomerId(device.deviceOwnerCustomerId),
1285                     "", true, true, null, 0);
1286         }
1287     }
1288
1289     public void playAmazonMusicTrack(Device device, @Nullable String trackId)
1290             throws IOException, URISyntaxException, InterruptedException {
1291         if (trackId == null || trackId.isEmpty()) {
1292             command(device, "{\"type\":\"PauseCommand\"}");
1293         } else {
1294             String command = "{\"trackId\":\"" + trackId + "\",\"playQueuePrime\":true}";
1295             makeRequest("POST",
1296                     alexaServer + "/api/cloudplayer/queue-and-play?deviceSerialNumber=" + device.serialNumber
1297                             + "&deviceType=" + device.deviceType + "&mediaOwnerCustomerId="
1298                             + getCustomerId(device.deviceOwnerCustomerId) + "&shuffle=false",
1299                     command, true, true, null, 0);
1300         }
1301     }
1302
1303     public void playAmazonMusicPlayList(Device device, @Nullable String playListId)
1304             throws IOException, URISyntaxException, InterruptedException {
1305         if (playListId == null || playListId.isEmpty()) {
1306             command(device, "{\"type\":\"PauseCommand\"}");
1307         } else {
1308             String command = "{\"playlistId\":\"" + playListId + "\",\"playQueuePrime\":true}";
1309             makeRequest("POST",
1310                     alexaServer + "/api/cloudplayer/queue-and-play?deviceSerialNumber=" + device.serialNumber
1311                             + "&deviceType=" + device.deviceType + "&mediaOwnerCustomerId="
1312                             + getCustomerId(device.deviceOwnerCustomerId) + "&shuffle=false",
1313                     command, true, true, null, 0);
1314         }
1315     }
1316
1317     public void announcement(Device device, String speak, String bodyText, @Nullable String title,
1318             @Nullable Integer ttsVolume, @Nullable Integer standardVolume) {
1319         String plainSpeak = speak.replaceAll("<.+?>", " ").replaceAll("\\s+", " ").trim();
1320         String plainBody = bodyText.replaceAll("<.+?>", " ").replaceAll("\\s+", " ").trim();
1321
1322         if (plainSpeak.isEmpty() && plainBody.isEmpty()) {
1323             // if there is neither a bodytext nor (except tags) a speaktext, we have nothing to announce
1324             return;
1325         }
1326
1327         // we lock announcements until we have finished adding this one
1328         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.ANNOUNCEMENT, k -> new ReentrantLock()));
1329         lock.lock();
1330         try {
1331             AnnouncementWrapper announcement = Objects.requireNonNull(announcements.computeIfAbsent(
1332                     Objects.hash(speak, plainBody, title), k -> new AnnouncementWrapper(speak, plainBody, title)));
1333             announcement.devices.add(device);
1334             announcement.ttsVolumes.add(ttsVolume);
1335             announcement.standardVolumes.add(standardVolume);
1336
1337             // schedule an announcement only if it has not been scheduled before
1338             timers.computeIfAbsent(TimerType.ANNOUNCEMENT,
1339                     k -> scheduler.schedule(this::sendAnnouncement, 500, TimeUnit.MILLISECONDS));
1340         } finally {
1341             lock.unlock();
1342         }
1343     }
1344
1345     private void sendAnnouncement() {
1346         // we lock new announcements until we have dispatched everything
1347         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.ANNOUNCEMENT, k -> new ReentrantLock()));
1348         lock.lock();
1349         try {
1350             Iterator<AnnouncementWrapper> iterator = announcements.values().iterator();
1351             while (iterator.hasNext()) {
1352                 AnnouncementWrapper announcement = iterator.next();
1353                 try {
1354                     List<Device> devices = announcement.devices;
1355                     if (!devices.isEmpty()) {
1356                         JsonAnnouncementContent content = new JsonAnnouncementContent(announcement);
1357
1358                         Map<String, Object> parameters = new HashMap<>();
1359                         parameters.put("expireAfter", "PT5S");
1360                         parameters.put("content", new JsonAnnouncementContent[] { content });
1361                         parameters.put("target", new JsonAnnouncementTarget(devices));
1362
1363                         String customerId = getCustomerId(devices.get(0).deviceOwnerCustomerId);
1364                         if (customerId != null) {
1365                             parameters.put("customerId", customerId);
1366                         }
1367                         executeSequenceCommandWithVolume(devices, "AlexaAnnouncement", parameters,
1368                                 announcement.ttsVolumes, announcement.standardVolumes);
1369                     }
1370                 } catch (Exception e) {
1371                     logger.warn("send announcement fails with unexpected error", e);
1372                 }
1373                 iterator.remove();
1374             }
1375         } finally {
1376             // the timer is done anyway immediately after we unlock
1377             timers.remove(TimerType.ANNOUNCEMENT);
1378             lock.unlock();
1379         }
1380     }
1381
1382     public void textToSpeech(Device device, String text, @Nullable Integer ttsVolume,
1383             @Nullable Integer standardVolume) {
1384         if (text.replaceAll("<.+?>", "").replaceAll("\\s+", " ").trim().isEmpty()) {
1385             return;
1386         }
1387
1388         // we lock TTS until we have finished adding this one
1389         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.TTS, k -> new ReentrantLock()));
1390         lock.lock();
1391         try {
1392             TextToSpeech textToSpeech = Objects
1393                     .requireNonNull(textToSpeeches.computeIfAbsent(Objects.hash(text), k -> new TextToSpeech(text)));
1394             textToSpeech.devices.add(device);
1395             textToSpeech.ttsVolumes.add(ttsVolume);
1396             textToSpeech.standardVolumes.add(standardVolume);
1397             // schedule a TTS only if it has not been scheduled before
1398             timers.computeIfAbsent(TimerType.TTS,
1399                     k -> scheduler.schedule(this::sendTextToSpeech, 500, TimeUnit.MILLISECONDS));
1400         } finally {
1401             lock.unlock();
1402         }
1403     }
1404
1405     private void sendTextToSpeech() {
1406         // we lock new TTS until we have dispatched everything
1407         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.TTS, k -> new ReentrantLock()));
1408         lock.lock();
1409         try {
1410             Iterator<TextToSpeech> iterator = textToSpeeches.values().iterator();
1411             while (iterator.hasNext()) {
1412                 TextToSpeech textToSpeech = iterator.next();
1413                 try {
1414                     List<Device> devices = textToSpeech.devices;
1415                     if (!devices.isEmpty()) {
1416                         String text = textToSpeech.text;
1417                         Map<String, Object> parameters = Map.of("textToSpeak", text);
1418                         executeSequenceCommandWithVolume(devices, "Alexa.Speak", parameters, textToSpeech.ttsVolumes,
1419                                 textToSpeech.standardVolumes);
1420                     }
1421                 } catch (Exception e) {
1422                     logger.warn("send textToSpeech fails with unexpected error", e);
1423                 }
1424                 iterator.remove();
1425             }
1426         } finally {
1427             // the timer is done anyway immediately after we unlock
1428             timers.remove(TimerType.TTS);
1429             lock.unlock();
1430         }
1431     }
1432
1433     public void textCommand(Device device, String text, @Nullable Integer ttsVolume, @Nullable Integer standardVolume) {
1434         if (text.replaceAll("<.+?>", "").replaceAll("\\s+", " ").trim().isEmpty()) {
1435             return;
1436         }
1437
1438         // we lock TextCommands until we have finished adding this one
1439         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.TEXT_COMMAND, k -> new ReentrantLock()));
1440         lock.lock();
1441         try {
1442             TextCommand textCommand = Objects
1443                     .requireNonNull(textCommands.computeIfAbsent(Objects.hash(text), k -> new TextCommand(text)));
1444             textCommand.devices.add(device);
1445             textCommand.ttsVolumes.add(ttsVolume);
1446             textCommand.standardVolumes.add(standardVolume);
1447             // schedule a TextCommand only if it has not been scheduled before
1448             timers.computeIfAbsent(TimerType.TEXT_COMMAND,
1449                     k -> scheduler.schedule(this::sendTextCommand, 500, TimeUnit.MILLISECONDS));
1450         } finally {
1451             lock.unlock();
1452         }
1453     }
1454
1455     private synchronized void sendTextCommand() {
1456         // we lock new TTS until we have dispatched everything
1457         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.TEXT_COMMAND, k -> new ReentrantLock()));
1458         lock.lock();
1459
1460         try {
1461             Iterator<TextCommand> iterator = textCommands.values().iterator();
1462             while (iterator.hasNext()) {
1463                 TextCommand textCommand = iterator.next();
1464                 try {
1465                     List<Device> devices = textCommand.devices;
1466                     if (!devices.isEmpty()) {
1467                         String text = textCommand.text;
1468                         Map<String, Object> parameters = Map.of("text", text);
1469                         executeSequenceCommandWithVolume(devices, "Alexa.TextCommand", parameters,
1470                                 textCommand.ttsVolumes, textCommand.standardVolumes);
1471                     }
1472                 } catch (Exception e) {
1473                     logger.warn("send textCommand fails with unexpected error", e);
1474                 }
1475                 iterator.remove();
1476             }
1477         } finally {
1478             // the timer is done anyway immediately after we unlock
1479             timers.remove(TimerType.TEXT_COMMAND);
1480             lock.unlock();
1481         }
1482     }
1483
1484     public void volume(Device device, int vol) {
1485         // we lock volume until we have finished adding this one
1486         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.VOLUME, k -> new ReentrantLock()));
1487         lock.lock();
1488         try {
1489             Volume volume = Objects.requireNonNull(volumes.computeIfAbsent(vol, k -> new Volume(vol)));
1490             volume.devices.add(device);
1491             volume.volumes.add(vol);
1492             // schedule a TTS only if it has not been scheduled before
1493             timers.computeIfAbsent(TimerType.VOLUME,
1494                     k -> scheduler.schedule(this::sendVolume, 500, TimeUnit.MILLISECONDS));
1495         } finally {
1496             lock.unlock();
1497         }
1498     }
1499
1500     private void sendVolume() {
1501         // we lock new volume until we have dispatched everything
1502         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.VOLUME, k -> new ReentrantLock()));
1503         lock.lock();
1504         try {
1505             Iterator<Volume> iterator = volumes.values().iterator();
1506             while (iterator.hasNext()) {
1507                 Volume volume = iterator.next();
1508                 try {
1509                     List<Device> devices = volume.devices;
1510                     if (!devices.isEmpty()) {
1511                         executeSequenceCommandWithVolume(devices, null, Map.of(), volume.volumes, List.of());
1512                     }
1513                 } catch (Exception e) {
1514                     logger.warn("send volume fails with unexpected error", e);
1515                 }
1516                 iterator.remove();
1517             }
1518         } finally {
1519             // the timer is done anyway immediately after we unlock
1520             timers.remove(TimerType.VOLUME);
1521             lock.unlock();
1522         }
1523     }
1524
1525     private void executeSequenceCommandWithVolume(List<Device> devices, @Nullable String command,
1526             Map<String, Object> parameters, List<@Nullable Integer> ttsVolumes,
1527             List<@Nullable Integer> standardVolumes) {
1528         JsonArray serialNodesToExecute = new JsonArray();
1529         JsonArray ttsVolumeNodesToExecute = new JsonArray();
1530         for (int i = 0; i < devices.size(); i++) {
1531             Integer ttsVolume = ttsVolumes.size() > i ? ttsVolumes.get(i) : null;
1532             Integer standardVolume = standardVolumes.size() > i ? standardVolumes.get(i) : null;
1533             if (ttsVolume != null && (standardVolume != null || !ttsVolume.equals(standardVolume))) {
1534                 ttsVolumeNodesToExecute.add(
1535                         createExecutionNode(devices.get(i), "Alexa.DeviceControls.Volume", Map.of("value", ttsVolume)));
1536             }
1537         }
1538         if (ttsVolumeNodesToExecute.size() > 0) {
1539             JsonObject parallelNodesToExecute = new JsonObject();
1540             parallelNodesToExecute.addProperty("@type", "com.amazon.alexa.behaviors.model.ParallelNode");
1541             parallelNodesToExecute.add("nodesToExecute", ttsVolumeNodesToExecute);
1542             serialNodesToExecute.add(parallelNodesToExecute);
1543         }
1544
1545         if (command != null && !parameters.isEmpty()) {
1546             JsonArray commandNodesToExecute = new JsonArray();
1547             if ("Alexa.Speak".equals(command) || "Alexa.TextCommand".equals(command)) {
1548                 for (Device device : devices) {
1549                     commandNodesToExecute.add(createExecutionNode(device, command, parameters));
1550                 }
1551             } else {
1552                 commandNodesToExecute.add(createExecutionNode(devices.get(0), command, parameters));
1553             }
1554             if (commandNodesToExecute.size() > 0) {
1555                 JsonObject parallelNodesToExecute = new JsonObject();
1556                 parallelNodesToExecute.addProperty("@type", "com.amazon.alexa.behaviors.model.ParallelNode");
1557                 parallelNodesToExecute.add("nodesToExecute", commandNodesToExecute);
1558                 serialNodesToExecute.add(parallelNodesToExecute);
1559             }
1560         }
1561
1562         JsonArray standardVolumeNodesToExecute = new JsonArray();
1563         for (int i = 0; i < devices.size(); i++) {
1564             Integer ttsVolume = ttsVolumes.size() > i ? ttsVolumes.get(i) : null;
1565             Integer standardVolume = standardVolumes.size() > i ? standardVolumes.get(i) : null;
1566             if (ttsVolume != null && standardVolume != null && !ttsVolume.equals(standardVolume)) {
1567                 standardVolumeNodesToExecute.add(createExecutionNode(devices.get(i), "Alexa.DeviceControls.Volume",
1568                         Map.of("value", standardVolume)));
1569             }
1570         }
1571         if (standardVolumeNodesToExecute.size() > 0) {
1572             JsonObject parallelNodesToExecute = new JsonObject();
1573             parallelNodesToExecute.addProperty("@type", "com.amazon.alexa.behaviors.model.ParallelNode");
1574             parallelNodesToExecute.add("nodesToExecute", standardVolumeNodesToExecute);
1575             serialNodesToExecute.add(parallelNodesToExecute);
1576         }
1577
1578         if (serialNodesToExecute.size() > 0) {
1579             executeSequenceNodes(devices, serialNodesToExecute, false);
1580         }
1581     }
1582
1583     // commands: Alexa.Weather.Play, Alexa.Traffic.Play, Alexa.FlashBriefing.Play,
1584     // Alexa.GoodMorning.Play,
1585     // Alexa.SingASong.Play, Alexa.TellStory.Play, Alexa.Speak (textToSpeach)
1586     public void executeSequenceCommand(Device device, String command, Map<String, Object> parameters) {
1587         JsonObject nodeToExecute = createExecutionNode(device, command, parameters);
1588         executeSequenceNode(List.of(device), nodeToExecute);
1589     }
1590
1591     private void executeSequenceNode(List<Device> devices, JsonObject nodeToExecute) {
1592         QueueObject queueObject = new QueueObject();
1593         queueObject.devices = devices;
1594         queueObject.nodeToExecute = nodeToExecute;
1595         String serialNumbers = "";
1596         for (Device device : devices) {
1597             String serialNumber = device.serialNumber;
1598             if (serialNumber != null) {
1599                 Objects.requireNonNull(this.devices.computeIfAbsent(serialNumber, k -> new LinkedBlockingQueue<>()))
1600                         .offer(queueObject);
1601                 serialNumbers = serialNumbers + device.serialNumber + " ";
1602             }
1603         }
1604         logger.debug("added {} device {}", queueObject.hashCode(), serialNumbers);
1605     }
1606
1607     private void handleExecuteSequenceNode() {
1608         Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.DEVICES, k -> new ReentrantLock()));
1609         if (lock.tryLock()) {
1610             try {
1611                 for (String serialNumber : devices.keySet()) {
1612                     LinkedBlockingQueue<QueueObject> queueObjects = devices.get(serialNumber);
1613                     if (queueObjects != null) {
1614                         QueueObject queueObject = queueObjects.peek();
1615                         if (queueObject != null) {
1616                             Future<?> future = queueObject.future;
1617                             if (future == null || future.isDone()) {
1618                                 boolean execute = true;
1619                                 String serial = "";
1620                                 for (Device tmpDevice : queueObject.devices) {
1621                                     if (!serialNumber.equals(tmpDevice.serialNumber)) {
1622                                         LinkedBlockingQueue<QueueObject> tmpQueueObjects = devices
1623                                                 .get(tmpDevice.serialNumber);
1624                                         if (tmpQueueObjects != null) {
1625                                             QueueObject tmpQueueObject = tmpQueueObjects.peek();
1626                                             Future<?> tmpFuture = tmpQueueObject.future;
1627                                             if (!queueObject.equals(tmpQueueObject)
1628                                                     || (tmpFuture != null && !tmpFuture.isDone())) {
1629                                                 execute = false;
1630                                                 break;
1631                                             }
1632                                             serial = serial + tmpDevice.serialNumber + " ";
1633                                         }
1634                                     }
1635                                 }
1636                                 if (execute) {
1637                                     queueObject.future = scheduler.submit(() -> queuedExecuteSequenceNode(queueObject));
1638                                     logger.debug("thread {} device {}", queueObject.hashCode(), serial);
1639                                 }
1640                             }
1641                         }
1642                     }
1643                 }
1644             } finally {
1645                 lock.unlock();
1646             }
1647         }
1648     }
1649
1650     private void queuedExecuteSequenceNode(QueueObject queueObject) {
1651         JsonObject nodeToExecute = queueObject.nodeToExecute;
1652         ExecutionNodeObject executionNodeObject = getExecutionNodeObject(nodeToExecute);
1653         if (executionNodeObject == null) {
1654             logger.debug("executionNodeObject empty, removing without execution");
1655             removeObjectFromQueueAfterExecutionCompletion(queueObject);
1656             return;
1657         }
1658         List<String> types = executionNodeObject.types;
1659         long delay = 0;
1660         if (types.contains("Alexa.DeviceControls.Volume")) {
1661             delay += 2000;
1662         }
1663         if (types.contains("Announcement")) {
1664             delay += 3000;
1665         } else {
1666             delay += 2000;
1667         }
1668         try {
1669             JsonObject sequenceJson = new JsonObject();
1670             sequenceJson.addProperty("@type", "com.amazon.alexa.behaviors.model.Sequence");
1671             sequenceJson.add("startNode", nodeToExecute);
1672
1673             JsonStartRoutineRequest request = new JsonStartRoutineRequest();
1674             request.sequenceJson = gson.toJson(sequenceJson);
1675             String json = gson.toJson(request);
1676
1677             Map<String, String> headers = new HashMap<>();
1678             headers.put("Routines-Version", "1.1.218665");
1679
1680             String text = executionNodeObject.text;
1681             if (text != null) {
1682                 text = text.replaceAll("<.+?>", " ").replaceAll("\\s+", " ").trim();
1683                 delay += text.length() * 150;
1684             }
1685
1686             makeRequest("POST", alexaServer + "/api/behaviors/preview", json, true, true, null, 3);
1687
1688             Thread.sleep(delay);
1689         } catch (IOException | URISyntaxException | InterruptedException e) {
1690             logger.warn("execute sequence node fails with unexpected error", e);
1691         } finally {
1692             removeObjectFromQueueAfterExecutionCompletion(queueObject);
1693         }
1694     }
1695
1696     private void removeObjectFromQueueAfterExecutionCompletion(QueueObject queueObject) {
1697         String serial = "";
1698         for (Device device : queueObject.devices) {
1699             String serialNumber = device.serialNumber;
1700             if (serialNumber != null) {
1701                 LinkedBlockingQueue<?> queue = devices.get(serialNumber);
1702                 if (queue != null) {
1703                     queue.remove(queueObject);
1704                 }
1705                 serial = serial + serialNumber + " ";
1706             }
1707         }
1708         logger.debug("removed {} device {}", queueObject.hashCode(), serial);
1709     }
1710
1711     private void executeSequenceNodes(List<Device> devices, JsonArray nodesToExecute, boolean parallel) {
1712         JsonObject serialNode = new JsonObject();
1713         if (parallel) {
1714             serialNode.addProperty("@type", "com.amazon.alexa.behaviors.model.ParallelNode");
1715         } else {
1716             serialNode.addProperty("@type", "com.amazon.alexa.behaviors.model.SerialNode");
1717         }
1718
1719         serialNode.add("nodesToExecute", nodesToExecute);
1720
1721         executeSequenceNode(devices, serialNode);
1722     }
1723
1724     private JsonObject createExecutionNode(@Nullable Device device, String command, Map<String, Object> parameters) {
1725         JsonObject operationPayload = new JsonObject();
1726         if (device != null) {
1727             operationPayload.addProperty("deviceType", device.deviceType);
1728             operationPayload.addProperty("deviceSerialNumber", device.serialNumber);
1729             operationPayload.addProperty("locale", "");
1730             operationPayload.addProperty("customerId", getCustomerId(device.deviceOwnerCustomerId));
1731         }
1732         for (String key : parameters.keySet()) {
1733             Object value = parameters.get(key);
1734             if (value instanceof String) {
1735                 operationPayload.addProperty(key, (String) value);
1736             } else if (value instanceof Number) {
1737                 operationPayload.addProperty(key, (Number) value);
1738             } else if (value instanceof Boolean) {
1739                 operationPayload.addProperty(key, (Boolean) value);
1740             } else if (value instanceof Character) {
1741                 operationPayload.addProperty(key, (Character) value);
1742             } else {
1743                 operationPayload.add(key, gson.toJsonTree(value));
1744             }
1745         }
1746
1747         JsonObject nodeToExecute = new JsonObject();
1748         nodeToExecute.addProperty("@type", "com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode");
1749         nodeToExecute.addProperty("type", command);
1750         if ("Alexa.TextCommand".equals(command)) {
1751             nodeToExecute.addProperty("skillId", "amzn1.ask.1p.tellalexa");
1752         }
1753         nodeToExecute.add("operationPayload", operationPayload);
1754         return nodeToExecute;
1755     }
1756
1757     @Nullable
1758     private ExecutionNodeObject getExecutionNodeObject(JsonObject nodeToExecute) {
1759         ExecutionNodeObject executionNodeObject = new ExecutionNodeObject();
1760         if (nodeToExecute.has("nodesToExecute")) {
1761             JsonArray serialNodesToExecute = nodeToExecute.getAsJsonArray("nodesToExecute");
1762             if (serialNodesToExecute != null && serialNodesToExecute.size() > 0) {
1763                 for (int i = 0; i < serialNodesToExecute.size(); i++) {
1764                     JsonObject serialNodesToExecuteJsonObject = serialNodesToExecute.get(i).getAsJsonObject();
1765                     if (serialNodesToExecuteJsonObject.has("nodesToExecute")) {
1766                         JsonArray parallelNodesToExecute = serialNodesToExecuteJsonObject
1767                                 .getAsJsonArray("nodesToExecute");
1768                         if (parallelNodesToExecute != null && parallelNodesToExecute.size() > 0) {
1769                             JsonObject parallelNodesToExecuteJsonObject = parallelNodesToExecute.get(0)
1770                                     .getAsJsonObject();
1771                             if (processNodesToExecuteJsonObject(executionNodeObject,
1772                                     parallelNodesToExecuteJsonObject)) {
1773                                 break;
1774                             }
1775                         }
1776                     } else {
1777                         if (processNodesToExecuteJsonObject(executionNodeObject, serialNodesToExecuteJsonObject)) {
1778                             break;
1779                         }
1780                     }
1781                 }
1782             }
1783         }
1784
1785         return executionNodeObject;
1786     }
1787
1788     private boolean processNodesToExecuteJsonObject(ExecutionNodeObject executionNodeObject,
1789             JsonObject nodesToExecuteJsonObject) {
1790         if (nodesToExecuteJsonObject.has("type")) {
1791             executionNodeObject.types.add(nodesToExecuteJsonObject.get("type").getAsString());
1792             if (nodesToExecuteJsonObject.has("operationPayload")) {
1793                 JsonObject operationPayload = nodesToExecuteJsonObject.getAsJsonObject("operationPayload");
1794                 if (operationPayload != null) {
1795                     if (operationPayload.has("textToSpeak")) {
1796                         executionNodeObject.text = operationPayload.get("textToSpeak").getAsString();
1797                         return true;
1798                     } else if (operationPayload.has("text")) {
1799                         executionNodeObject.text = operationPayload.get("text").getAsString();
1800                         return true;
1801                     } else if (operationPayload.has("content")) {
1802                         JsonArray content = operationPayload.getAsJsonArray("content");
1803                         if (content != null && content.size() > 0) {
1804                             JsonObject contentJsonObject = content.get(0).getAsJsonObject();
1805                             if (contentJsonObject.has("speak")) {
1806                                 JsonObject speak = contentJsonObject.getAsJsonObject("speak");
1807                                 if (speak != null && speak.has("value")) {
1808                                     executionNodeObject.text = speak.get("value").getAsString();
1809                                     return true;
1810                                 }
1811                             }
1812                         }
1813                     }
1814                 }
1815             }
1816         }
1817         return false;
1818     }
1819
1820     public void startRoutine(Device device, String utterance)
1821             throws IOException, URISyntaxException, InterruptedException {
1822         JsonAutomation found = null;
1823         String deviceLocale = "";
1824         JsonAutomation[] routines = getRoutines();
1825         if (routines == null) {
1826             return;
1827         }
1828         for (JsonAutomation routine : routines) {
1829             if (routine != null) {
1830                 Trigger[] triggers = routine.triggers;
1831                 if (triggers != null && routine.sequence != null) {
1832                     for (JsonAutomation.Trigger trigger : triggers) {
1833                         if (trigger == null) {
1834                             continue;
1835                         }
1836                         Payload payload = trigger.payload;
1837                         if (payload == null) {
1838                             continue;
1839                         }
1840                         String payloadUtterance = payload.utterance;
1841                         if (payloadUtterance != null && payloadUtterance.equalsIgnoreCase(utterance)) {
1842                             found = routine;
1843                             deviceLocale = payload.locale;
1844                             break;
1845                         }
1846                     }
1847                 }
1848             }
1849         }
1850         if (found != null) {
1851             String sequenceJson = gson.toJson(found.sequence);
1852
1853             JsonStartRoutineRequest request = new JsonStartRoutineRequest();
1854             request.behaviorId = found.automationId;
1855
1856             // replace tokens
1857             // "deviceType":"ALEXA_CURRENT_DEVICE_TYPE"
1858             String deviceType = "\"deviceType\":\"ALEXA_CURRENT_DEVICE_TYPE\"";
1859             String newDeviceType = "\"deviceType\":\"" + device.deviceType + "\"";
1860             sequenceJson = sequenceJson.replace(deviceType.subSequence(0, deviceType.length()),
1861                     newDeviceType.subSequence(0, newDeviceType.length()));
1862
1863             // "deviceSerialNumber":"ALEXA_CURRENT_DSN"
1864             String deviceSerial = "\"deviceSerialNumber\":\"ALEXA_CURRENT_DSN\"";
1865             String newDeviceSerial = "\"deviceSerialNumber\":\"" + device.serialNumber + "\"";
1866             sequenceJson = sequenceJson.replace(deviceSerial.subSequence(0, deviceSerial.length()),
1867                     newDeviceSerial.subSequence(0, newDeviceSerial.length()));
1868
1869             // "customerId": "ALEXA_CUSTOMER_ID"
1870             String customerId = "\"customerId\":\"ALEXA_CUSTOMER_ID\"";
1871             String newCustomerId = "\"customerId\":\"" + getCustomerId(device.deviceOwnerCustomerId) + "\"";
1872             sequenceJson = sequenceJson.replace(customerId.subSequence(0, customerId.length()),
1873                     newCustomerId.subSequence(0, newCustomerId.length()));
1874
1875             // "locale": "ALEXA_CURRENT_LOCALE"
1876             String locale = "\"locale\":\"ALEXA_CURRENT_LOCALE\"";
1877             String newlocale = deviceLocale != null && !deviceLocale.isEmpty() ? "\"locale\":\"" + deviceLocale + "\""
1878                     : "\"locale\":null";
1879             sequenceJson = sequenceJson.replace(locale.subSequence(0, locale.length()),
1880                     newlocale.subSequence(0, newlocale.length()));
1881
1882             request.sequenceJson = sequenceJson;
1883
1884             String requestJson = gson.toJson(request);
1885             makeRequest("POST", alexaServer + "/api/behaviors/preview", requestJson, true, true, null, 3);
1886         } else {
1887             logger.warn("Routine {} not found", utterance);
1888         }
1889     }
1890
1891     public @Nullable JsonAutomation @Nullable [] getRoutines()
1892             throws IOException, URISyntaxException, InterruptedException {
1893         String json = makeRequestAndReturnString(alexaServer + "/api/behaviors/automations?limit=2000");
1894         JsonAutomation[] result = parseJson(json, JsonAutomation[].class);
1895         return result;
1896     }
1897
1898     public JsonFeed[] getEnabledFlashBriefings() throws IOException, URISyntaxException, InterruptedException {
1899         String json = makeRequestAndReturnString(alexaServer + "/api/content-skills/enabled-feeds");
1900         JsonEnabledFeeds result = parseJson(json, JsonEnabledFeeds.class);
1901         if (result == null) {
1902             return new JsonFeed[0];
1903         }
1904         JsonFeed[] enabledFeeds = result.enabledFeeds;
1905         if (enabledFeeds != null) {
1906             return enabledFeeds;
1907         }
1908         return new JsonFeed[0];
1909     }
1910
1911     public void setEnabledFlashBriefings(JsonFeed[] enabledFlashBriefing)
1912             throws IOException, URISyntaxException, InterruptedException {
1913         JsonEnabledFeeds enabled = new JsonEnabledFeeds();
1914         enabled.enabledFeeds = enabledFlashBriefing;
1915         String json = gsonWithNullSerialization.toJson(enabled);
1916         makeRequest("POST", alexaServer + "/api/content-skills/enabled-feeds", json, true, true, null, 0);
1917     }
1918
1919     public JsonNotificationSound[] getNotificationSounds(Device device)
1920             throws IOException, URISyntaxException, InterruptedException {
1921         String json = makeRequestAndReturnString(
1922                 alexaServer + "/api/notification/sounds?deviceSerialNumber=" + device.serialNumber + "&deviceType="
1923                         + device.deviceType + "&softwareVersion=" + device.softwareVersion);
1924         JsonNotificationSounds result = parseJson(json, JsonNotificationSounds.class);
1925         if (result == null) {
1926             return new JsonNotificationSound[0];
1927         }
1928         JsonNotificationSound[] notificationSounds = result.notificationSounds;
1929         if (notificationSounds != null) {
1930             return notificationSounds;
1931         }
1932         return new JsonNotificationSound[0];
1933     }
1934
1935     public JsonNotificationResponse[] notifications() throws IOException, URISyntaxException, InterruptedException {
1936         String response = makeRequestAndReturnString(alexaServer + "/api/notifications");
1937         JsonNotificationsResponse result = parseJson(response, JsonNotificationsResponse.class);
1938         if (result == null) {
1939             return new JsonNotificationResponse[0];
1940         }
1941         JsonNotificationResponse[] notifications = result.notifications;
1942         if (notifications == null) {
1943             return new JsonNotificationResponse[0];
1944         }
1945         return notifications;
1946     }
1947
1948     public @Nullable JsonNotificationResponse notification(Device device, String type, @Nullable String label,
1949             @Nullable JsonNotificationSound sound) throws IOException, URISyntaxException, InterruptedException {
1950         Date date = new Date(new Date().getTime());
1951         long createdDate = date.getTime();
1952         Date alarm = new Date(createdDate + 5000); // add 5 seconds, because amazon does not except calls for times in
1953         // the past (compared with the server time)
1954         long alarmTime = alarm.getTime();
1955
1956         JsonNotificationRequest request = new JsonNotificationRequest();
1957         request.type = type;
1958         request.deviceSerialNumber = device.serialNumber;
1959         request.deviceType = device.deviceType;
1960         request.createdDate = createdDate;
1961         request.alarmTime = alarmTime;
1962         request.reminderLabel = label;
1963         request.sound = sound;
1964         request.originalDate = new SimpleDateFormat("yyyy-MM-dd").format(alarm);
1965         request.originalTime = new SimpleDateFormat("HH:mm:ss.SSSS").format(alarm);
1966         request.type = type;
1967         request.id = "create" + type;
1968
1969         String data = gsonWithNullSerialization.toJson(request);
1970         String response = makeRequestAndReturnString("PUT", alexaServer + "/api/notifications/createReminder", data,
1971                 true, null);
1972         JsonNotificationResponse result = parseJson(response, JsonNotificationResponse.class);
1973         return result;
1974     }
1975
1976     public void stopNotification(JsonNotificationResponse notification)
1977             throws IOException, URISyntaxException, InterruptedException {
1978         makeRequestAndReturnString("DELETE", alexaServer + "/api/notifications/" + notification.id, null, true, null);
1979     }
1980
1981     public @Nullable JsonNotificationResponse getNotificationState(JsonNotificationResponse notification)
1982             throws IOException, URISyntaxException, InterruptedException {
1983         String response = makeRequestAndReturnString("GET", alexaServer + "/api/notifications/" + notification.id, null,
1984                 true, null);
1985         JsonNotificationResponse result = parseJson(response, JsonNotificationResponse.class);
1986         return result;
1987     }
1988
1989     public List<JsonMusicProvider> getMusicProviders() {
1990         try {
1991             Map<String, String> headers = new HashMap<>();
1992             headers.put("Routines-Version", "1.1.218665");
1993             String response = makeRequestAndReturnString("GET",
1994                     alexaServer + "/api/behaviors/entities?skillId=amzn1.ask.1p.music", null, true, headers);
1995             if (!response.isEmpty()) {
1996                 JsonMusicProvider[] result = parseJson(response, JsonMusicProvider[].class);
1997                 return Arrays.asList(result);
1998             }
1999         } catch (IOException | URISyntaxException | InterruptedException e) {
2000             logger.warn("getMusicProviders fails: {}", e.getMessage());
2001         }
2002         return List.of();
2003     }
2004
2005     public void playMusicVoiceCommand(Device device, String providerId, String voiceCommand)
2006             throws IOException, URISyntaxException, InterruptedException {
2007         JsonPlaySearchPhraseOperationPayload payload = new JsonPlaySearchPhraseOperationPayload();
2008         payload.customerId = getCustomerId(device.deviceOwnerCustomerId);
2009         payload.locale = "ALEXA_CURRENT_LOCALE";
2010         payload.musicProviderId = providerId;
2011         payload.searchPhrase = voiceCommand;
2012
2013         String playloadString = gson.toJson(payload);
2014
2015         JsonObject postValidationJson = new JsonObject();
2016
2017         postValidationJson.addProperty("type", "Alexa.Music.PlaySearchPhrase");
2018         postValidationJson.addProperty("operationPayload", playloadString);
2019
2020         String postDataValidate = postValidationJson.toString();
2021
2022         String validateResultJson = makeRequestAndReturnString("POST",
2023                 alexaServer + "/api/behaviors/operation/validate", postDataValidate, true, null);
2024
2025         if (!validateResultJson.isEmpty()) {
2026             JsonPlayValidationResult validationResult = parseJson(validateResultJson, JsonPlayValidationResult.class);
2027             if (validationResult != null) {
2028                 JsonPlaySearchPhraseOperationPayload validatedOperationPayload = validationResult.operationPayload;
2029                 if (validatedOperationPayload != null) {
2030                     payload.sanitizedSearchPhrase = validatedOperationPayload.sanitizedSearchPhrase;
2031                     payload.searchPhrase = validatedOperationPayload.searchPhrase;
2032                 }
2033             }
2034         }
2035
2036         payload.locale = null;
2037         payload.deviceSerialNumber = device.serialNumber;
2038         payload.deviceType = device.deviceType;
2039
2040         JsonObject sequenceJson = new JsonObject();
2041         sequenceJson.addProperty("@type", "com.amazon.alexa.behaviors.model.Sequence");
2042         JsonObject startNodeJson = new JsonObject();
2043         startNodeJson.addProperty("@type", "com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode");
2044         startNodeJson.addProperty("type", "Alexa.Music.PlaySearchPhrase");
2045         startNodeJson.add("operationPayload", gson.toJsonTree(payload));
2046         sequenceJson.add("startNode", startNodeJson);
2047
2048         JsonStartRoutineRequest startRoutineRequest = new JsonStartRoutineRequest();
2049         startRoutineRequest.sequenceJson = sequenceJson.toString();
2050         startRoutineRequest.status = null;
2051
2052         String postData = gson.toJson(startRoutineRequest);
2053         makeRequest("POST", alexaServer + "/api/behaviors/preview", postData, true, true, null, 3);
2054     }
2055
2056     public @Nullable JsonEqualizer getEqualizer(Device device)
2057             throws IOException, URISyntaxException, InterruptedException {
2058         String json = makeRequestAndReturnString(
2059                 alexaServer + "/api/equalizer/" + device.serialNumber + "/" + device.deviceType);
2060         return parseJson(json, JsonEqualizer.class);
2061     }
2062
2063     public void setEqualizer(Device device, JsonEqualizer settings)
2064             throws IOException, URISyntaxException, InterruptedException {
2065         String postData = gson.toJson(settings);
2066         makeRequest("POST", alexaServer + "/api/equalizer/" + device.serialNumber + "/" + device.deviceType, postData,
2067                 true, true, null, 0);
2068     }
2069
2070     public static class AnnouncementWrapper {
2071         public List<Device> devices = new ArrayList<>();
2072         public String speak;
2073         public String bodyText;
2074         public @Nullable String title;
2075         public List<@Nullable Integer> ttsVolumes = new ArrayList<>();
2076         public List<@Nullable Integer> standardVolumes = new ArrayList<>();
2077
2078         public AnnouncementWrapper(String speak, String bodyText, @Nullable String title) {
2079             this.speak = speak;
2080             this.bodyText = bodyText;
2081             this.title = title;
2082         }
2083     }
2084
2085     private static class TextToSpeech {
2086         public List<Device> devices = new ArrayList<>();
2087         public String text;
2088         public List<@Nullable Integer> ttsVolumes = new ArrayList<>();
2089         public List<@Nullable Integer> standardVolumes = new ArrayList<>();
2090
2091         public TextToSpeech(String text) {
2092             this.text = text;
2093         }
2094     }
2095
2096     private static class TextCommand {
2097         public List<Device> devices = new ArrayList<>();
2098         public String text;
2099         public List<@Nullable Integer> ttsVolumes = new ArrayList<>();
2100         public List<@Nullable Integer> standardVolumes = new ArrayList<>();
2101
2102         public TextCommand(String text) {
2103             this.text = text;
2104         }
2105     }
2106
2107     private static class Volume {
2108         public List<Device> devices = new ArrayList<>();
2109         public int volume;
2110         public List<@Nullable Integer> volumes = new ArrayList<>();
2111
2112         public Volume(int volume) {
2113             this.volume = volume;
2114         }
2115     }
2116
2117     private static class QueueObject {
2118         public @Nullable Future<?> future;
2119         public List<Device> devices = List.of();
2120         public JsonObject nodeToExecute = new JsonObject();
2121     }
2122
2123     private static class ExecutionNodeObject {
2124         public List<String> types = new ArrayList<>();
2125         @Nullable
2126         public String text;
2127     }
2128 }