iobroker.sayit 2.1.2 → 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,10 @@ 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
+
268
272
  ### 2.1.2 (2023-03-27)
269
273
  * (bluefox) Corrected engines with web-link
270
274
 
package/io-package.json CHANGED
@@ -1,8 +1,21 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "sayit",
4
- "version": "2.1.2",
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
+ },
6
19
  "2.1.2": {
7
20
  "en": "Corrected engines with web-link",
8
21
  "de": "Korrigierte Motoren mit Weblink",
@@ -78,18 +91,6 @@
78
91
  "es": "Se corrigieron errores en io-package.json",
79
92
  "pl": "Naprawiono błędy w io-package.json",
80
93
  "zh-cn": "修复了 io-package.json 中的错误"
81
- },
82
- "1.12.4": {
83
- "en": "Fixed errors in io-package.json",
84
- "de": "Fehler in io-package.json behoben",
85
- "ru": "Исправлены ошибки в io-package.json",
86
- "pt": "Corrigidos erros em io-package.json",
87
- "nl": "Fouten opgelost in io-package.json",
88
- "fr": "Correction d'erreurs dans io-package.json",
89
- "it": "Risolti errori in io-package.json",
90
- "es": "Se corrigieron errores en io-package.json",
91
- "pl": "Naprawiono błędy w io-package.json",
92
- "zh-cn": "修复了 io-package.json 中的错误"
93
94
  }
94
95
  },
95
96
  "title": "Text to speech",
@@ -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
 
@@ -201,17 +200,27 @@ class Text2Speech {
201
200
  fs.writeFileSync(this.MP3FILE, response.data, 'binary');
202
201
  }
203
202
 
204
- sayItGetSpeechPolly(text, language, _, testOptions) {
205
- aws = aws || require('aws-sdk');
206
- const awsAccessKey = (testOptions && testOptions.awsAccessKey) || this.adapter.config.awsAccessKey;
207
- const awsSecretKey = (testOptions && testOptions.awsSecretKey) || this.adapter.config.awsSecretKey;
208
- const awsRegion = (testOptions && testOptions.awsRegion) || this.adapter.config.awsRegion;
209
-
210
- this.polly = this.polly || new aws.Polly({
211
- accessKeyId: awsAccessKey,
212
- secretAccessKey: awsSecretKey,
213
- region: awsRegion,
214
- });
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
+ }
215
224
 
216
225
  let type = 'text';
