iobroker.tr-064 4.2.16 → 4.2.17

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
@@ -133,6 +133,10 @@ To use the call monitor feature it must be first enabled in the AVM Fritz!Box.
133
133
  To enable the call monitor dial ```#96*5*``` and the TCP/IP Port 1012 will be opened. To close the port dial ```#96*4*```.
134
134
 
135
135
  ## Changelog
136
+ ### 4.2.17 (2022-09-16)
137
+ * (simatec/Apollon77) Prevent duplication of entries in configuration
138
+ * (Apollon77) Make sure active status of devices in jsonDeviceList is correct
139
+
136
140
  ### 4.2.16 (2022-03-21)
137
141
  * (Apollon77) Fix info logs on callee/caller
138
142
  * (Apollon77) Add special handling for potential broken external image links in phonebook
@@ -91,7 +91,7 @@
91
91
  ' <p>'+ newIndex +'</p>\n' +
92
92
  ' </td>\n' +
93
93
  ' <td>\n' +
94
- ' <input type="text" class="validate">\n' +
94
+ ' <input type="text" class="validate">\n' +
95
95
  ' </td>\n' +
96
96
  ' <td>\n' +
97
97
  ' <input type="text" class="validate">\n' +
@@ -144,10 +144,12 @@
144
144
  //look for devices on router
145
145
  function deviceLookup(onChange) {
146
146
  $('.load-wait').show();
147
- $('#chooseDevice').empty();
147
+ console.log('deviceLookup started');
148
148
  sendTo('tr-064.' + instance, 'discovery', {onlyActive: true, reread: false}, function (result) {
149
+ $('#chooseDevice').empty();
149
150
  $('.load-wait').hide();
150
151
  let arr = JSON.parse(result);
152
+ console.log('Got ' + arr.length + ' devices');
151
153
 
152
154
  for (let i = 0; i < arr.length; i++) {
153
155
  let newRow = '<tr>\n' +
@@ -226,19 +228,22 @@
226
228
  }
227
229
  }
228
230
 
229
- //defaul sort by name =)
231
+ //default sort by name =)
230
232
  $('#modalDeviceName').click();
231
233
  });
232
234
  }
233
235
 
234
236
  // the function loadSettings has to exist ...
235
237
  function load(settings, onChange) {
238
+ console.log('load started');
236
239
  if (systemConfig) {
237
240
  secret = (systemConfig && systemConfig.native && systemConfig.native.secret) || 'Zgfr56gFe87jJOM';
241
+ console.log('load started: system config existing');
238
242
  loadHelper(settings, onChange);
239
243
  return;
240
244
  }
241
245
  socket.emit('getObject', 'system.config', function (err, obj) {
246
+ console.log('load started: system config loaded');
242
247
  secret = (obj.native ? obj.native.secret : '') || 'Zgfr56gFe87jJOM';
243
248
  loadHelper(settings, onChange);
244
249
  });
@@ -300,19 +305,19 @@
300
305
 
301
306
  if ($key.attr('type') === 'checkbox') {
302
307
  // do not call onChange direct, because onChange could expect some arguments
303
- $key.prop('checked', sObj).on('change', () => onChange())
304
- ;
308
+ $key.prop('checked', sObj).on('change', () => onChange());
305
309
  } else {
306
310
  // do not call onChange direct, because onChange could expect some arguments
307
311
  $key.val(sObj)
308
312
  .on('change', () => onChange())
309
- .on('keyup', () => onChange())
310
- ;
313
+ .on('keyup', () => onChange());
311
314
  }
312
315
  });
313
316
 
317
+ $('#devices').empty();
314
318
  //read devices from settings and show in table
315
319
  let countDevices = settings.devices.length;
