iobroker.sayit 2.1.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -265,6 +265,13 @@ Following values for engines are possible:
265
265
  ### **WORK IN PROGRESS**
266
266
  -->
267
267
  ## Changelog
268
+ ### 3.0.0 (2023-04-03)
269
+ * (bluefox) Restored cloud engines. Warning: update cloud adapter to at least 4.4.0
270
+ * (bluefox) Breaking changes: Minimal node.js version is 14
271
+
272
+ ### 2.1.2 (2023-03-27)
273
+ * (bluefox) Corrected engines with web-link
274
+
268
275
  ### 2.1.1 (2023-03-24)
269
276
  * (Jey-Cee) Added support for Coqui TTS
270
277
  * (bluefox) Renamed all configuration attributes
@@ -265,6 +265,15 @@
265
265
  "sm": 6,
266
266
  "md": 4,
267
267
  "lg": 2
268
+ },
269
+ "_test": {
270
+ "newLine": true,
271
+ "variant": "contained",
272
+ "type": "sendTo",
273
+ "label": "Test",
274
+ "command": "test",
275
+ "jsonData": "${JSON.stringify(data)}",
276
+ "icon": "send"
268
277
  }
269
278
  }
270
279
  },
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "sayit",
4
- "version": "2.1.1",
4
+ "version": "3.0.0",
5
5
  "news": {
6
+ "3.0.0": {
7
+ "en": "Restored cloud engines. Warning: update cloud adapter to at least 4.4.0\nBreaking changes: Minimal node.js version is 14",
8
+ "de": "Restaurierte Cloud-Motoren. Warnung: Cloud-Adapter auf mindestens 4.4.0 aktualisieren\nÄnderungsvorschläge: Minimal node.js version is 14",
9
+ "ru": "Восстановление облачных двигателей. Внимание: обновление облачного адаптера не менее 4.4.0\nПерерыв изменений: Минимальная версия node.js 14",
10
+ "pt": "Motores de nuvem restaurados. Aviso: atualize o adaptador de nuvem para pelo menos 4.4.0\nAlterações de ruptura: A versão mínima do node.js é 14",
11
+ "nl": "Gerestaureerde wolkenmotoren. Vertaling:\nBreaking changes: Minimale node",
12
+ "fr": "Moteurs cloud restaurés. Avertissement: mettre à jour l'adaptateur cloud au moins 4.4.0\nChangements de rupture: Minimal node.js version est 14",
13
+ "it": "Motori cloud restaurati. Avvertenza: aggiornamento adattatore cloud almeno 4.4.0\nCambiamenti di rottura: Versione minimal node.js è 14",
14
+ "es": "Motores de nube restaurados. Advertencia: actualización del adaptador de nube a al menos 4.4.0\nCambios de ruptura: Minimal node.js versión es 14",
15
+ "pl": "Restored cloud engine (ang.). Warning: aktualizacja adapteru chmur do przynajmniej 4.4\nZmiany: Wersja minimalna jest 14",
16
+ "uk": "Відновлення хмарних двигунів. Попередження: оновлення хмарного адаптера до принаймні 4.4.0\nЗміни прориву: Minimal node.js версія 14",
17
+ "zh-cn": "恢复云雾器。 警告:更新云雾剂,至少4.4.0\n断然变化: 米切尔·诺贝尔版本为14。"
18
+ },
19
+ "2.1.2": {
20
+ "en": "Corrected engines with web-link",
21
+ "de": "Korrigierte Motoren mit Weblink",
22
+ "ru": "Правильные двигатели с web-ссылка",
23
+ "pt": "Motores corrigidos com web-link",
24
+ "nl": "Vertaling:",
25
+ "fr": "Moteurs corrigés avec web-link",
26
+ "it": "Motori corretti con web-link",
27
+ "es": "Motores corregidos con enlace web",
28
+ "pl": "Poprawione silniki z linkami stron internetowych",
29
+ "uk": "Виправлені двигуни з веб-посиланням",
30
+ "zh-cn": "连接网络的工程师"
31
+ },
6
32
  "2.1.1": {
7
33
  "en": "Added support for Coqui TTS\nRenamed all configuration attributes",
8
34
  "de": "Unterstützung für Coqui TTS\nAlle Konfigurationsattribute umbenannt",
@@ -65,30 +91,6 @@
65
91
  "es": "Se corrigieron errores en io-package.json",
66
92
  "pl": "Naprawiono błędy w io-package.json",
67
93
  "zh-cn": "修复了 io-package.json 中的错误"
68
- },
69
- "1.12.4": {
70
- "en": "Fixed errors in io-package.json",
71
- "de": "Fehler in io-package.json behoben",
72
- "ru": "Исправлены ошибки в io-package.json",
73
- "pt": "Corrigidos erros em io-package.json",
74
- "nl": "Fouten opgelost in io-package.json",
75
- "fr": "Correction d'erreurs dans io-package.json",
76
- "it": "Risolti errori in io-package.json",
77
- "es": "Se corrigieron errores en io-package.json",
78
- "pl": "Naprawiono błędy w io-package.json",
79
- "zh-cn": "修复了 io-package.json 中的错误"
80
- },
81
- "1.12.3": {
82
- "en": "corrected the google engine\nAdded new voices: german, korean, brasil, Dutch",
83
- "de": "die Google-Engine korrigiert\nNeue Stimmen hinzugefügt: Deutsch, Koreanisch, Brasil, Niederländisch",
84
- "ru": "исправил движок гугл\nДобавлены новые голоса: немецкий, корейский, бразильский, голландский.",
85
- "pt": "corrigiu o motor do google\nAdicionadas novas vozes: alemão, coreano, brasil, holandês",
86
- "nl": "de google engine gecorrigeerd correct\nNieuwe stemmen toegevoegd: Duits, Koreaans, Brazilië, Nederlands",
87
- "fr": "corrigé le moteur google\nAjout de nouvelles voix : allemand, coréen, brésilien, néerlandais",
88
- "it": "corretto il motore di Google\nAggiunte nuove voci: tedesco, coreano, brasiliano, olandese",
89
- "es": "corrigió el motor de google\nAñadidas nuevas voces: alemán, coreano, brasil, holandés",
90
- "pl": "poprawiłem silnik google\nDodano nowe głosy: niemiecki, koreański, brazylijski, holenderski",
91
- "zh-cn": "更正了谷歌引擎\n添加了新的声音:德语、韩语、巴西语、荷兰语"
92
94
  }
93
95
  },
94
96
  "title": "Text to speech",
@@ -106,29 +106,49 @@ class Speech2Device {
106
106
  return false;
107
107
  }
108
108
 