217
226
  if (text.match(/<[-+\w\s'"=]+>/)) {
@@ -220,29 +229,24 @@ class Text2Speech {
220
229
  }
221
230
  type = 'ssml';
222
231
  }
223
- const params = {
224
- Text: text,
232
+
233
+ const pParams = {
225
234
  OutputFormat: 'mp3',
226
- TextType: type,
227
- VoiceId: sayitEngines[language].ename,
235
+ Text: text,
236
+ TextType: type || 'text',
237
+ VoiceId: sayitEngines[language].ename || 'Marlene',
228
238
  };
239
+ const command = new SynthesizeSpeechCommand(pParams);
229
240
 
230
- return new Promise((resolve, reject) => this.polly.synthesizeSpeech(params, (err, data) => {
231
- if (err) {
232
- reject(`Cannot get answer: ${JSON.stringify(err)}`);
233
- } else if (data) {
234
- if (data.AudioStream instanceof Buffer) {
235
- try {
236
- fs.writeFileSync(this.MP3FILE, data.AudioStream, 'binary');
237
- } catch (err) {
238
- return reject(`File error: ${err}`);
239
- }
240
- resolve();
241
- } else {
242
- reject(`Answer in invalid format: ${data ? data.toString() : 'null'}`);
243
- }
244
- }
245
- }));
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
+ }
246
250
  }
247
251
 
248
252
  async sayItGetSpeechCoquiTTS(text, language, _, testOptions) {
@@ -269,28 +273,35 @@ class Text2Speech {
269
273
  }
270
274
  }
271
275
 
272
- async sayItGetSpeechCloud(text, language, _, testOptions) {
273
- axios = axios || require('axios');
274
-
275
- if (!this.cloudAppKey) {
276
- const cloudInstance = (testOptions && testOptions.cloudInstance) || this.adapter.config.cloudInstance;
277
-
278
- const obj = await this.adapter.getForeignObjectAsync(`system.this.adapter.${cloudInstance}`);
279
- this.cloudAppKey = obj && obj.native && obj.native.apikey ? obj.native.apikey : 'error';
280
- this.cloudUrl = (obj && obj.native && obj.native.cloudUrl) || '';
281
- if (this.cloudAppKey && this.cloudAppKey.match(/^@pro_/)) {
282
- if (!this.cloudUrl.includes('https://iobroker.pro:') &&
283
- !this.cloudUrl.includes('https://iobroker.info:')) {
284
- 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`);
285
281
  }
286
- }
287
- this.cloudUrl = this.cloudUrl.replace(/https:\/\//, '').replace(/:\d+/, '');
288
- }
289
282
 
290
- if (this.cloudAppKey === 'error') {
291
- throw new Error(`No app key found in "${this.adapter.config.cloudInstance}".`);
292
- }
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
+ }
293
303
 
304
+ async sayItGetSpeechCloud(text, language, _, testOptions) {
294
305
  let type = 'text';
295
306
  if (text.match(/<[-+\w\s'"=]+>/)) {
296
307
  if (!text.match(/^<speak>/)) {
@@ -298,23 +309,11 @@ class Text2Speech {
298
309
  }
299
310
  type = 'ssml';
300
311
  }
301
- const params = new URLSearchParams();
302
- params.append('Text', text);
303
- params.append('appkey', this.cloudAppKey);
304
- params.append('TextType', type);
305
- params.append('VoiceId', sayitEngines[language].ename);
306
312
 
307
- const response = await axios.post(`https://${this.cloudUrl}/this.polly/`, params, {
308
- headers: {
309
- 'Content-Type': 'application/x-www-form-urlencoded',
310
- },
311
- responseType: 'arraybuffer',
312
- })
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);
313
315
 
314
- if (!response.data || response.data.length < 100) {
315
- throw new Error('Cannot get file: received file is too short');
316
- }
317
- fs.writeFileSync(this.MP3FILE, response.data, 'binary');
316
+ fs.writeFileSync(this.MP3FILE, Buffer.from(response.base64, 'base64'), 'binary');
318
317
  }
319
318
 
320
319
  async sayItGetSpeechPicoTTS(text, language) {
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 || {};
@@ -190,6 +191,7 @@ function processMessage(obj) {
190
191
  } else if (language === 'zh') {
191
192
  text = '你好';
192
193
  }
194
+ text += ` ${helloCounter++}`;
193
195
  const opts = {...obj.message};
194
196
  if (obj.callback) {
195
197
  opts.callback = error => {
@@ -284,15 +286,22 @@ function addToQueue(text, language, volume, onlyCache, testOptions) {
284
286
  volume = undefined;
285
287
  }
286
288
 
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
+
287
292
  const task = {text, language, volume, onlyCache, ts: Date.now(), combined, testOptions};
288
293
 
289
294
  // If more time than 15 seconds till last text, add announcement
290
- 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
+
291
300
  // place as first the announcement mp3
292
301
  tasks.push({
293
- text: adapter.config.announce,
302
+ text: announce,
294
303
  language,
295
- volume: Math.round((volume || 70) / 100 * (parseInt(adapter.config.annoVolume, 10) || 50)),
304
+ volume: Math.round((volume || 70) / 100 * (parseInt(annoVolume, 10) || 50)),
296
305
  ts: task.ts,
297
306
  testOptions
298
307
  });
@@ -342,7 +351,9 @@ async function processTasks() {
342
351
  if (text[0] === '!') {
343
352
  text = text.substring(1);
344
353
  }
345
- 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);
346
357
  if (Number.isNaN(volume)) {
347
358
  volume = undefined;
348
359
  }
@@ -350,7 +361,7 @@ async function processTasks() {
350
361
  let fileName;
351
362
 
352
363
  // find out if say.mp3 must be generated
353
- const isGenerate = !Speech2Device.isPlayFile(text) && sayitOptions[adapter.config.type].mp3Required;
364
+ const isGenerate = !Speech2Device.isPlayFile(text) && sayitOptions[type].mp3Required;
354
365
 
355
366
  language = language || (testOptions && testOptions.engine) || adapter.config.engine;
356
367
 
@@ -358,7 +369,7 @@ async function processTasks() {
358
369
  if (isGenerate && text.length && text2speech && speech2device) {
359
370
  // Check: may be it is a file from DB filesystem, like /vis.0/main/img/door-bell.mp3
360
371
  if (text[0] === '/') {
361
- if (adapter.config.cache || onlyCache) {
372
+ if (!testOptions && (adapter.config.cache || onlyCache)) {
362
373
  fileName = isCached(options.cacheDir, text, fileExt, adapter.config.cacheExpiryDays);
363
374
  }
364
375
 
@@ -410,6 +421,7 @@ async function processTasks() {
410
421
 
411
422
  // If text first must be generated, and it is not the same as last one
412
423
  if (!fileName && isGenerate) {
424
+ // do not cache if test options active, to test the voice generation too
413
425
  if (sayLastGeneratedText !== `[${language}]${text}` || testOptions) {
414
426
  if (adapter.config.cache && !testOptions) {
415
427
  let md5filename = isCached(options.cacheDir, `${language};${text}`, fileExt, adapter.config.cacheExpiryDays);
@@ -442,13 +454,13 @@ async function processTasks() {
442
454
  // play file
443
455
  if (fileName) {
444
456
  duration = await text2speech.getDuration(fileName);
445
- duration = await speech2device.playFile(adapter.config.type, fileName, language, volume, duration, testOptions);
457
+ duration = await speech2device.playFile(type, fileName, language, volume, duration, testOptions);
446
458
  } else if (!isGenerate) {
447
459
  if (Speech2Device.isPlayFile(text)) {
448
460
  duration = await text2speech.getDuration(text);
449
461
  }
450
462
 
451
- duration = await speech2device.playFile(adapter.config.type, text, language, volume, duration, testOptions);
463
+ duration = await speech2device.playFile(type, text, language, volume, duration, testOptions);
452
464
  }
453
465
  lastSay = Date.now();
454
466
  } catch (e) {
@@ -533,6 +545,36 @@ async function uploadFiles() {
533
545
  }
534
546
  }
535
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
+ }
536
578
  async function start() {
537
579
  if (!adapter.config.convertedV1toV2) {
538
580
  const newConfig = JSON.parse(JSON.stringify(adapter.config));
@@ -642,34 +684,7 @@ async function start() {
642
684
  MP3FILE = path.normalize(path.join(adapter.config.dataDir, `${adapter.namespace}.say.${fileExt}`));
643
685
  options.outFileExt = fileExt;
644
686
 
645
- if (adapter.config.announce) {
646
- adapter.config.annoDuration = parseInt(adapter.config.annoDuration) || 0;
647
- adapter.config.annoTimeout = parseInt(adapter.config.annoTimeout) || 15;
648
- adapter.config.annoVolume = parseInt(adapter.config.annoVolume) || 70; // percent from actual volume
649
-
650
- // remove "tts.userfiles/" from file name
651
- const fileName = adapter.config.announce.split('/').pop();
652
-
653
- if (!fs.existsSync(path.join(__dirname, fileName))) {
654
- try {
655
- const data = await adapter.readFileAsync(adapter.namespace, `tts.userfiles/${fileName}`);
656
- if (data) {
657
- try {
658
- fs.writeFileSync(path.join(__dirname, fileName), data);
659
- adapter.config.announce = path.join(__dirname, fileName);
660
- } catch (e) {
661
- adapter.log.error(`Cannot write file: ${e.toString()}`);
662
- adapter.config.announce = '';
663
- }
664
- }
665
- } catch (e) {
666
- adapter.log.error(`Cannot read file: ${e.toString()}`);
667
- adapter.config.announce = '';
668
- }
669
- } else {
670
- adapter.config.announce = path.join(__dirname, fileName);
671
- }
672
- }
687
+ await prepareAnnounceFiles(adapter.config);
673
688
 
674
689
  // If cache enabled
675
690
  if (adapter.config.cache) {
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "iobroker.sayit",
3
- "version": "2.1.2",
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"