320
+ console.log('countDevices: ' + countDevices);
316
321
  if (countDevices > 0) {
317
322
  for (let i = 0; i < countDevices; i++) {
318
323
  addDeviceRow(onChange, settings.devices[i].name, settings.devices[i].ip, settings.devices[i].mac);
@@ -499,7 +504,7 @@
499
504
  <th class="translate" id="deviceName">name</th>
500
505
  <th class="translate" id="deviceIP">ip</th>
501
506
  <th class="translate" id="deviceMac">MAC</th>
502
- <th class="translate" id="deviceDelete"></th>
507
+ <th class="translate" id="deviceDelete">&nbsp;</th>
503
508
  </tr>
504
509
  </thead>
505
510
  <tbody id="devices">
package/admin/words.js CHANGED
@@ -8,9 +8,9 @@ systemDictionary = {
8
8
  "Calllists": { "en": "Calllists", "de": "Anruflisten", "ru": "Calllists", "pt": "Listas de chamadas", "nl": "Calllists", "fr": "Listes d'appels", "it": "Calllists", "es": "Calistas", "pl": "Listy połączeń", "zh-cn": "通话清单"},
9
9
  "Cannot find any device": { "en": "Cannot find new devices", "de": "Kein neues Gerät gefunden", "ru": "Ничего не найдено", "pt": "Não é possível encontrar novos dispositivos", "nl": "Kan geen nieuwe apparaten vinden", "fr": "Impossible de trouver de nouveaux appareils", "it": "Non riesci a trovare nuovi dispositivi", "es": "No puedo encontrar nuevos dispositivos", "pl": "Nie można znaleźć nowych urządzeń", "zh-cn": "无法找到新的设备"},
10
10
  "Choose Device": { "en": "Choose Device", "de": "Gerät auswählen", "ru": "Выберите устройство", "pt": "Escolha o dispositivo", "nl": "Kies apparaat", "fr": "Choisissez un appareil", "it": "Scegli dispositivo", "es": "Elegir dispositivo", "pl": "Wybierz urządzenie", "zh-cn": "选择设备"},
11
- "Close": { "en": "Close", "de": "Schließen", "ru": "Закрыть", "pt": "Fechar", "nl": "Dichtbij", "fr": "Fermer", "it": "Vicino", "es": "Cerca", "pl": "Blisko", "zh-cn": "关"},
11
+ "Close": { "en": "Close", "de": "Schließen", "ru": "Закрыть", "pt": "Fechar", "nl": "Dichtbij", "fr": "Fermer", "it": "Vicino", "es": "Cerca", "pl": "Blisko", "zh-cn": "关闭"},
12
12
  "Create Json device list": { "en": "Create JSON device list", "de": "JSON Geräteliste erstellen", "ru": "Создать список устройств JSON", "pt": "Criar lista de dispositivos JSON", "nl": "Maak een JSON-apparatenlijst", "fr": "Créer une liste de périphériques JSON", "it": "Crea un elenco di dispositivi JSON", "es": "Crear lista de dispositivos JSON", "pl": "Utwórz listę urządzeń JSON", "zh-cn": "创建JSON设备列表"},
13
- "Devices": { "en": "Devices", "de": "Geräte", "ru": "Устройства", "pt": "Dispositivos", "nl": "apparaten", "fr": "Dispositifs", "it": "dispositivi", "es": "Dispositivos", "pl": "Urządzenia", "zh-cn": "设备"},
13
+ "Devices": { "en": "Devices", "de": "Geräte", "ru": "Устройства", "pt": "Dispositivos", "nl": "Apparaten", "fr": "Dispositifs", "it": "dispositivi", "es": "Dispositivos", "pl": "Urządzenia", "zh-cn": "设备"},
14
14
  "ERROR": { "en": "Error", "de": "Fehler", "ru": "ОШИБКА", "pt": "ERRO", "nl": "FOUT", "fr": "ERREUR", "it": "ERRORE", "es": "ERROR", "pl": "BŁĄD", "zh-cn": "错误"},
15
15
  "Enable adapter first": { "en": "Please enable the TR-064 instance first", "de": "Bitte die TR-064 Instanz starten", "ru": "Сначала активируйте драйвер", "pt": "Ativar adaptador primeiro", "nl": "Schakel eerst de adapter in", "fr": "Activer d'abord l'adaptateur", "it": "Abilitare prima l'adattatore", "es": "Habilitar primero el adaptador", "pl": "Włącz najpierw adapter", "zh-cn": "第一个启用适配器"},
16
16
  "Find a device": { "en": "Search for devices", "de": "Geräte suchen", "ru": "Список устройств", "pt": "Encontre um dispositivo", "nl": "Zoek een apparaat", "fr": "Trouver un appareil", "it": "Trova un dispositivo", "es": "Encontrar un dispositivo", "pl": "Znajdź urządzenie", "zh-cn": "找到一个设备"},
@@ -24,7 +24,7 @@ systemDictionary = {
24
24
  "Missed calls": { "en": "List of missed calls", "de": "Liste der entgangenen Anrufe", "ru": "Список пропущенных звонков", "pt": "Lista de chamadas perdidas", "nl": "Lijst voor gemiste oproepen", "fr": "Liste des appels manqués", "it": "Elenco per chiamate perse", "es": "Lista de llamadas perdidas", "pl": "Lista nieodebranych połączeń", "zh-cn": "列表未接来电"},
25
25
  "Name": { "en": "Name", "de": "Name", "ru": "Имя", "pt": "Nome", "nl": "Naam", "fr": "prénom", "it": "Nome", "es": "Nombre", "pl": "Imię", "zh-cn": "名称"},
26
26
  "Not enabled": { "en": "You have to start %s before you can use this function!", "de": "%s muss gestartet sein, bevor diese Funktion verwendet werden kann!", "ru": "Вы должны включить / запустить %s адаптер, прежде чем сможете использовать эту функцию!", "pt": "Você precisa ativar / iniciar o adaptador %s antes de poder usar esta função!", "nl": "U moet %s adapter inschakelen / starten voordat u deze functie kunt gebruiken!", "fr": "Vous devez activer / démarrer l'adaptateur %s avant de pouvoir utiliser cette fonction!", "it": "Devi abilitare / avviare l'adattatore %s prima di poter usare questa funzione!", "es": "¡Debe habilitar / iniciar el adaptador %s antes de poder usar esta función!", "pl": "Musisz włączyć / uruchomić %s adapter, aby móc korzystać z tej funkcji!", "zh-cn": "您必须先启用/启动%s适配器,然后才能使用此功能!"},
27
- "Ok": { "en": "Ok", "de": "Ok", "ru": "Ok", "pt": "Ok", "nl": "OK", "fr": "D'accord", "it": "Ok", "es": "De acuerdo", "pl": "Dobrze", "zh-cn": "\"确定\""},
27
+ "Ok": { "en": "Ok", "de": "Ok", "ru": "Ok", "pt": "Ok", "nl": "OK", "fr": "D'accord", "it": "Ok", "es": "De acuerdo", "pl": "Dobrze", "zh-cn": "确定"},
28
28
  "Options": { "en": "Options", "de": "Optionen", "ru": "Параметры", "pt": "Opções", "nl": "opties", "fr": "Les options", "it": "Opzioni", "es": "Opciones", "pl": "Opcje", "zh-cn": "选件"},
29
29
  "Outbound": { "en": "List of outbound calls", "de": "Liste der ausgehenden Anrufe", "ru": "Список исходящих звонков", "pt": "Listar para chamadas de saída", "nl": "Lijst voor uitgaande oproepen", "fr": "Liste des appels sortants", "it": "Elenco per le chiamate in uscita", "es": "Lista para llamadas salientes", "pl": "Lista połączeń wychodzących", "zh-cn": "列出的电话"},
30
30
  "Password": { "en": "Password", "de": "Passwort", "ru": "Пароль", "pt": "Senha", "nl": "Wachtwoord", "fr": "Mot de passe", "it": "Parola d'ordine", "es": "Contraseña", "pl": "Hasło", "zh-cn": "密码"},
package/io-package.json CHANGED
@@ -1,8 +1,20 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "tr-064",
4
- "version": "4.2.16",
4
+ "version": "4.2.17",
5
5
  "news": {
6
+ "4.2.17": {
7
+ "en": "Prevent duplication of entries in configuration\nMake sure active status of devices in jsonDeviceList is correct",
8
+ "de": "Verhindern Sie die Vervielfältigung von Einträgen in der Konfiguration\nStellen Sie sicher, dass der aktive Status von Geräten in json Gerät Liste ist korrekt",
9
+ "ru": "Предотвратить дублирование записей в конфигурации\nУбедитесь, что активный статус устройств в json Устройства Список правильный",
10
+ "pt": "Impedir a duplicação de entradas na configuração\nCertifique-se de status ativo de dispositivos em json Dispositivo A lista é correta",
11
+ "nl": "Vertaling:\nZorg voor actieve status van apparaten in Json Vernietiging. List is correct",
12
+ "fr": "Prévenir les doubles emplois dans la configuration\nAssurez-vous de l'état actif des appareils en json Dispositif La liste est correcte",
13
+ "it": "Prevenire la duplicazione delle voci nella configurazione\nAssicurarsi lo stato attivo dei dispositivi in json Dispositivo La lista è corretta",
14
+ "es": "Prevenir la duplicación de entradas en configuración\nAsegúrese de que el estado activo de los dispositivos en json Dispositivo La lista es correcta",
15
+ "pl": "Wynalezienie wpisów w konfiguracji\nUmożliwić czynny status urządzeń w jsonie. Device Lista jest prawidłowa",
16
+ "zh-cn": "B. 组合中物品的预防重复\nB. 确保在丛金中确保装置的积极参与 证人 名单正确"
17
+ },
6
18
  "4.2.16": {
7
19
  "en": "Fix info logs on callee/caller\nAdd special handling for potential broken external image links in phonebook\nPrevent some crash cases reported by Sentry",
8
20
  "de": "Korrigieren Sie Info-Protokolle auf Angerufenem/Anrufer\nFügen Sie eine spezielle Behandlung für potenziell defekte externe Bildlinks im Telefonbuch hinzu\nVerhindern Sie einige von Sentry gemeldete Absturzfälle",
@@ -74,18 +86,6 @@
74
86
  "es": "corregir la detección de reinicio de identificación para llamadas individuales",
75
87
  "pl": "naprawiono wykrywanie resetowania identyfikatora dla pojedynczych połączeń",
76
88
  "zh-cn": "修复单个呼叫的ID重置检测"
77
- },
78
- "4.2.10": {
79
- "en": "better handle caller id resets by reboots/FW updates to also update list specific counter and log when this happened",
80
- "de": "Besseres Behandeln des Zurücksetzens der Anrufer-ID durch Neustarts / FW-Aktualisierungen, um auch den listenspezifischen Zähler zu aktualisieren und zu protokollieren, wenn dies passiert ist",
81
- "ru": "лучше обрабатывать сброс идентификатора вызывающего абонента при перезагрузке / обновлении прошивки, чтобы также обновлять счетчик конкретного списка и регистрировать, когда это произошло",
82
- "pt": "lidar melhor com redefinições de identificador de chamadas por reinicializações / atualizações de FW para também atualizar o contador específico da lista e registrar quando isso aconteceu",
83
- "nl": "Beller-ID-resets beter afhandelen door reboots / FW-updates om ook de lijstspecifieke teller en het logboek bij te werken wanneer dit gebeurde",
84
- "fr": "mieux gérer les réinitialisations de l'identifiant de l'appelant par des redémarrages / mises à jour du micrologiciel pour également mettre à jour le compteur spécifique de la liste et le journal lorsque cela s'est produit",
85
- "it": "gestire meglio i ripristini dell'ID chiamante tramite riavvio / aggiornamenti FW per aggiornare anche il contatore specifico dell'elenco e il registro quando ciò è accaduto",
86
- "es": "manejar mejor los reinicios del identificador de llamadas mediante reinicios / actualizaciones de FW para actualizar también el contador específico de la lista y el registro cuando esto sucedió",
87
- "pl": "Lepsza obsługa resetowania identyfikatora dzwoniącego przez ponowne uruchomienie / aktualizacje FW, aby również zaktualizować określony licznik listy i dziennik, kiedy to się stało",
88
- "zh-cn": "通过重新启动/固件更新更好地处理呼叫者ID重置,以便还更新列表特定计数器并在发生这种情况时进行记录"
89
89
  }
90
90
  },
91
91
  "title": "TR-064",
package/main.js CHANGED
@@ -152,7 +152,7 @@ const CHANNEL_CALLLISTS = 'calllists';
152
152
  const CHANNEL_CALLMONITOR = 'callmonitor';
153
153
 
154
154
  let devStates;
155
- const allDevices = [];
155
+ let allDevices = [];
156
156
  const ipActive = {};
157
157
 
158
158
  const states = {
@@ -249,8 +249,9 @@ function onMessage(obj) {
249
249
  let onlyActive;
250
250
  let reread;
251
251
 
252
+ adapter.log.debug('onMessage: ' + JSON.stringify(obj));
252
253
  switch (obj.command) {
253
- case 'discovery':
254
+ case 'discovery': {
254
255
  if (typeof obj.message === 'object') {
255
256
  onlyActive = obj.message.onlyActive;
256
257
  reread = obj.message.reread;
@@ -259,28 +260,36 @@ function onMessage(obj) {
259
260
  return false;
260
261
  }
261
262
  if (!reread && allDevices.length > 0 && allDevices.onlyActive === onlyActive) {
263
+ adapter.log.debug('Discovery result: ' + JSON.stringify(allDevices));
262
264
  adapter.sendTo(obj.from, obj.command, JSON.stringify(allDevices), obj.callback);
263
265
  return true;
264
266
  }
265
- allDevices.onlyActive = onlyActive;
267
+
268
+ const newAllDevices = [];
269
+ newAllDevices.onlyActive = onlyActive;
270
+ let responseSent = false;
266
271
 
267
272
  tr064Client.forEachHostEntry((err, device, cnt, all) => {
268
273
  const active = !!(~~device.NewActive);
269
274
 
270
275
  if (!onlyActive || active) {
271
- allDevices.push ({
276
+ newAllDevices.push({
272
277
  name: device.NewHostName,
273
278
  ip: device.NewIPAddress,
274
279
  mac: device.NewMACAddress,
275
280
  active: active
276
281
  });
277
282
  }
278
- if (cnt + 1 >= all) {
279
- adapter.sendTo(obj.from, obj.command, JSON.stringify(allDevices), obj.callback);
283
+ adapter.log.debug('Discovery Add (' + cnt + '/' + all + '): ' + device.NewHostName + ' ' + device.NewIPAddress + ' ' + device.NewMACAddress + ' ' + device.NewActive);
284
+ if (cnt + 1 >= all && !responseSent) {
285
+ responseSent = true;
286
+ allDevices = newAllDevices;
287
+ adapter.log.debug('Discovery result: ' + JSON.stringify(allDevices));
288
+ adapter.sendTo(obj.from, obj.command, JSON.stringify(newAllDevices), obj.callback);
280
289
  }
281
290
  });
282
291
  return true;
283
-
292
+ }
284
293
  default:
285
294
  adapter.log.warn('Unknown command: ' + obj.command);
286
295
  break;
@@ -1087,7 +1096,7 @@ function createConfiguredDevices(callback) {
1087
1096
  }
1088
1097
  dev.setChannelEx(device.NewHostName, { common: { name: device.NewHostName + ' (' + device.NewIPAddress + ')', role: 'channel' }, native: { mac: device.NewMACAddress }} );
1089
1098
  setActive(dev, device.NewActive, device.NewIPAddress, device.NewMACAddress);
1090
- arr.push( { active: !!device.NewActive, ip: device.NewIPAddress, name: device.NewHostName, mac: device.NewMACAddress } );
1099
+ arr.push( { active: !!(~~device.NewActive), ip: device.NewIPAddress, name: device.NewHostName, mac: device.NewMACAddress } );
1091
1100
  });
1092
1101
  }
1093
1102
 
@@ -1110,7 +1119,7 @@ function updateDevices(callback) {
1110
1119
  dev.setChannelEx(device.NewHostName);
1111
1120
  setActive(dev, device.NewActive, device.NewIPAddress, device.NewMACAddress);
1112
1121
  if (adapter.config.jsonDeviceList) {
1113
- arr.push( { active: !!device.NewActive, ip: device.NewIPAddress, name: device.NewHostName, mac: device.NewMACAddress } );
1122
+ arr.push( { active: !!(~~device.NewActive), ip: device.NewIPAddress, name: device.NewHostName, mac: device.NewMACAddress } );
1114
1123
  }
1115
1124
  });
1116
1125
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.tr-064",
3
- "version": "4.2.16",
3
+ "version": "4.2.17",
4
4
  "description": "ioBroker tr-064 Adapter",
5
5
  "author": {
6
6
  "name": "soef",
@@ -31,18 +31,18 @@
31
31
  "mdns-discovery": "^0.2.6",
32
32
  "tr-O64": "^0.2.4",
33
33
  "xml2js": "^0.4.23",
34
- "@iobroker/adapter-core": "^2.6.0"
34
+ "@iobroker/adapter-core": "^2.6.6"
35
35
  },
36
36
  "devDependencies": {
37
- "@alcalzone/release-script": "^3.5.6",
38
- "@alcalzone/release-script-plugin-iobroker": "^3.5.7",
39
- "@alcalzone/release-script-plugin-license": "^3.5.3",
40
- "gulp": "^4.0.2",
41
- "mocha": "^9.2.2",
37
+ "@alcalzone/release-script": "^3.5.9",
38
+ "@alcalzone/release-script-plugin-iobroker": "^3.5.9",
39
+ "@alcalzone/release-script-plugin-license": "^3.5.9",
40
+ "@iobroker/adapter-dev": "^1.1.0",
41
+ "@iobroker/dev-server": "^0.5.0",
42
+ "@iobroker/testing": "^4.1.0",
43
+ "mocha": "^10.0.0",
42
44
  "chai": "^4.3.6",
43
- "axios": "^0.26.1",
44
- "@iobroker/testing": "^2.5.6",
45
- "eslint": "^8.11.0"
45
+ "eslint": "^8.23.1"
46
46
  },
47
47
  "main": "main.js",
48
48
  "scripts": {
@@ -53,7 +53,8 @@
53
53
  "release": "release-script",
54
54
  "release-patch": "release-script patch --yes",
55
55
  "release-minor": "release-script minor --yes",
56
- "release-major": "release-script major --yes"
56
+ "release-major": "release-script major --yes",
57
+ "translate": "translate-adapter"
57
58
  },
58
59
  "engines": {
59
60
  "node": ">=8.0.0"
@@ -1,3 +0,0 @@
1
- {
2
- "plugins": ["iobroker", "license"]
3
- }
package/lib/tools.js DELETED
@@ -1,80 +0,0 @@
1
- const axios = require('axios');
2
-
3
- /**
4
- * Tests whether the given variable is a real object and not an Array
5
- * @param {any} it The variable to test
6
- * @returns {it is Record<string, any>}
7
- */
8
- function isObject(it) {
9
- // This is necessary because:
10
- // typeof null === 'object'
11
- // typeof [] === 'object'
12
- // [] instanceof Object === true
13
- return Object.prototype.toString.call(it) === '[object Object]';
14
- }
15
-
16
- /**
17
- * Tests whether the given variable is really an Array
18
- * @param {any} it The variable to test
19
- * @returns {it is any[]}
20
- */
21
- function isArray(it) {
22
- if (Array.isArray != null) {
23
- return Array.isArray(it);
24
- }
25
- return Object.prototype.toString.call(it) === '[object Array]';
26
- }
27
-
28
- /**
29
- * Translates text using the Google Translate API
30
- * @param {string} text The text to translate
31
- * @param {string} targetLang The target languate
32
- * @param {string} yandex api key
33
- * @returns {Promise<string>}
34
- */
35
- async function translateText(text, targetLang, yandex) {
36
- if (targetLang === 'en') {
37
- return text;
38
- }
39
- if (yandex) {
40
- return await translateYandex(text, targetLang, yandex);
41
- } else {
42
- return await translateGoogle(text, targetLang);
43
- }
44
- }
45
-
46
- async function translateYandex(text, targetLang, yandex) {
47
- if (targetLang === 'zh-cn') {
48
- targetLang = 'zh';
49
- }
50
- try {
51
- const url = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandex}&text=${encodeURIComponent(text)}&lang=en-${targetLang}`;
52
- const response = await axios({url, timeout: 15000});
53
- if (response.data && response.data['text']) {
54
- return response.data['text'][0];
55
- }
56
- throw new Error('Invalid response for translate request');
57
- } catch (e) {
58
- throw new Error(`Could not translate to "${targetLang}": ${e}`);
59
- }
60
- }
61
-
62
- async function translateGoogle(text, targetLang) {
63
- try {
64
- const url = `http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}&ie=UTF-8&oe=UTF-8`;
65
- const response = await axios({url, timeout: 15000});
66
- if (isArray(response.data)) {
67
- // we got a valid response
68
- return response.data[0][0][0];
69
- }
70
- throw new Error('Invalid response for translate request');
71
- } catch (e) {
72
- throw new Error(`Could not translate to "${targetLang}": ${e}`);
73
- }
74
- }
75
-
76
- module.exports = {
77
- isArray,
78
- isObject,
79
- translateText
80
- };