109
- async sayItBrowser(text, language, volume, duration) {
109
+ async sayItBrowser(text, language, volume, duration, testOptions) {
110
110
  const result = await this.uploadToStates(text);
111
111
 
112
- await this.adapter.setForeignStateAsync('vis.0.control.instance', this.adapter.config.browserInstance);
112
+ const browserInstance = (testOptions && testOptions.browserInstance) || this.adapter.config.browserInstance;
113
+
114
+ await this.adapter.setForeignStateAsync('vis.0.control.instance', browserInstance);
113
115
  await this.adapter.setForeignStateAsync('vis.0.control.data', result.fileInDB);
114
116
  await this.adapter.setForeignStateAsync('vis.0.control.command', 'playSound');
115
117
 
116
118
  return duration;
117
119
  }
118
120
 
119
- async sayItSonos(text, language, volume, duration) {
121
+ async getWebLink(testOptions) {
122
+ if (testOptions) {
123
+ const webServer = (testOptions && testOptions.webServer) || this.adapter.config.webServer;
124
+ const webInstance = (testOptions && testOptions.webInstance) || this.adapter.config.webInstance;
125
+
126
+ if (!this.options.webLink || webServer !== this.adapter.config.webServer || webInstance !== this.adapter.config.webInstance) {
127
+ const obj = await this.adapter.getForeignObjectAsync(`system.adapter.${testOptions.webInstance}`);
128
+ return this.options.getWebLink(obj, webServer, webInstance);
129
+ }
130
+ }
131
+
132
+ return this.options.webLink;
133
+ }
134
+
135
+ async sayItSonos(text, language, volume, duration, testOptions) {
120
136
  volume = volume || this.options.sayLastVolume;
121
137
  const result = await this.uploadToStates(text);
122
138
  if (volume === 'null') {
123
139
  volume = 0;
124
140
  }
125
141
 
126
- const fileName = `${volume ? `${volume};` : ''}${this.options.webLink}${result.fileInDB}`;
142
+ const webLink = await this.getWebLink(testOptions);
143
+
144
+ const fileName = `${volume ? `${volume};` : ''}${webLink}${result.fileInDB}`;
145
+
146
+ const sonosDevice = (testOptions && testOptions.sonosDevice) || this.adapter.config.sonosDevice;
127
147
 
128
- if (this.adapter.config.sonosDevice && this.options.webLink) {
129
- this.adapter.log.info(`Set "${this.adapter.config.sonosDevice}.tts: ${fileName}`);
130
- await this.adapter.setForeignStateAsync(`${this.adapter.config.sonosDevice}.tts`, fileName);
131
- } else if (this.options.webLink) {
148
+ if (sonosDevice && webLink) {
149
+ this.adapter.log.info(`Set "${sonosDevice}.tts: ${fileName}`);
150
+ await this.adapter.setForeignStateAsync(`${sonosDevice}.tts`, fileName);
151
+ } else if (webLink) {
132
152
  this.adapter.log.info(`Send to sonos ${fileName}`);
133
153
  this.adapter.sendTo('sonos', 'send', fileName);
134
154
  } else {
@@ -138,7 +158,7 @@ class Speech2Device {
138
158
  return duration;
139
159
  }
140
160
 
141
- async sayItHeos(text, language, volume, duration) {
161
+ async sayItHeos(text, language, volume, duration, testOptions) {
142
162
  volume = volume || this.options.sayLastVolume;
143
163
 
144
164
  const result = await this.uploadToStates(text);
@@ -146,13 +166,15 @@ class Speech2Device {
146
166
  if (volume === 'null') {
147
167
  volume = 0;
148
168
  }
169
+ const webLink = await this.getWebLink(testOptions);
149
170
 
150
- const fileName = `${volume ? `${volume};` : ''}${this.options.webLink}${result.fileInDB}`;
171
+ const fileName = `${volume ? `${volume};` : ''}${webLink}${result.fileInDB}`;
172
+ const heosDevice = (testOptions && testOptions.heosDevice) || this.adapter.config.heosDevice;
151
173
 
152
- if (this.adapter.config.heosDevice && this.options.webLink) {
153
- this.adapter.log.info(`Set "${this.adapter.config.heosDevice}.tts: ${fileName}`);
154
- await this.adapter.setForeignStateAsync(`${this.adapter.config.heosDevice}.tts`, fileName);
155
- } else if (this.options.webLink) {
174
+ if (heosDevice && webLink) {
175
+ this.adapter.log.info(`Set "${heosDevice}.tts: ${fileName}`);
176
+ await this.adapter.setForeignStateAsync(`${heosDevice}.tts`, fileName);
177
+ } else if (webLink) {
156
178
  this.adapter.log.info(`Send to heos ${fileName}`);
157
179
  this.adapter.sendTo('heos', 'send', fileName);
158
180
  } else {
@@ -162,20 +184,22 @@ class Speech2Device {
162
184
  return duration;
163
185
  }
164
186
 
165
- async sayItMpd(text, language, volume, duration) {
187
+ async sayItMpd(text, language, volume, duration, testOptions) {
166
188
  volume = volume || this.options.sayLastVolume;
167
189
 
168
190
  const result = await this.uploadToStates(text);
169
191
  if (volume === 'null' || volume === 'undefined') {
170
192
  volume = 0;
171
193
  }
194
+ const webLink = await this.getWebLink(testOptions);
195
+ const mpdInstance = (testOptions && testOptions.mpdInstance) || this.adapter.config.mpdInstance;
172
196
 
173
- const fileName = `${volume ? `${volume};` : ''}${this.options.webLink}${result.fileInDB}`;
197
+ const fileName = `${volume ? `${volume};` : ''}${webLink}${result.fileInDB}`;
174
198
 
175
- if (this.adapter.config.mpdInstance && this.options.webLink) {
176
- this.adapter.log.info(`Set "${this.adapter.config.mpdInstance}.say: ${fileName}`);
177
- await this.adapter.setForeignStateAsync(`${this.adapter.config.mpdInstance}.say`, fileName);
178
- } else if (this.options.webLink) {
199
+ if (mpdInstance && webLink) {
200
+ this.adapter.log.info(`Set "${mpdInstance}.say: ${fileName}`);
201
+ await this.adapter.setForeignStateAsync(`${mpdInstance}.say`, fileName);
202
+ } else if (webLink) {
179
203
  this.adapter.log.info(`Send to MPD ${fileName}`);
180
204
  this.adapter.sendTo('mpd', 'say', fileName);
181
205
  } else {
@@ -185,7 +209,7 @@ class Speech2Device {
185
209
  return duration;
186
210
  }
187
211
 
188
- async sayItChromecast(text, language, volume, duration) {
212
+ async sayItChromecast(text, language, volume, duration, testOptions) {
189
213
  volume = volume || this.options.sayLastVolume;
190
214
 
191
215
  const result = await this.uploadToStates(text);
@@ -193,18 +217,20 @@ class Speech2Device {
193
217
  if (volume === 'null') {
194
218
  volume = 0;
195
219
  }
220
+ const webLink = await this.getWebLink(testOptions);
221
+ const chromecastDevice = (testOptions && testOptions.chromecastDevice) || this.adapter.config.chromecastDevice;
196
222
 
197
223
  //Create announcement JSON
198
224
  const announcement = {
199
- url: `${this.options.webLink}${result.fileInDB}`,
225
+ url: `${webLink}${result.fileInDB}`,
200
226
  };
201
227
  if (volume) {
202
228
  announcement.volume = volume;
203
229
  }
204
230
  const announcementJSON = JSON.stringify(announcement);
205
231
 
206
- if (this.adapter.config.chromecastDevice && this.options.webLink) {
207
- const chromecastAnnouncementDev = `${this.adapter.config.chromecastDevice}.player.announcement`;
232
+ if (chromecastDevice && webLink) {
233
+ const chromecastAnnouncementDev = `${chromecastDevice}.player.announcement`;
208
234
  this.adapter.log.info(`Set "${chromecastAnnouncementDev} to ${announcementJSON}`);
209
235
  await this.adapter.setForeignStateAsync(chromecastAnnouncementDev, announcementJSON);
210
236
  // Check every 500 ms if the announcement has finished playing
@@ -296,7 +322,7 @@ class Speech2Device {
296
322
  });
297
323
  }
298
324
 
299
- async sayItGoogleHome(text, language, volume, duration) {
325
+ async sayItGoogleHome(text, language, volume, duration, testOptions) {
300
326
  if (!this.GHClient) {
301
327
  const {Client, DefaultMediaReceiver} = require('castv2-client');
302
328
  this.GHClient = Client;
@@ -308,12 +334,14 @@ class Speech2Device {
308
334
  if (volume === 'null' || volume === null) {
309
335
  volume = 0;
310
336
  }
337
+ const webLink = await this.getWebLink(testOptions);
338
+ const googleHomeServer = (testOptions && testOptions.googleHomeServer) || this.adapter.config.googleHomeServer;
311
339
 
312
- if (this.adapter.config.googleHomeServer && this.options.webLink) {
313
- const url = `${this.options.webLink}${result.fileInDB}`;
314
- this.adapter.log.debug(`Send to google home "${this.adapter.config.googleHomeServer}": ${url}`);
340
+ if (googleHomeServer && webLink) {
341
+ const url = `${webLink}${result.fileInDB}`;
342
+ this.adapter.log.debug(`Send to google home "${googleHomeServer}": ${url}`);
315
343
 
316
- await this.sendToGoogleHome(this.adapter.config.googleHomeServer, url, volume);
344
+ await this.sendToGoogleHome(googleHomeServer, url, volume);
317
345
  } else {
318
346
  throw new Error('Web server is unavailable!');
319
347
  }
@@ -321,34 +349,35 @@ class Speech2Device {
321
349
  return duration;
322
350
  }
323
351
 
324
- async sayItMP24(text, language, volume, duration) {
352
+ async sayItMP24(text, language, volume, duration, testOptions) {
325
353
  axios = axios || require('axios');
354
+ const mp24Server = (testOptions && testOptions.mp24Server) || this.adapter.config.mp24Server;
326
355
 
327
- if (this.adapter.config.mp24Server) {
356
+ if (mp24Server) {
328
357
  if (!Speech2Device.isPlayFile(text)) {
329
358
  // say
330
- this.adapter.log.debug(`Request MediaPlayer24 "http://${this.adapter.config.mp24Server}:50000/tts=${encodeURI(text)}"`);
359
+ this.adapter.log.debug(`Request MediaPlayer24 "http://${mp24Server}:50000/tts=${encodeURI(text)}"`);
331
360
  try {
332
- const response = await axios.get(`http://${this.adapter.config.mp24Server}:50000/tts=${encodeURI(text)}`);
333
- this.adapter.log.debug(`Response from MediaPlayer24 "${this.adapter.config.mp24Server}": ${response.data}`);
361
+ const response = await axios.get(`http://${mp24Server}:50000/tts=${encodeURI(text)}`);
362
+ this.adapter.log.debug(`Response from MediaPlayer24 "${mp24Server}": ${response.data}`);
334
363
  } catch (e) {
335
364
  if (e.message === 'Parse Error') {
336
365
  this.adapter.log.debug('Played successfully');
337
366
  } else {
338
- this.adapter.log.error(`Cannot say text on MediaPlayer24 "${this.adapter.config.mp24Server}": ${e.message}`);
367
+ this.adapter.log.error(`Cannot say text on MediaPlayer24 "${mp24Server}": ${e.message}`);
339
368
  throw e;
340
369
  }
341
370
  }
342
371
  } else {
343
372
  // play local file
344
373
  try {
345
- const response = await axios.get(`http://${this.adapter.config.mp24Server}:50000/track=${text}`);
346
- this.adapter.log.debug(`Response from MediaPlayer24 "${this.adapter.config.mp24Server}": ${response.data}`);
374
+ const response = await axios.get(`http://${mp24Server}:50000/track=${text}`);
375
+ this.adapter.log.debug(`Response from MediaPlayer24 "${mp24Server}": ${response.data}`);
347
376
  } catch (e) {
348
377
  if (e.message === 'Parse Error') {
349
378
  this.adapter.log.debug('Played successfully');
350
379
  } else {
351
- this.adapter.log.error(`Cannot say text on MediaPlayer24 "${this.adapter.config.mp24Server}": ${e.message}`);
380
+ this.adapter.log.error(`Cannot say text on MediaPlayer24 "${mp24Server}": ${e.message}`);
352
381
  throw e;
353
382
  }
354
383
  }
@@ -358,19 +387,23 @@ class Speech2Device {
358
387
  return duration + 2;
359
388
  }
360
389
 
361
- async sayItMP24ftp(text, language, volume, duration) {
390
+ async sayItMP24ftp(text, language, volume, duration, testOptions) {
362
391
  const result = await this.uploadToStates(text);
392
+ const mp24Server = (testOptions && testOptions.mp24Server) || this.adapter.config.mp24Server;
393
+ const ftpPort = (testOptions && testOptions.ftpPort) || this.adapter.config.ftpPort;
394
+ const ftpUser = (testOptions && testOptions.ftpUser) || this.adapter.config.ftpUser;
395
+ const ftpPassword = (testOptions && testOptions.ftpPassword) || this.adapter.config.ftpPassword;
363
396
 
364
397
  // Copy mp3 file to android device to play it later with MediaPlayer
365
- if (this.adapter.config.ftpPort && this.adapter.config.mp24Server) {
398
+ if (ftpPort && mp24Server) {
366
399
  jsftp = jsftp || require('jsftp');
367
400
  axios = axios || require('axios');
368
401
 
369
402
  const ftp = new jsftp({
370
- host: this.adapter.config.mp24Server,
371
- port: parseInt(this.adapter.config.ftpPort, 10), // defaults to 21
372
- user: this.adapter.config.ftpUser || 'anonymous', // defaults to 'anonymous'
373
- pass: this.adapter.config.ftpPassword || 'anonymous', // defaults to 'anonymous'
403
+ host: mp24Server,
404
+ port: parseInt(ftpPort, 10), // defaults to 21
405
+ user: ftpUser || 'anonymous', // defaults to 'anonymous'
406
+ pass: ftpPassword || 'anonymous', // defaults to 'anonymous'
374
407
  });
375
408
 
376
409
  await new Promise((resolve, reject) => {
@@ -385,15 +418,15 @@ class Speech2Device {
385
418
 
386
419
  if (!hadError) {
387
420
  try {
388
- const response = await axios.get(`http://${this.adapter.config.mp24Server}:50000/track=${fileNameOnFTP}`);
389
- this.adapter.log.debug(`Response from MediaPlayer24 "${this.adapter.config.mp24Server}": ${response.data}`);
421
+ const response = await axios.get(`http://${mp24Server}:50000/track=${fileNameOnFTP}`);
422
+ this.adapter.log.debug(`Response from MediaPlayer24 "${mp24Server}": ${response.data}`);
390
423
  resolve();
391
424
  } catch (e) {
392
425
  if (e.message === 'Parse Error') {
393
426
  this.adapter.log.debug('Played successfully');
394
427
  resolve();
395
428
  } else {
396
- this.adapter.log.error(`Cannot say text on MediaPlayer24 "${this.adapter.config.mp24Server}": ${e.message}`);
429
+ this.adapter.log.error(`Cannot say text on MediaPlayer24 "${mp24Server}": ${e.message}`);
397
430
  reject(e);
398
431
  }
399
432
  }
@@ -403,7 +436,7 @@ class Speech2Device {
403
436
  });
404
437
  });
405
438
  } catch (e) {
406
- throw new Error(`Cannot upload file to ${this.adapter.config.mp24Server}:${this.adapter.config.port}`);
439
+ throw new Error(`Cannot upload file to ${mp24Server}:${ftpPort}`);
407
440
  }
408
441
  });
409
442
  }
@@ -411,28 +444,30 @@ class Speech2Device {
411
444
  return duration + 2;
412
445
  }
413
446
 
414
- async sayItSystem(text, language, volume, duration) {
447
+ async sayItSystem(text, language, volume, duration, testOptions) {
415
448
  os = os || require('os');
416
449
  cp = cp || require('child_process');
417
450
 
418
451
  const result = await this.uploadToStates(text);
452
+ const systemCommand = (testOptions && testOptions.systemCommand) || this.adapter.config.systemCommand;
453
+ const systemPlayer = (testOptions && testOptions.systemPlayer) || this.adapter.config.systemPlayer;
419
454
 
420
455
  const p = os.platform();
421
456
  let cmd;
422
457
 
423
458
  if (volume !== undefined) {
424
- await this.sayItSystemVolume(volume);
459
+ await this.sayItSystemVolume(volume, testOptions);
425
460
  }
426
461
 
427
- if (this.adapter.config.systemCommand) {
462
+ if (systemCommand) {
428
463
  // custom command
429
- if (this.adapter.config.systemCommand.includes('%s')) {
430
- cmd = this.adapter.config.systemCommand.replace('%s', result.fileOnDisk);
464
+ if (systemCommand.includes('%s')) {
465
+ cmd = systemCommand.replace('%s', result.fileOnDisk);
431
466
  } else {
432
467
  if (p.match(/^win/)) {
433
- cmd = `${this.adapter.config.systemCommand} "${result.fileOnDisk}"`;
468
+ cmd = `${systemCommand} "${result.fileOnDisk}"`;
434
469
  } else {
435
- cmd = `${this.adapter.config.systemCommand} ${result.fileOnDisk}`;
470
+ cmd = `${systemCommand} ${result.fileOnDisk}`;
436
471
  }
437
472
  }
438
473
  try {
@@ -443,9 +478,9 @@ class Speech2Device {
443
478
  } else {
444
479
  if (p === 'linux') {
445
480
  // linux
446
- if (this.adapter.config.systemPlayer === 'omxplayer') {
481
+ if (systemPlayer === 'omxplayer') {
447
482
  cmd = `omxplayer -o local ${result.fileOnDisk}`;
448
- } else if (this.adapter.config.systemPlayer === 'mpg321') {
483
+ } else if (systemPlayer === 'mpg321') {
449
484
  cmd = `mpg321 -g ${this.options.sayLastVolume} ${result.fileOnDisk}`;
450
485
  } else {
451
486
  cmd = `mplayer ${result.fileOnDisk} -volume ${this.options.sayLastVolume}`;
@@ -479,10 +514,10 @@ class Speech2Device {
479
514
  }
480
515
  }
481
516
 
482
- async sayItWindows(text, language, volume, duration) {
517
+ async sayItWindows(text, language, volume, duration, testOptions) {
483
518
  // If mp3 file
484
519
  if (Speech2Device.isPlayFile(text)) {
485
- return this.sayItSystem(text, language, volume);
520
+ return this.sayItSystem(text, language, volume, duration, testOptions);
486
521
  }
487
522
 
488
523
  os = os || require('os');
@@ -491,7 +526,7 @@ class Speech2Device {
491
526
  const p = os.platform();
492
527
 
493
528
  if (volume || volume === 0) {
494
- await this.sayItSystemVolume(volume);
529
+ await this.sayItSystemVolume(volume, testOptions);
495
530
  }
496
531
 
497
532
  if (p.match(/^win/)) {
@@ -508,7 +543,7 @@ class Speech2Device {
508
543
  return duration + 2;
509
544
  }
510
545
 
511
- async sayItSystemVolume(level) {
546
+ async sayItSystemVolume(level, testOptions) {
512
547
  if ((!level && level !== 0) || level === 'null') {
513
548
  return;
514
549
  }
@@ -532,8 +567,9 @@ class Speech2Device {
532
567
  this.options.sayLastVolume = level;
533
568
 
534
569
  const p = os.platform();
570
+ const systemPlayer = (testOptions && testOptions.systemPlayer) || this.adapter.config.systemPlayer;
535
571
 
536
- if (p === 'linux' && this.adapter.config.player !== 'mpg321') {
572
+ if (p === 'linux' && systemPlayer !== 'mpg321') {
537
573
  // linux
538
574
  try {
539
575
  await this.spawn('amixer', ['cset', 'name="Master Playback Volume"', '--', `${level}%`]);
@@ -545,7 +581,7 @@ class Speech2Device {
545
581
  // windows volume is from 0 to 65535
546
582
  level = Math.round((65535 * level) / 100); // because this level is from 0 to 100
547
583
  try {
548
- await this.spawn(`${__dirname}/../nircmd/nircmdc.exe`, ['setsysvolume', level], true);
584
+ await this.spawn(path.normalize(`${__dirname}/../nircmd/nircmdc.exe`), ['setsysvolume', level], true);
549
585
  } catch (err) {
550
586
  this.adapter.log.error('nircmd is not available, so you may hear no audio.');
551
587
  }
@@ -559,27 +595,28 @@ class Speech2Device {
559
595
  }
560
596
  };
561
597
 
562
- async playFile(type, text, language, volume, duration) {
598
+ async playFile(type, text, language, volume, duration, testOptions) {
599
+ type = testOptions ? testOptions.type || type : type;
563
600
  if (type === 'browser') {
564
- return await this.sayItBrowser(text, language, volume, duration);
601
+ return await this.sayItBrowser(text, language, volume, duration, testOptions);
565
602
  } else if (type === 'mp24ftp') {
566
- return await this.sayItMP24ftp(text, language, volume, duration);
603
+ return await this.sayItMP24ftp(text, language, volume, duration, testOptions);
567
604
  } else if (type === 'mp24') {
568
- return await this.sayItMP24(text, language, volume, duration);
605
+ return await this.sayItMP24(text, language, volume, duration, testOptions);
569
606
  } else if (type === 'system') {
570
- return await this.sayItSystem(text, language, volume, duration);
607
+ return await this.sayItSystem(text, language, volume, duration, testOptions);
571
608
  } else if (type === 'windows') {
572
- return await this.sayItWindows(text, language, volume, duration);
609
+ return await this.sayItWindows(text, language, volume, duration, testOptions);
573
610
  } else if (type === 'sonos') {
574
- return await this.sayItSonos(text, language, volume, duration);
611
+ return await this.sayItSonos(text, language, volume, duration, testOptions);
575
612
  } else if (type === 'heos') {
576
- return await this.sayItHeos(text, language, volume, duration);
613
+ return await this.sayItHeos(text, language, volume, duration, testOptions);
577
614
  } else if (type === 'chromecast') {
578
- return await this.sayItChromecast(text, language, volume, duration);
615
+ return await this.sayItChromecast(text, language, volume, duration, testOptions);
579
616
  } else if (type === 'mpd') {
580
- return await this.sayItMpd(text, language, volume, duration);
617
+ return await this.sayItMpd(text, language, volume, duration, testOptions);
581
618
  } else if (type === 'googleHome') {
582
- return await this.sayItGoogleHome(text, language, volume, duration);
619
+ return await this.sayItGoogleHome(text, language, volume, duration, testOptions);
583
620
  } else {
584
621
  this.adapter.log.error(`Unknown play type: ${type}`);
585
622
  }
@@ -4,10 +4,11 @@ const mp3Duration = require('mp3-duration');
4
4
  const engines = require('../admin/engines.js');
5
5
  const sayitEngines = engines.sayitEngines;
6
6
  const { URLSearchParams } = require('url');
7
+ const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly');
8
+
7
9
  let cp;
8
10
  let googleTTS;
9
11
  let axios;
10
- let aws;
11
12
 
12
13
  class Text2Speech {
13
14
  constructor(adapter, options) {
@@ -17,8 +18,6 @@ class Text2Speech {
17
18
  this.getCachedFileName = options.getCachedFileName;
18
19
  this.isCached = options.isCached;
19
20
  this.MP3FILE = options.MP3FILE;
20
- this.cloudAppKey = null;
21
- this.cloudUrl = null;
22
21
  this.polly = null;
23
22
  }
24
23
 
@@ -95,7 +94,7 @@ class Text2Speech {
95
94
  });
96
95
  }
97
96
 
98
- async sayItGetSpeechGoogle(text, language, volume) {
97
+ async sayItGetSpeechGoogle(text, language, volume, testOptions) {
99
98
  if (!text.length) {
100
99
  throw new Error('No text to speak');
101
100
  }
@@ -104,12 +103,12 @@ class Text2Speech {
104
103
  if (text.length > 70) {
105
104
  const parts = Text2Speech.splitText(text);
106
105
  for (let t = 1; t < parts.length; t++) {
107
- this.addToQueue(parts[t], language, volume);
106
+ this.addToQueue(parts[t], language, volume, testOptions);
108
107
  }
109
108
  text = parts[0];
110
109
  }
111
110
 
112
- language = language || this.adapter.config.engine;
111
+ language = language || (testOptions && testOptions.engine) || this.adapter.config.engine;
113
112
 
114
113
  // get base64 text
115
114
  const data = await googleTTS.getAudioBase64(text, {
@@ -124,30 +123,34 @@ class Text2Speech {
124
123
  throw new Error('received file is too short');
125
124
  } else
126
125
  if (buf.toString().includes('302 Moved')) {
127
- throw new Error(`http://${this.options.host}${this.options.path}\nCannot get file: ${buf.toString()}`);
126
+ throw new Error(`https://translate.google.com\nCannot get file: ${buf.toString()}`);
128
127
  } else {
129
128
  fs.writeFileSync(this.MP3FILE, buf, 'binary');
130
129
  }
131
130
  }
132
131
 
133
- async sayItGetSpeechYandexCloud(text, language) {
132
+ async sayItGetSpeechYandexCloud(text, language, _, testOptions) {
134
133
  if (language === 'ru' || language === 'ru_YA' || language === 'ru_YA_CLOUD') {
135
134
  language = 'ru-RU';
136
135
  }
136
+ axios = axios || require('axios');
137
+ const yandexCloudVoice = (testOptions && testOptions.yandexCloudVoice) || this.adapter.config.yandexCloudVoice || '';
138
+ const yandexKey = (testOptions && testOptions.yandexKey) || this.adapter.config.yandexKey;
139
+ const yandexEmotion = (testOptions && testOptions.yandexEmotion) || this.adapter.config.yandexEmotion;
140
+ const yandexFolderID = (testOptions && testOptions.yandexFolderID) || this.adapter.config.yandexFolderID;
137
141
 
138
- const voice = this.adapter.config.yandexCloudVoice || '';
139
142
  const params = new URLSearchParams();
140
143
  params.append('text', text);
141
- params.append('voice', voice.replace(' Premium', ''));
142
- params.append('folderId', this.adapter.config.yandexFolderID || '');
143
- if (this.adapter.config.yandexEmotion !== 'none' && this.adapter.config.yandexEmotion) {
144
- params.append('emotion', this.adapter.config.yandexEmotion);
144
+ params.append('voice', yandexCloudVoice.replace(' Premium', ''));
145
+ params.append('folderId', yandexFolderID || '');
146
+ if (yandexEmotion !== 'none' && yandexEmotion) {
147
+ params.append('emotion', yandexEmotion);
145
148
  }
146
149
  params.append('lang', language);
147
150
 
148
151
  const response = await axios.post(`https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize`, params, {
149
152
  headers: {
150
- 'Authorization': `Api-Key ${this.adapter.config.yandexKey}`,
153
+ 'Authorization': `Api-Key ${yandexKey}`,
151
154
  },
152
155
  responseType: 'arraybuffer',
153
156
  });
@@ -158,7 +161,7 @@ class Text2Speech {
158
161
  fs.writeFileSync(this.MP3FILE, response.data, 'binary');
159
162
  }
160
163
 
161
- async sayItGetSpeechYandex(text, language) {
164
+ async sayItGetSpeechYandex(text, language, _, testOptions) {
162
165
  if (language === 'ru' || language === 'ru_YA') {
163
166
  language = 'ru-RU';
164
167
  }
@@ -168,22 +171,28 @@ class Text2Speech {
168
171
  ill: true, false
169
172
  robot: true, false
170
173
  */
174
+ const yandexVoice = (testOptions && testOptions.yandexVoice) || this.adapter.config.yandexVoice;
175
+ const yandexKey = (testOptions && testOptions.yandexKey) || this.adapter.config.yandexKey;
176
+ const yandexEmotion = (testOptions && testOptions.yandexEmotion) || this.adapter.config.yandexEmotion;
177
+ const yandexDrunk = (testOptions && testOptions.yandexDrunk !== undefined ? testOptions.yandexDrunk : this.adapter.config.yandexDrunk) || this.adapter.config.yandexDrunk;
178
+ const yandexIll = (testOptions && testOptions.yandexIll !== undefined ? testOptions.yandexIll : this.adapter.config.yandexIll) || this.adapter.config.yandexIll;
179
+ const yandexRobot = (testOptions && testOptions.yandexRobot !== undefined ? testOptions.yandexRobot : this.adapter.config.yandexRobot) || this.adapter.config.yandexRobot;
171
180
 
172
- let url = `https://tts.voicetech.yandex.net/generate?lang=${language}&format=mp3&speaker=${this.adapter.config.yandexVoice}&key=${this.adapter.config.yandexKey}&text=${encodeURI(text.trim())}`;
181
+ let url = `https://tts.voicetech.yandex.net/generate?lang=${language}&format=mp3&speaker=${yandexVoice}&key=${yandexKey}&text=${encodeURI(text.trim())}`;
173
182
 
174
- if (this.adapter.config.yandexEmotion && this.adapter.config.yandexEmotion !== 'none') {
175
- url += `&emotion=${this.adapter.config.yandexEmotion}`;
183
+ if (yandexEmotion && yandexEmotion !== 'none') {
184
+ url += `&emotion=${yandexEmotion}`;
176
185
  }
177
- if (this.adapter.config.yandexDrunk === 'true' || this.adapter.config.yandexDrunk === true) {
186
+ if (yandexDrunk === 'true' || yandexDrunk === true) {
178
187
  url += '&drunk=true';
179
188
  }
180
- if (this.adapter.config.yandexIll === 'true' || this.adapter.config.yandexIll === true) {
189
+ if (yandexIll === 'true' || yandexIll === true) {
181
190
  url += '&ill=true';
182
191
  }
183
- if (this.adapter.config.yandexRobot === 'true' || this.adapter.config.yandexRobot === true) {
192
+ if (yandexRobot === 'true' || yandexRobot === true) {
184
193
  url += '&robot=true';
185
194
  }
186
-
195
+ axios = axios || require('axios');
187
196
  const response = await axios.get(url, {responseType: 'arraybuffer'});
188
197
  if (!response.data || response.data.length < 100) {
189
198
  throw new Error('Cannot get file: received file is too short');
@@ -191,14 +200,28 @@ class Text2Speech {
191
200
  fs.writeFileSync(this.MP3FILE, response.data, 'binary');
192
201
  }
193
202
 
194
- sayItGetSpeechPolly(text, language) {
195
- aws = aws || require('aws-sdk');
203
+ async sayItGetSpeechPolly(text, language, _, testOptions) {
204
+ let _polly;
205
+ if (testOptions) {
206
+ _polly = new PollyClient({
207
+ region: (testOptions && testOptions.awsRegion) || this.adapter.config.awsRegion,
208
+ credentials: {
209
+ accessKeyId: (testOptions && testOptions.awsAccessKey) || this.adapter.config.awsAccessKey,
210
+ secretAccessKey: (testOptions && testOptions.awsSecretKey) || this.adapter.config.awsSecretKey,
211
+ },
212
+ });
213
+ } else {
214
+ this.polly = this.polly || new PollyClient({
215
+ region: this.adapter.config.awsRegion,
216
+ credentials: {
217
+ accessKeyId: this.adapter.config.awsAccessKey,
218
+ secretAccessKey: this.adapter.config.awsSecretKey,
219
+ },
220
+ });
221
+
222
+ _polly = this.polly;
223
+ }
196
224
 
197
- this.polly = this.polly || new aws.Polly({
198
- accessKeyId: this.adapter.config.awsAccessKey,
199
- secretAccessKey: this.adapter.config.awsSecretKey,
200
- region: this.adapter.config.awsRegion,
201
- });
202
225
  let type = 'text';
203
226
  if (text.match(/<[-+\w\s'"=]+>/)) {
204
227
  if (!text.match(/^<speak>/)) {
@@ -206,35 +229,30 @@ class Text2Speech {
206
229
  }
207
230
  type = 'ssml';
208
231
  }
209
- const params = {
210
- Text: text,
232
+
233
+ const pParams = {
211
234
  OutputFormat: 'mp3',
212
- TextType: type,
213
- VoiceId: sayitEngines[language].ename,
235
+ Text: text,
236
+ TextType: type || 'text',
237
+ VoiceId: sayitEngines[language].ename || 'Marlene',
214
238
  };
239
+ const command = new SynthesizeSpeechCommand(pParams);
215
240
 
216
- return new Promise((resolve, reject) => this.polly.synthesizeSpeech(params, (err, data) => {
217
- if (err) {
218
- reject(`Cannot get answer: ${JSON.stringify(err)}`);
219
- } else if (data) {
220
- if (data.AudioStream instanceof Buffer) {
221
- try {
222
- fs.writeFileSync(this.MP3FILE, data.AudioStream, 'binary');
223
- } catch (err) {
224
- return reject(`File error: ${err}`);
225
- }
226
- resolve();
227
- } else {
228
- reject(`Answer in invalid format: ${data ? data.toString() : 'null'}`);
229
- }
230
- }
231
- }));
241
+ const data = await _polly.send(command);
242
+ const byteArray = data && data.AudioStream && (await data.AudioStream.transformToByteArray());
243
+
244
+ // process data.
245
+ if (!byteArray || !byteArray.length) {
246
+ throw new Error('No data received');
247
+ } else {
248
+ fs.writeFileSync(this.MP3FILE, Buffer.from(byteArray), 'binary');
249
+ }
232
250
  }
233
251
 
234
- async sayItGetSpeechCoquiTTS(text, language) {
252
+ async sayItGetSpeechCoquiTTS(text, language, _, testOptions) {
235
253
  language = language.substring(0, 2);
236
254
  let cmd;
237
- const coquiVocoder = this.adapter.config.coquiVocoder;
255
+ const coquiVocoder = (testOptions && testOptions.coquiVocoder) || this.adapter.config.coquiVocoder;
238
256
  if (coquiVocoder === 'default') {
239
257
  cmd = `tts --text ". ${text} ." --model_name tts_models/${language}/${coquiVocoder.replace(' ', '/')} --out_path ${__dirname}/say.wav`;
240
258
  } else {
@@ -255,26 +273,35 @@ class Text2Speech {
255
273
  }
256
274
  }
257
275
 
258
- async sayItGetSpeechCloud(text, language) {
259
- axios = axios || require('axios');
260
-
261
- if (!this.cloudAppKey) {
262
- const obj = await this.adapter.getForeignObjectAsync(`system.this.adapter.${this.adapter.config.cloudInstance}`);
263
- this.cloudAppKey = obj && obj.native && obj.native.apikey ? obj.native.apikey : 'error';
264
- this.cloudUrl = (obj && obj.native && obj.native.cloudUrl) || '';
265
- if (this.cloudAppKey && this.cloudAppKey.match(/^@pro_/)) {
266
- if (!this.cloudUrl.includes('https://iobroker.pro:') &&
267
- !this.cloudUrl.includes('https://iobroker.info:')) {
268
- this.cloudUrl = 'https://iobroker.pro:10555';
276
+ sendToPromise(adapter, command, message, timeout) {
277
+ return this.adapter.getForeignStateAsync(`system.adapter.${adapter}.alive`)
278
+ .then(state => {
279
+ if (!state || !state.val) {
280
+ return Promise.reject(`Instance "${adapter}" is not running`);
269
281
  }
270
- }
271
- this.cloudUrl = this.cloudUrl.replace(/https:\/\//, '').replace(/:\d+/, '');
272
- }
273
282
 
274
- if (this.cloudAppKey === 'error') {
275
- throw new Error(`No app key found in "${this.adapter.config.cloudInstance}".`);
276
- }
283
+ return new Promise((resolve, reject) => {
284
+ let timer = setTimeout(() => {
285
+ timer = null;
286
+ reject(`Timeout (${timeout} ms) by sendTo "${adapter}"`);
287
+ }, timeout || 5000);
288
+
289
+ this.adapter.sendTo(adapter, command, message, response => {
290
+ if (timer) {
291
+ timer && clearTimeout(timer);
292
+ timer = null;
293
+ if (response.error) {
294
+ reject(response.error);
295
+ } else {
296
+ resolve(response);
297
+ }
298
+ }
299
+ });
300
+ });
301
+ });
302
+ }
277
303
 
304
+ async sayItGetSpeechCloud(text, language, _, testOptions) {
278
305
  let type = 'text';
279
306
  if (text.match(/<[-+\w\s'"=]+>/)) {
280
307
  if (!text.match(/^<speak>/)) {
@@ -282,23 +309,11 @@ class Text2Speech {
282
309
  }
283
310
  type = 'ssml';
284
311
  }
285
- const params = new URLSearchParams();
286
- params.append('Text', text);
287
- params.append('appkey', this.cloudAppKey);
288
- params.append('TextType', type);
289
- params.append('VoiceId', sayitEngines[language].ename);
290
312
 
291
- const response = await axios.post(`https://${this.cloudUrl}/this.polly/`, params, {
292
- headers: {
293
- 'Content-Type': 'application/x-www-form-urlencoded',
294
- },
295
- responseType: 'arraybuffer',
296
- })
313
+ // send message to cloud instance
314
+ const response = await this.sendToPromise(this.adapter.config.cloudInstance, 'tts', {text, voiceId: sayitEngines[language].ename, textType: type}, 10000);
297
315
 
298
- if (!response.data || response.data.length < 100) {
299
- throw new Error('Cannot get file: received file is too short');
300
- }
301
- fs.writeFileSync(this.MP3FILE, response.data, 'binary');
316
+ fs.writeFileSync(this.MP3FILE, Buffer.from(response.base64, 'base64'), 'binary');
302
317
  }
303
318
 
304
319
  async sayItGetSpeechPicoTTS(text, language) {
@@ -352,8 +367,8 @@ class Text2Speech {
352
367
  }
353
368
  };
354
369
 
355
- async sayItGetSpeech(text, language, volume) {
356
- if (this.adapter.config.cache) {
370
+ async sayItGetSpeech(text, language, volume, testOptions) {
371
+ if (this.adapter.config.cache && !testOptions) {
357
372
  const md5filename = this.isCached(this.options.cacheDir, `${language};${text}`, this.options.outFileExt, this.adapter.config.cacheExpiryDays);
358
373
 
359
374
  if (md5filename) {
@@ -371,25 +386,25 @@ class Text2Speech {
371
386
  const engine = sayitEngines[language].engine;
372
387
 
373
388
  if (engine === 'google') {
374
- await this.sayItGetSpeechGoogle(text, language, volume);
389
+ await this.sayItGetSpeechGoogle(text, language, volume, testOptions);
375
390
  } else if (engine === 'yandex') {
376
- await this.sayItGetSpeechYandex(text, language, volume);
391
+ await this.sayItGetSpeechYandex(text, language, null, testOptions);
377
392
  } else if (engine === 'yandexCloud') {
378
- await this.sayItGetSpeechYandexCloud(text, language, volume);
393
+ await this.sayItGetSpeechYandexCloud(text, language, null, testOptions);
379
394
  } else if (engine === 'polly') {
380
- await this.sayItGetSpeechPolly(text, language, volume);
395
+ await this.sayItGetSpeechPolly(text, language, null, testOptions);
381
396
  } else if (engine === 'coquiTTS') {
382
- await this.sayItGetSpeechCoquiTTS(text, language, volume);
397
+ await this.sayItGetSpeechCoquiTTS(text, language, null, testOptions);
383
398
  } else if (engine === 'cloud') {
384
- await this.sayItGetSpeechCloud(text, language, volume);
399
+ await this.sayItGetSpeechCloud(text, language, null, testOptions);
385
400
  } else if (engine === 'PicoTTS') {
386
- await this.sayItGetSpeechPicoTTS(text, language, volume);
401
+ await this.sayItGetSpeechPicoTTS(text, language, null, testOptions);
387
402
  } else {
388
403
  throw new Error(`Engine ${engine} not yet supported.`);
389
404
  }
390
405
  } else {
391
406
  // fallback to google
392
- await this.sayItGetSpeechGoogle(text, language, volume);
407
+ await this.sayItGetSpeechGoogle(text, language, volume, testOptions);
393
408
  }
394
409
 
395
410
  if (this.adapter.config.cache) {
package/main.js CHANGED
@@ -35,6 +35,7 @@ let speech2device = null;
35
35
  let MP3FILE;
36
36
  const tasks = [];
37
37
  let processing = false;
38
+ let helloCounter = 1;
38
39
 
39
40
  function startAdapter(options) {
40
41
  options = options || {};
@@ -78,7 +79,7 @@ function startAdapter(options) {
78
79
 
79
80
  adapter.on('objectChange', (id, obj) => {
80
81
  if (id === `system.adapter.${adapter.config.webInstance}`) {
81
- applyWebSettings(obj);
82
+ options.webLink = getWebLink(obj, adapter.config.webServer, adapter.config.webInstance);
82
83
  }
83
84
  });
84
85
 
@@ -166,6 +167,39 @@ function processMessage(obj) {
166
167
  }
167
168
  adapter.sendTo(obj.from, obj.command, list, obj.callback);
168
169
  });
170
+ } else if (obj.callback && obj.command === 'test') {
171
+ const language = (obj.message.engine || adapter.config.engine).substring(0, 2);
172
+ let text = 'Hello';
173
+ if (language === 'de') {
174
+ text = 'Hallo';
175
+ } else if (language === 'pl') {
176
+ text = 'Cześć';
177
+ } else if (language === 'uk') {
178
+ text = 'Привіт';
179
+ } else if (language === 'ru') {
180
+ text = 'Привет';
181
+ } else if (language === 'it') {
182
+ text = 'Ciao';
183
+ } else if (language === 'pt') {
184
+ text = 'Olá';
185
+ } else if (language === 'es') {
186
+ text = 'Hola';
187
+ } else if (language === 'fr') {
188
+ text = 'Bonjour';
189
+ } else if (language === 'nl') {
190
+ text = 'Hallo';
191
+ } else if (language === 'zh') {
192
+ text = '你好';
193
+ }
194
+ text += ` ${helloCounter++}`;
195
+ const opts = {...obj.message};
196
+ if (obj.callback) {
197
+ opts.callback = error => {
198
+ adapter.sendTo(obj.from, obj.command, {error, result: error ? undefined : 'Ok'}, obj.callback);
199
+ };
200
+ }
201
+
202
+ addToQueue(text, null, null, null, opts);
169
203
  }
170
204
  }
171
205
  }
@@ -210,7 +244,7 @@ function mkpathSync(rootpath, dirpath) {
210
244
  }
211
245
  }
212
246
 
213
- function addToQueue(text, language, volume, onlyCache) {
247
+ function addToQueue(text, language, volume, onlyCache, testOptions) {
214
248
  // Extract language from "en;volume;Text to say"
215
249
  if (text.includes(';')) {
216
250
  const arr = text.split(';', 3);
@@ -252,16 +286,24 @@ function addToQueue(text, language, volume, onlyCache) {
252
286
  volume = undefined;
253
287
  }
254
288
 
255
- const task = {text, language, volume, onlyCache, ts: Date.now(), combined};
289
+ let announce = testOptions && testOptions.announce !== undefined ? testOptions.announce : adapter.config.announce;
290
+ const annoTimeout = parseInt(testOptions && testOptions.annoTimeout !== undefined ? testOptions.annoTimeout : adapter.config.annoTimeout, 10);
291
+
292
+ const task = {text, language, volume, onlyCache, ts: Date.now(), combined, testOptions};
256
293
 
257
294
  // If more time than 15 seconds till last text, add announcement
258
- if (!onlyCache && adapter.config.announce && !tasks.length && (!lastSay || (Date.now() - lastSay > adapter.config.annoTimeout * 1000))) {
295
+ if (!onlyCache && announce && !tasks.length && (!lastSay || (Date.now() - lastSay > annoTimeout * 1000))) {
296
+ testOptions && prepareAnnounceFiles(testOptions);
297
+ const annoVolume = parseInt(testOptions && testOptions.annoVolume !== undefined ? testOptions.annoVolume : adapter.config.annoVolume, 10);
298
+ announce = testOptions && testOptions.announce !== undefined ? testOptions.announce : adapter.config.announce;
299
+
259
300
  // place as first the announcement mp3
260
301
  tasks.push({
261
- text: adapter.config.announce,
302
+ text: announce,
262
303
  language,
263
- volume: Math.round((volume || 70) / 100 * (parseInt(adapter.config.annoVolume, 10) || 50)),
264
- ts: task.ts
304
+ volume: Math.round((volume || 70) / 100 * (parseInt(annoVolume, 10) || 50)),
305
+ ts: task.ts,
306
+ testOptions
265
307
  });
266
308
  // and then text
267
309
  tasks.push(task);
@@ -303,12 +345,15 @@ async function processTasks() {
303
345
  return;
304
346
  }
305
347
  processing = true;
306
- let {text, language, volume, onlyCache} = tasks[0];
348
+ let {text, language, volume, onlyCache, testOptions} = tasks[0];
349
+ let error;
307
350
 
308
351
  if (text[0] === '!') {
309
352
  text = text.substring(1);
310
353
  }
311
- volume = parseInt(volume || adapter.config.volume, 10);
354
+ const type = (testOptions && testOptions.type) || adapter.config.type;
355
+
356
+ volume = parseInt(volume || (testOptions && testOptions.volume) || adapter.config.volume, 10);
312
357
  if (Number.isNaN(volume)) {
313
358
  volume = undefined;
314
359
  }
@@ -316,15 +361,15 @@ async function processTasks() {
316
361
  let fileName;
317
362
 
318
363
  // find out if say.mp3 must be generated
319
- const isGenerate = !Speech2Device.isPlayFile(text) && sayitOptions[adapter.config.type].mp3Required;
364
+ const isGenerate = !Speech2Device.isPlayFile(text) && sayitOptions[type].mp3Required;
320
365
 
321
- language = language || adapter.config.engine;
366
+ language = language || (testOptions && testOptions.engine) || adapter.config.engine;
322
367
 
323
368
  // if no text => do not process
324
369
  if (isGenerate && text.length && text2speech && speech2device) {
325
370
  // Check: may be it is a file from DB filesystem, like /vis.0/main/img/door-bell.mp3
326
371
  if (text[0] === '/') {
327
- if (adapter.config.cache || onlyCache) {
372
+ if (!testOptions && (adapter.config.cache || onlyCache)) {
328
373
  fileName = isCached(options.cacheDir, text, fileExt, adapter.config.cacheExpiryDays);
329
374
  }
330
375
 
@@ -376,19 +421,23 @@ async function processTasks() {
376
421
 
377
422
  // If text first must be generated, and it is not the same as last one
378
423
  if (!fileName && isGenerate) {
379
- if (sayLastGeneratedText !== `[${language}]${text}`) {
380
- if (adapter.config.cache) {
424
+ // do not cache if test options active, to test the voice generation too
425
+ if (sayLastGeneratedText !== `[${language}]${text}` || testOptions) {
426
+ if (adapter.config.cache && !testOptions) {
381
427
  let md5filename = isCached(options.cacheDir, `${language};${text}`, fileExt, adapter.config.cacheExpiryDays);
382
428
  if (md5filename) {
383
429
  fileName = md5filename;
384
- } else {
385
- try {
386
- fileName = await text2speech.sayItGetSpeech(text, language, volume);
387
- sayLastGeneratedText = `[${language}]${text}`;
388
- } catch (e) {
389
- fileName = null;
390
- adapter.log.error(`Cannot generate speech file: ${e}`);
391
- }
430
+ }
431
+ }
432
+
433
+ if (!fileName) {
434
+ try {
435
+ fileName = await text2speech.sayItGetSpeech(text, language, volume, testOptions);
436
+ sayLastGeneratedText = `[${language}]${text}`;
437
+ } catch (e) {
438
+ fileName = null;
439
+ error = `Cannot generate speech file: ${e}`;
440
+ adapter.log.error(error);
392
441
  }
393
442
  }
394
443
  } else {
@@ -405,21 +454,27 @@ async function processTasks() {
405
454
  // play file
406
455
  if (fileName) {
407
456
  duration = await text2speech.getDuration(fileName);
408
- duration = await speech2device.playFile(adapter.config.type, fileName, language, volume, duration);
457
+ duration = await speech2device.playFile(type, fileName, language, volume, duration, testOptions);
409
458
  } else if (!isGenerate) {
410
459
  if (Speech2Device.isPlayFile(text)) {
411
460
  duration = await text2speech.getDuration(text);
412
461
  }
413
462
 
414
- duration = await speech2device.playFile(adapter.config.type, text, language, volume, duration);
463
+ duration = await speech2device.playFile(type, text, language, volume, duration, testOptions);
415
464
  }
416
465
  lastSay = Date.now();
417
466
  } catch (e) {
418
- adapter.log.error(`Cannot play file: ${e}`);
467
+ error = `Cannot play file: ${e}`;
468
+ adapter.log.error(error);
419
469
  }
420
470
  await adapter.setStateAsync('tts.playing', false, true);
421
471
  }
422
472
 
473
+ if (tasks[0] && tasks[0].testOptions && tasks[0].testOptions.callback) {
474
+ tasks[0].testOptions.callback(error);
475
+ tasks[0].testOptions.callback = null;
476
+ }
477
+
423
478
  tasks.shift();
424
479
 
425
480
  if (tasks.length) {
@@ -490,6 +545,36 @@ async function uploadFiles() {
490
545
  }
491
546
  }
492
547
 
548
+ async function prepareAnnounceFiles(config) {
549
+ if (config.announce) {
550
+ config.annoDuration = parseInt(config.annoDuration) || 0;
551
+ config.annoTimeout = parseInt(config.annoTimeout) || 15;
552
+ config.annoVolume = parseInt(config.annoVolume) || 70; // percent from actual volume
553
+
554
+ // remove "tts.userfiles/" from file name
555
+ const fileName = config.announce.split('/').pop();
556
+
557
+ if (!fs.existsSync(path.join(__dirname, fileName))) {
558
+ try {
559
+ const data = await adapter.readFileAsync(adapter.namespace, `tts.userfiles/${fileName}`);
560
+ if (data) {
561
+ try {
562
+ fs.writeFileSync(path.join(__dirname, fileName), data);
563
+ config.announce = path.join(__dirname, fileName);
564
+ } catch (e) {
565
+ adapter.log.error(`Cannot write file: ${e.toString()}`);
566
+ config.announce = '';
567
+ }
568
+ }
569
+ } catch (e) {
570
+ adapter.log.error(`Cannot read file: ${e.toString()}`);
571
+ config.announce = '';
572
+ }
573
+ } else {
574
+ config.announce = path.join(__dirname, fileName);
575
+ }
576
+ }
577
+ }
493
578
  async function start() {
494
579
  if (!adapter.config.convertedV1toV2) {
495
580
  const newConfig = JSON.parse(JSON.stringify(adapter.config));
@@ -599,34 +684,7 @@ async function start() {
599
684
  MP3FILE = path.normalize(path.join(adapter.config.dataDir, `${adapter.namespace}.say.${fileExt}`));
600
685
  options.outFileExt = fileExt;
601
686
 
602
- if (adapter.config.announce) {
603
- adapter.config.annoDuration = parseInt(adapter.config.annoDuration) || 0;
604
- adapter.config.annoTimeout = parseInt(adapter.config.annoTimeout) || 15;
605
- adapter.config.annoVolume = parseInt(adapter.config.annoVolume) || 70; // percent from actual volume
606
-
607
- // remove "tts.userfiles/" from file name
608
- const fileName = adapter.config.announce.split('/').pop();
609
-
610
- if (!fs.existsSync(path.join(__dirname, fileName))) {
611
- try {
612
- const data = await adapter.readFileAsync(adapter.namespace, `tts.userfiles/${fileName}`);
613
- if (data) {
614
- try {
615
- fs.writeFileSync(path.join(__dirname, fileName), data);
616
- adapter.config.announce = path.join(__dirname, fileName);
617
- } catch (e) {
618
- adapter.log.error(`Cannot write file: ${e.toString()}`);
619
- adapter.config.announce = '';
620
- }
621
- }
622
- } catch (e) {
623
- adapter.log.error(`Cannot read file: ${e.toString()}`);
624
- adapter.config.announce = '';
625
- }
626
- } else {
627
- adapter.config.announce = path.join(__dirname, fileName);
628
- }
629
- }
687
+ await prepareAnnounceFiles(adapter.config);
630
688
 
631
689
  // If cache enabled
632
690
  if (adapter.config.cache) {
@@ -704,8 +762,8 @@ async function start() {
704
762
  (adapter.config.type === 'mpd') ||
705
763
  (adapter.config.type === 'googleHome')
706
764
  ) {
707
- const settings = await adapter.getForeignObjectAsync(`system.adapter.${adapter.config.webInstance}`);
708
- applyWebSettings(null, settings);
765
+ const obj = await adapter.getForeignObjectAsync(`system.adapter.${adapter.config.webInstance}`);
766
+ options.webLink = getWebLink(obj, adapter.config.webServer, adapter.config.webInstance);
709
767
 
710
768
  // update web link on changes
711
769
  await adapter.subscribeForeignObjectsAsync(`system.adapter.${adapter.config.webInstance}`);
@@ -728,6 +786,7 @@ async function start() {
728
786
  options.addToQueue = addToQueue;
729
787
  options.getCachedFileName = getCachedFileName;
730
788
  options.isCached = isCached;
789
+ options.getWebLink = getWebLink;
731
790
  options.MP3FILE = MP3FILE;
732
791
  text2speech = new Text2Speech(adapter, options);
733
792
  speech2device = new Speech2Device(adapter, options);
@@ -762,31 +821,34 @@ async function start() {
762
821
  adapter.subscribeStates('*');
763
822
  }
764
823
 
765
- function applyWebSettings(obj) {
824
+ function getWebLink(obj, webServer, webInstance) {
825
+ let webLink = '';
766
826
  if (obj && obj.native) {
767
- options.webLink = 'http';
827
+ webLink = 'http';
768
828
  if (obj.native.auth) {
769
- adapter.log.error(`Cannot use server "${adapter.config.webInstance}" with authentication for sonos/heos/chromecast. Select other or create another one.`);
829
+ adapter.log.error(`Cannot use server "${obj._id}" with authentication for sonos/heos/chromecast. Select other or create another one.`);
770
830
  } else {
771
831
  if (obj.native.secure) {
772
- options.webLink += 's';
832
+ webLink += 's';
773
833
  }
774
- options.webLink += '://';
834
+ webLink += '://';
775
835
  if (obj.native.bind === 'localhost' || obj.native.bind === '127.0.0.1') {
776
- adapter.log.error(`Selected web server "${adapter.config.webInstance}" is only on local device available. Select other or create another one.`);
836
+ adapter.log.error(`Selected web server "${obj._id}" is only on local device available. Select other or create another one.`);
777
837
  } else {
778
838
  if (obj.native.bind === '0.0.0.0') {
779
- options.webLink += adapter.config.webServer;
839
+ webLink += webServer || adapter.config.webServer;
780
840
  } else {
781
- options.webLink += obj.native.bind;
841
+ webLink += obj.native.bind;
782
842
  }
783
843
  }
784
844
 
785
- options.webLink += `:${obj.native.port}`;
845
+ webLink += `:${obj.native.port}`;
786
846
  }
787
847
  } else {
788
- adapter.log.error(`Cannot read information about "${adapter.config.webInstance}". No web server is active`);
848
+ adapter.log.error(`Cannot read information about "${webInstance || adapter.config.webInstance}". No web server is active`);
789
849
  }
850
+
851
+ return webLink;
790
852
  }
791
853
 
792
854
  async function main() {
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "iobroker.sayit",
3
- "version": "2.1.1",
3
+ "version": "3.0.0",
4
4
  "description": "Text to speech interface for ioBroker.",
5
5
  "author": {
6
6
  "name": "bluefox",
7
7
  "email": "dogafox@gmail.com"
8
8
  },
9
+ "engines": {
10
+ "node": ">=14.0.0"
11
+ },
9
12
  "contributors": [
10
13
  {
11
14
  "name": "bluefox",
@@ -37,8 +40,8 @@
37
40
  },
38
41
  "dependencies": {
39
42
  "jsftp": "^2.1.3",
40
- "aws-sdk": "~2.1341.0",
41
- "@iobroker/adapter-core": "^2.6.7",
43
+ "@aws-sdk/client-polly": "^3.303.0",
44
+ "@iobroker/adapter-core": "^2.6.8",
42
45
  "google-tts-api": "^2.0.2",
43
46
  "axios": "^1.3.4",
44
47
  "mp3-duration": "^1.1.0"