]> git.basschouten.com Git - openhab-addons.git/blob
b81da7e98f9f908e28b3bb9a2968a9489de2753d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.voice.voicerss.internal.cloudapi;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.net.HttpURLConnection;
18 import java.net.URL;
19 import java.net.URLConnection;
20 import java.net.URLEncoder;
21 import java.nio.charset.StandardCharsets;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Set;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * This class implements the Cloud service from VoiceRSS. For more information,
36  * see API documentation at http://www.voicerss.org/api .
37  *
38  * Current state of implementation:
39  * <ul>
40  * <li>All API languages supported</li>
41  * <li>Only default voice supported with good audio quality</li>
42  * <li>MP3, OGG, AAC and WAV audio formats supported</li>
43  * <li>It uses HTTP and not HTTPS (for performance reasons)</li>
44  * </ul>
45  *
46  * @author Jochen Hiller - Initial contribution
47  * @author Laurent Garnier - add support for all API languages
48  * @author Laurent Garnier - add support for OGG and AAC audio formats
49  * @author Andreas Brenk - add support for WAV audio format
50  */
51 @NonNullByDefault
52 public class VoiceRSSCloudImpl implements VoiceRSSCloudAPI {
53
54     public static final String DEFAULT_VOICE = "default";
55
56     public static final String API_URL = "https://api.voicerss.org/?key=%s&hl=%s&c=%s&f=%s&src=%s";
57     public static final String API_URL_WITH_VOICE = API_URL + "&v=%s";
58
59     private static final Set<String> SUPPORTED_AUDIO_CODECS = Set.of("MP3", "OGG", "AAC", "WAV", "CAF");
60
61     private static final Set<Locale> SUPPORTED_LOCALES = new HashSet<>();
62     static {
63         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ar-eg"));
64         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ar-sa"));
65         SUPPORTED_LOCALES.add(Locale.forLanguageTag("bg-bg"));
66         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ca-es"));
67         SUPPORTED_LOCALES.add(Locale.forLanguageTag("cs-cz"));
68         SUPPORTED_LOCALES.add(Locale.forLanguageTag("da-dk"));
69         SUPPORTED_LOCALES.add(Locale.forLanguageTag("de-at"));
70         SUPPORTED_LOCALES.add(Locale.forLanguageTag("de-de"));
71         SUPPORTED_LOCALES.add(Locale.forLanguageTag("de-ch"));
72         SUPPORTED_LOCALES.add(Locale.forLanguageTag("el-gr"));
73         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-au"));
74         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-ca"));
75         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-gb"));
76         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-ie"));
77         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-in"));
78         SUPPORTED_LOCALES.add(Locale.forLanguageTag("en-us"));
79         SUPPORTED_LOCALES.add(Locale.forLanguageTag("es-es"));
80         SUPPORTED_LOCALES.add(Locale.forLanguageTag("es-mx"));
81         SUPPORTED_LOCALES.add(Locale.forLanguageTag("fi-fi"));
82         SUPPORTED_LOCALES.add(Locale.forLanguageTag("fr-ca"));
83         SUPPORTED_LOCALES.add(Locale.forLanguageTag("fr-fr"));
84         SUPPORTED_LOCALES.add(Locale.forLanguageTag("fr-ch"));
85         SUPPORTED_LOCALES.add(Locale.forLanguageTag("he-il"));
86         SUPPORTED_LOCALES.add(Locale.forLanguageTag("hi-in"));
87         SUPPORTED_LOCALES.add(Locale.forLanguageTag("hr-hr"));
88         SUPPORTED_LOCALES.add(Locale.forLanguageTag("hu-hu"));
89         SUPPORTED_LOCALES.add(Locale.forLanguageTag("id-id"));
90         SUPPORTED_LOCALES.add(Locale.forLanguageTag("it-it"));
91         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ja-jp"));
92         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ko-kr"));
93         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ms-my"));
94         SUPPORTED_LOCALES.add(Locale.forLanguageTag("nb-no"));
95         SUPPORTED_LOCALES.add(Locale.forLanguageTag("nl-be"));
96         SUPPORTED_LOCALES.add(Locale.forLanguageTag("nl-nl"));
97         SUPPORTED_LOCALES.add(Locale.forLanguageTag("pl-pl"));
98         SUPPORTED_LOCALES.add(Locale.forLanguageTag("pt-br"));
99         SUPPORTED_LOCALES.add(Locale.forLanguageTag("pt-pt"));
100         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ro-ro"));
101         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ru-ru"));
102         SUPPORTED_LOCALES.add(Locale.forLanguageTag("sk-sk"));
103         SUPPORTED_LOCALES.add(Locale.forLanguageTag("sl-si"));
104         SUPPORTED_LOCALES.add(Locale.forLanguageTag("sv-se"));
105         SUPPORTED_LOCALES.add(Locale.forLanguageTag("ta-in"));
106         SUPPORTED_LOCALES.add(Locale.forLanguageTag("th-th"));
107         SUPPORTED_LOCALES.add(Locale.forLanguageTag("tr-tr"));
108         SUPPORTED_LOCALES.add(Locale.forLanguageTag("vi-vn"));
109         SUPPORTED_LOCALES.add(Locale.forLanguageTag("zh-cn"));
110         SUPPORTED_LOCALES.add(Locale.forLanguageTag("zh-hk"));
111         SUPPORTED_LOCALES.add(Locale.forLanguageTag("zh-tw"));
112     }
113
114     private static final Map<String, Set<String>> SUPPORTED_VOICES = new HashMap<>();
115     static {
116         SUPPORTED_VOICES.put("ar-eg", Set.of("Oda"));
117         SUPPORTED_VOICES.put("ar-sa", Set.of("Salim"));
118         SUPPORTED_VOICES.put("bg-bg", Set.of("Dimo"));
119         SUPPORTED_VOICES.put("ca-es", Set.of("Rut"));
120         SUPPORTED_VOICES.put("cs-cz", Set.of("Josef"));
121         SUPPORTED_VOICES.put("da-dk", Set.of("Freja"));
122         SUPPORTED_VOICES.put("de-at", Set.of("Lukas"));
123         SUPPORTED_VOICES.put("de-de", Set.of("Hanna", "Lina", "Jonas"));
124         SUPPORTED_VOICES.put("de-ch", Set.of("Tim"));
125         SUPPORTED_VOICES.put("el-gr", Set.of("Neo"));
126         SUPPORTED_VOICES.put("en-au", Set.of("Zoe", "Isla", "Evie", "Jack"));
127         SUPPORTED_VOICES.put("en-ca", Set.of("Rose", "Clara", "Emma", "Mason"));
128         SUPPORTED_VOICES.put("en-gb", Set.of("Alice", "Nancy", "Lily", "Harry"));
129         SUPPORTED_VOICES.put("en-ie", Set.of("Oran"));
130         SUPPORTED_VOICES.put("en-in", Set.of("Eka", "Jai", "Ajit"));
131         SUPPORTED_VOICES.put("en-us", Set.of("Linda", "Amy", "Mary", "John", "Mike"));
132         SUPPORTED_VOICES.put("es-es", Set.of("Camila", "Sofia", "Luna", "Diego"));
133         SUPPORTED_VOICES.put("es-mx", Set.of("Juana", "Silvia", "Teresa", "Jose"));
134         SUPPORTED_VOICES.put("fi-fi", Set.of("Aada"));
135         SUPPORTED_VOICES.put("fr-ca", Set.of("Emile", "Olivia", "Logan", "Felix"));
136         SUPPORTED_VOICES.put("fr-fr", Set.of("Bette", "Iva", "Zola", "Axel"));
137         SUPPORTED_VOICES.put("fr-ch", Set.of("Theo"));
138         SUPPORTED_VOICES.put("he-il", Set.of("Rami"));
139         SUPPORTED_VOICES.put("hi-in", Set.of("Puja", "Kabir"));
140         SUPPORTED_VOICES.put("hr-hr", Set.of("Nikola"));
141         SUPPORTED_VOICES.put("hu-hu", Set.of("Mate"));
142         SUPPORTED_VOICES.put("id-id", Set.of("Intan"));
143         SUPPORTED_VOICES.put("it-it", Set.of("Bria", "Mia", "Pietro"));
144         SUPPORTED_VOICES.put("ja-jp", Set.of("Hina", "Airi", "Fumi", "Akira"));
145         SUPPORTED_VOICES.put("ko-kr", Set.of("Nari"));
146         SUPPORTED_VOICES.put("ms-my", Set.of("Aqil"));
147         SUPPORTED_VOICES.put("nb-no", Set.of("Marte", "Erik"));
148         SUPPORTED_VOICES.put("nl-be", Set.of("Daan"));
149         SUPPORTED_VOICES.put("nl-nl", Set.of("Lotte", "Bram"));
150         SUPPORTED_VOICES.put("pl-pl", Set.of("Julia", "Jan"));
151         SUPPORTED_VOICES.put("pt-br", Set.of("Marcia", "Ligia", "Yara", "Dinis"));
152         SUPPORTED_VOICES.put("pt-pt", Set.of("Leonor"));
153         SUPPORTED_VOICES.put("ro-ro", Set.of("Doru"));
154         SUPPORTED_VOICES.put("ru-ru", Set.of("Olga", "Marina", "Peter"));
155         SUPPORTED_VOICES.put("sk-sk", Set.of("Beda"));
156         SUPPORTED_VOICES.put("sl-si", Set.of("Vid"));
157         SUPPORTED_VOICES.put("sv-se", Set.of("Molly", "Hugo"));
158         SUPPORTED_VOICES.put("ta-in", Set.of("Sai"));
159         SUPPORTED_VOICES.put("th-th", Set.of("Ukrit"));
160         SUPPORTED_VOICES.put("tr-tr", Set.of("Omer"));
161         SUPPORTED_VOICES.put("vi-vn", Set.of("Chi"));
162         SUPPORTED_VOICES.put("zh-cn", Set.of("Luli", "Shu", "Chow", "Wang"));
163         SUPPORTED_VOICES.put("zh-hk", Set.of("Jia", "Xia", "Chen"));
164         SUPPORTED_VOICES.put("zh-tw", Set.of("Akemi", "Lin", "Lee"));
165     }
166
167     protected boolean logging;
168
169     public VoiceRSSCloudImpl(boolean logging) {
170         this.logging = logging;
171     }
172
173     @Override
174     public Set<String> getAvailableAudioCodecs() {
175         return SUPPORTED_AUDIO_CODECS;
176     }
177
178     @Override
179     public Set<Locale> getAvailableLocales() {
180         return SUPPORTED_LOCALES;
181     }
182
183     @Override
184     public Set<String> getAvailableVoices() {
185         // different locales support different voices, so let's list all here in one big set when no locale is provided
186         Set<String> allvoxes = new HashSet<>();
187         allvoxes.add(DEFAULT_VOICE);
188         for (Set<String> langvoxes : SUPPORTED_VOICES.values()) {
189             for (String langvox : langvoxes) {
190                 allvoxes.add(langvox);
191             }
192         }
193         return allvoxes;
194     }
195
196     @Override
197     public Set<String> getAvailableVoices(Locale locale) {
198         Set<String> allvoxes = new HashSet<>();
199         allvoxes.add(DEFAULT_VOICE);
200         // all maps must be defined with key in lowercase
201         String langtag = locale.toLanguageTag().toLowerCase();
202         if (SUPPORTED_VOICES.containsKey(langtag)) {
203             for (String langvox : SUPPORTED_VOICES.get(langtag)) {
204                 allvoxes.add(langvox);
205             }
206         }
207         return allvoxes;
208     }
209
210     /*
211      * This method will return an input stream to an audio stream for the given
212      * parameters.
213      *
214      * It will do that using a plain URL connection to avoid any external
215      * dependencies.
216      */
217     @Override
218     public InputStream getTextToSpeech(String apiKey, String text, String locale, String voice, String audioCodec,
219             String audioFormat) throws IOException {
220         String url = createURL(apiKey, text, locale, voice, audioCodec, audioFormat);
221         if (logging) {
222             LoggerFactory.getLogger(VoiceRSSCloudImpl.class).debug("Call {}", url.replace(apiKey, "***"));
223         }
224         URLConnection connection = new URL(url).openConnection();
225
226         // we will check return codes. The service will ALWAYS return a HTTP
227         // 200, but for error messages, it will return a text/plain format and
228         // the error message in body
229         int status = ((HttpURLConnection) connection).getResponseCode();
230         if (HttpURLConnection.HTTP_OK != status) {
231             if (logging) {
232                 LoggerFactory.getLogger(VoiceRSSCloudImpl.class).warn("Call {} returned HTTP {}",
233                         url.replace(apiKey, "***"), status);
234             }
235             throw new IOException("Could not read from service: HTTP code " + status);
236         }
237         if (logging) {
238             Logger logger = LoggerFactory.getLogger(VoiceRSSCloudImpl.class);
239             if (logger.isTraceEnabled()) {
240                 for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
241                     logger.trace("Response.header: {}={}", header.getKey(), header.getValue());
242                 }
243             }
244         }
245         String contentType = connection.getHeaderField("Content-Type");
246         InputStream is = connection.getInputStream();
247         // check if content type is text/plain, then we have an error
248         if (contentType.contains("text/plain")) {
249             byte[] bytes = new byte[256];
250             is.read(bytes, 0, 256);
251             // close before throwing an exception
252             try {
253                 is.close();
254             } catch (IOException ex) {
255                 if (logging) {
256                     LoggerFactory.getLogger(VoiceRSSCloudImpl.class).debug("Failed to close inputstream", ex);
257                 }
258             }
259             throw new IOException(
260                     "Could not read audio content, service returned an error: " + new String(bytes, "UTF-8"));
261         } else {
262             return is;
263         }
264     }
265
266     // internal
267
268     /**
269      * This method will create the URL for the cloud service. The text will be
270      * URI encoded as it is part of the URL.
271      *
272      * It is in package scope to be accessed by tests.
273      */
274     private String createURL(String apiKey, String text, String locale, String voice, String audioCodec,
275             String audioFormat) {
276         String encodedMsg = URLEncoder.encode(text, StandardCharsets.UTF_8);
277         String url;
278         if (!DEFAULT_VOICE.equals(voice)) {
279             url = String.format(API_URL_WITH_VOICE, apiKey, locale, audioCodec, audioFormat, encodedMsg, voice);
280         } else {
281             url = String.format(API_URL, apiKey, locale, audioCodec, audioFormat, encodedMsg);
282         }
283         return url;
284     }
285 }