iobroker.telegram 1.11.1 → 1.12.3

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
@@ -9,6 +9,8 @@
9
9
  [![Translation status](https://weblate.iobroker.net/widgets/adapters/-/telegram/svg-badge.svg)](https://weblate.iobroker.net/engage/adapters/?utm_source=widget)
10
10
  [![Downloads](https://img.shields.io/npm/dm/iobroker.telegram.svg)](https://www.npmjs.com/package/iobroker.telegram)
11
11
 
12
+ **This adapter uses Sentry libraries to automatically report exceptions and code errors to the developers.** For more details and for information how to disable the error reporting see [Sentry-Plugin Documentation](https://github.com/ioBroker/plugin-sentry#plugin-sentry)! Sentry reporting is used starting with js-controller 3.0.
13
+
12
14
  ## Configuration
13
15
  Ask [@BotFather](https://telegram.me/botfather) to create new bot ```/newbot```.
14
16
 
@@ -696,6 +698,7 @@ msg.payload = {
696
698
  "parse_mode": "MarkdownV2"
697
699
  }
698
700
  ```
701
+ Before sending it to `telegram.INSTANCE.communicate.responseJson you need to stringify the object!`
699
702
 
700
703
  <!--
701
704
  Placeholder for the next version (at the beginning of the line):
@@ -703,6 +706,17 @@ msg.payload = {
703
706
  -->
704
707
 
705
708
  ## Changelog
709
+ ### 1.12.3 (2022-04-19)
710
+ * (Apollon77) Make sure also not set states can be queried - will return "State not set" in this case!
711
+
712
+ ### 1.12.2 (2022-04-01)
713
+ * (Apollon77) Fix crash cases reported by Sentry
714
+
715
+ ### 1.12.0 (2022-03-21)
716
+ * (Apollon77) Add new JSON states communication.responseJson and communication.responseSilentJson to also accept json structures (stringified!) to send messages
717
+ * (Apollon77) Try to prevent adapter crashes when internet is not available
718
+ * (Apollon77) Add Sentry for crash reporting
719
+
706
720
  ### 1.11.1 (2022-01-27)
707
721
  * (bluefox) fixed the receiving files
708
722
 
@@ -188,6 +188,7 @@
188
188
  return showMessage(_('Password confirmation is not equal with password'));
189
189
  }
190
190
  //obj.password = encrypt('Zgfr56gFe87jJON', obj.password);
191
+ delete obj.passwordRepeat;
191
192
 
192
193
  callback(obj);
193
194
  }
package/io-package.json CHANGED
@@ -1,8 +1,44 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "telegram",
4
- "version": "1.11.1",
4
+ "version": "1.12.3",
5
5
  "news": {
6
+ "1.12.3": {
7
+ "en": "Make sure also not set states can be queried - will return \"State not set\" in this case!",
8
+ "de": "Stellen Sie sicher, dass auch nicht gesetzte Zustände abgefragt werden können - in diesem Fall wird \"Zustand nicht gesetzt\" zurückgegeben!",
9
+ "ru": "Убедитесь, что также можно запросить неустановленные состояния - в этом случае будет возвращено «Состояние не установлено»!",
10
+ "pt": "Certifique-se também de que os estados não definidos podem ser consultados - retornará \"Estado não definido\" neste caso!",
11
+ "nl": "Zorg ervoor dat ook niet-ingestelde staten kunnen worden opgevraagd - in dit geval wordt \"Status niet ingesteld\" geretourneerd!",
12
+ "fr": "Assurez-vous également que les états non définis peuvent être interrogés - renverra \"State not set\" dans ce cas !",
13
+ "it": "Assicurati che anche gli stati non impostati possano essere interrogati - in questo caso restituirà \"Stato non impostato\"!",
14
+ "es": "Asegúrese de que también se puedan consultar los estados no establecidos; ¡devolverá \"Estado no establecido\" en este caso!",
15
+ "pl": "Upewnij się, że również nieustawione stany mogą być odpytywane - w tym przypadku zwróci \"State not set\"!",
16
+ "zh-cn": "确保也可以查询未设置的状态 - 在这种情况下将返回“未设置状态”!"
17
+ },
18
+ "1.12.2": {
19
+ "en": "Fix crash cases reported by Sentry",
20
+ "de": "Von Sentry gemeldete Absturzfälle beheben",
21
+ "ru": "Исправить случаи сбоев, о которых сообщил Sentry",
22
+ "pt": "Corrigir casos de travamento relatados pelo Sentinela",
23
+ "nl": "Herstel crashgevallen gemeld door Sentry",
24
+ "fr": "Correction des cas de plantage signalés par Sentry",
25
+ "it": "Risolvi i casi di crash segnalati da Sentry",
26
+ "es": "Solucionar casos de fallas informados por Sentry",
27
+ "pl": "Napraw przypadki awarii zgłoszone przez Sentry",
28
+ "zh-cn": "修复 Sentry 报告的崩溃案例"
29
+ },
30
+ "1.12.0": {
31
+ "en": "Add new JSON states communication.responseJson and communication.responseSilentJson to also accept json structures (stringified!) to send messages\nTry to prevent adapter crashes when internet is not available \nAdd Sentry for crash reporting",
32
+ "de": "Fügen Sie die neuen JSON-Zustände communication.responseJson und communication.responseSilentJson hinzu, um auch JSON-Strukturen (stringifiziert!) zum Senden von Nachrichten zu akzeptieren\nVersuchen Sie, Adapterabstürze zu verhindern, wenn das Internet nicht verfügbar ist\nFügen Sie Sentry für Absturzberichte hinzu",
33
+ "ru": "Добавьте новые состояния JSON Communication.responseJson и Communication.responseSilentJson, чтобы также принимать структуры json (строковые!) для отправки сообщений.\nПостарайтесь предотвратить сбои адаптера, когда интернет недоступен\nДобавьте Sentry для отчетов о сбоях",
34
+ "pt": "Adicione novos estados JSON communication.responseJson e communication.responseSilentJson para também aceitar estruturas json (stringified!) para enviar mensagens\nTente evitar falhas no adaptador quando a internet não estiver disponível\nAdicionar Sentinela para relatórios de falhas",
35
+ "nl": "Voeg nieuwe JSON-staten communication.responseJson en communication.responseSilentJson toe om ook json-structuren (stringified!) te accepteren om berichten te verzenden\nProbeer adaptercrashes te voorkomen wanneer internet niet beschikbaar is\nSentry toevoegen voor crashrapportage",
36
+ "fr": "Ajoutez de nouveaux états JSON communication.responseJson et communication.responseSilentJson pour accepter également les structures json (stringifiées !) Pour envoyer des messages\nEssayez d'éviter les plantages de l'adaptateur lorsque Internet n'est pas disponible\nAjouter Sentry pour les rapports de plantage",
37
+ "it": "Aggiungi nuovi stati JSON communication.responseJson e communication.responseSilentJson per accettare anche strutture json (stringate!) Per inviare messaggi\nCerca di evitare che l'adattatore si arresti in modo anomalo quando Internet non è disponibile\nAggiungi Sentinella per la segnalazione degli arresti anomali",
38
+ "es": "Agregue nuevos estados JSON communication.responseJson y communication.responseSilentJson para aceptar también estructuras json (¡en cadena!) para enviar mensajes\nIntente evitar fallas en el adaptador cuando no haya Internet disponible\nAgregar Sentry para informes de fallas",
39
+ "pl": "Dodaj nowe stany JSON communication.responseJson i communication.responseSilentJson, aby akceptować również struktury json (stringified!) do wysyłania wiadomości\nStaraj się zapobiegać awariom adaptera, gdy internet nie jest dostępny\nDodaj Sentry do zgłaszania awarii",
40
+ "zh-cn": "添加新的 JSON 状态communication.responseJson 和communication.responseSilentJson 也接受json 结构(字符串化!)发送消息\n尝试在互联网不可用时防止适配器崩溃\n添加 Sentry 以进行崩溃报告"
41
+ },
6
42
  "1.11.1": {
7
43
  "en": "fixed the receiving files",
8
44
  "de": "die empfangenen Dateien repariert",
@@ -50,34 +86,6 @@
50
86
  "es": "Agregue el estado botSendRaw para permitir el procesamiento de los datos RAW enviados por bot\nAgregar nivel para js-controller 3.3\nArreglado el control de los estados.",
51
87
  "pl": "Dodaj stan botSendRaw, aby umożliwić przetwarzanie danych RAW wysyłanych przez bota\nDodaj warstwę dla kontrolera js 3.3\nPoprawiono kontrolę stanów",
52
88
  "zh-cn": "添加 botSendRaw 状态以允许处理 bot 发送的 RAW 数据\n为 js-controller 3.3 添加层\n修复了对状态的控制"
53
- },
54
- "1.9.0": {
55
- "en": "Added the option to not authenticate the new users\nAdded the option to disable system messages for specific users",
56
- "de": "Option hinzugefügt, die neuen Benutzer nicht zu authentifizieren\nOption zum Deaktivieren von Systemnachrichten für bestimmte Benutzer hinzugefügt",
57
- "ru": "Добавлена возможность не аутентифицировать новых пользователей\nДобавлена возможность отключить системные сообщения для определенных пользователей",
58
- "pt": "Adicionada a opção de não autenticar os novos usuários\nAdicionada a opção de desativar mensagens do sistema para usuários específicos",
59
- "nl": "De optie toegevoegd om de nieuwe gebruikers niet te authenticeren\nDe optie toegevoegd om systeemberichten voor specifieke gebruikers uit te schakelen",
60
- "fr": "Ajout de l'option pour ne pas authentifier les nouveaux utilisateurs\nAjout de l'option pour désactiver les messages système pour des utilisateurs spécifiques",
61
- "it": "Aggiunta l'opzione per non autenticare i nuovi utenti\nAggiunta l'opzione per disabilitare i messaggi di sistema per utenti specifici",
62
- "es": "Añadida la opción de no autenticar a los nuevos usuarios.\nSe agregó la opción para deshabilitar los mensajes del sistema para usuarios específicos.",
63
- "pl": "Dodano opcję, aby nie uwierzytelniać nowych użytkowników\nDodano opcję wyłączenia wiadomości systemowych dla określonych użytkowników",
64
- "zh-cn": "添加了不对新用户进行身份验证的选项\n添加了禁用特定用户的系统消息的选项"
65
- },
66
- "1.8.3": {
67
- "en": "corrected bug with many simultaneous requests \nformatting\nimplemented editMessageMedia and editMessageCaption\nEncrypt token \nCorrected error with password\nCorrected error with boolean easy controls",
68
- "de": "Fehler mit vielen gleichzeitigen Anfragen behoben\nFormatierung\neditMessageMedia und editMessageCaption implementiert\nToken verschlüsseln\nFehler mit Passwort behoben\nFehler mit booleschen einfachen Steuerelementen korrigiert",
69
- "ru": "исправлена ошибка с множеством одновременных запросов\nформатирование\nреализованы editMessageMedia и editMessageCaption\nЗашифровать токен\nИсправлена ошибка с паролем\nИсправлена ошибка с помощью простых логических элементов управления",
70
- "pt": "bug corrigido com muitas solicitações simultâneas\nformatação\nimplementado editMessageMedia e editMessageCaption\nCriptografar token\nErro corrigido com senha\nErro corrigido com controles fáceis booleanos",
71
- "nl": "bug gecorrigeerd met veel gelijktijdige verzoeken\nopmaak\ngeïmplementeerd editMessageMedia en editMessageCaption\nVersleutel token\nFout gecorrigeerd met wachtwoord\nFout gecorrigeerd met boolean easy controls",
72
- "fr": "bug corrigé avec de nombreuses requêtes simultanées\nmise en page\nimplémenté editMessageMedia et editMessageCaption\nChiffrer le jeton\nErreur corrigée avec le mot de passe\nErreur corrigée avec des commandes simples booléennes",
73
- "it": "bug corretto con molte richieste simultanee\nformattazione\nimplementato editMessageMedia e editMessageCaption\nCrittografa il token\nErrore corretto con password\nErrore corretto con controlli booleani facili",
74
- "es": "error corregido con muchas solicitudes simultáneas\nformateo\nimplementado editMessageMedia y editMessageCaption\nCifrar token\nError corregido con contraseña\nError corregido con controles booleanos fáciles",
75
- "pl": "poprawiony błąd z wieloma jednoczesnymi żądaniami\nformatowanie\nzaimplementowano editMessageMedia i editMessageCaption\nZaszyfruj token\nPoprawiony błąd z hasłem\nPoprawiony błąd z łatwymi kontrolkami boolowskimi",
76
- "zh-cn": "修正了许多同时请求的错误\n格式化\n实现了 editMessageMedia 和 editMessageCaption\n加密令牌\n更正密码错误\n使用布尔型简单控件更正错误"
77
- },
78
- "1.8.2": {
79
- "en": "fixed data types",
80
- "de": "Datentypen korrigiert"
81
89
  }
82
90
  },
83
91
  "title": "Telegram",
@@ -130,7 +138,17 @@
130
138
  {
131
139
  "js-controller": ">=3.3.0"
132
140
  }
133
- ]
141
+ ],
142
+ "globalDependencies": [
143
+ {
144
+ "admin": ">=4.0.9"
145
+ }
146
+ ],
147
+ "plugins": {
148
+ "sentry": {
149
+ "dsn": "https://ae1b374ffb5d40cbabe9bff369520972@sentry.iobroker.net/38"
150
+ }
151
+ }
134
152
  },
135
153
  "protectedNative": [
136
154
  "token",
@@ -308,6 +326,30 @@
308
326
  },
309
327
  "native": {}
310
328
  },
329
+ {
330
+ "_id": "communicate.responseJson",
331
+ "type": "state",
332
+ "common": {
333
+ "role": "json",
334
+ "name": "Send text through telegram with notification with json definition",
335
+ "type": "string",
336
+ "read": true,
337
+ "write": true
338
+ },
339
+ "native": {}
340
+ },
341
+ {
342
+ "_id": "communicate.responseSilentJson",
343
+ "type": "state",
344
+ "common": {
345
+ "role": "json",
346
+ "name": "Send text through telegram silently with json definition",
347
+ "type": "string",
348
+ "read": true,
349
+ "write": true
350
+ },
351
+ "native": {}
352
+ },
311
353
  {
312
354
  "_id": "communicate.users",
313
355
  "type": "state",
package/main.js CHANGED
@@ -75,7 +75,25 @@ const systemLang2CallMe = {
75
75
 
76
76
  function startAdapter(options) {
77
77
  options = options || {};
78
- Object.assign(options, {name: adapterName});
78
+ Object.assign(options, {
79
+ name: adapterName,
80
+ /**
81
+ * If the JS-Controller catches an unhandled error, this will be called
82
+ * so we have a chance to handle it ourself.
83
+ * @param {Error} err
84
+ */
85
+ error: (err) => {
86
+ // Identify unhandled errors originating from callbacks in scripts
87
+ // These are not caught by wrapping the execution code in try-catch
88
+ if (err ) {
89
+ const errStr = err.toString();
90
+ if (errStr.includes('getaddrinfo') || errStr.includes('api.telegram.org') || errStr.includes('EAI_AGAIN')) {
91
+ return true;
92
+ }
93
+ }
94
+ return false;
95
+ }
96
+ });
79
97
 
80
98
  adapter = new utils.Adapter(options);
81
99
 
@@ -275,14 +293,42 @@ function startAdapter(options) {
275
293
  if (state) {
276
294
  if (!state.ack) {
277
295
  if (id.endsWith('communicate.response')) {
296
+ if (typeof state.val === 'object') {
297
+ adapter.log.error(`communicate.response only supports passing a message to send as string. You provided ${JSON.stringofy(state.val)}. Please use "communicate.responseJson" instead with a stringified JSON object!`);
298
+ return;
299
+ }
278
300
  // Send to someone this message
279
301
  sendMessage(state.val)
280
302
  .then(data => adapter.setState('communicate.response', state.val, true));
281
303
  } else
282
304
  if (id.endsWith('communicate.responseSilent')) {
305
+ if (typeof state.val === 'object') {
306
+ adapter.log.error(`communicate.responseSilent only supports passing a message to send as string. You provided ${JSON.stringofy(state.val)}. Please use "communicate.responseSilentJson" instead with a stringified JSON object!`);
307
+ return;
308
+ }
283
309
  // Send to someone this message
284
310
  sendMessage(state.val, null, null, {disable_notification: true})
285
311
  .then(data => adapter.setState('communicate.responseSilent', state.val, true));
312
+ } else
313
+ if (id.endsWith('communicate.responseJson')) {
314
+ try {
315
+ const val = JSON.parse(state.val);
316
+ // Send to someone this message
317
+ sendMessage(val)
318
+ .then(data => adapter.setState('communicate.responseJson', state.val, true));
319
+ } catch (err) {
320
+ adapter.log.error(`could not parse Json in communicate.responseJon state: ${err.message}`);
321
+ }
322
+ } else
323
+ if (id.endsWith('communicate.responseSilentJson')) {
324
+ try {
325
+ const val = JSON.parse(state.val);
326
+ // Send to someone this message
327
+ sendMessage(val, null, null, {disable_notification: true})
328
+ .then(data => adapter.setState('communicate.responseSilent', state.val, true));
329
+ } catch (err) {
330
+ adapter.log.error(`could not parse Json in communicate.responseSilentJon state: ${err.message}`);
331
+ }
286
332
  }
287
333
  } else {
288
334
  if (commands[id] && commands[id].report) {
@@ -337,6 +383,9 @@ function sendSystemMessage(text) {
337
383
  }
338
384
 
339
385
  function getStatus(id, state) {
386
+ if (!state) {
387
+ state = {val: 'State not set'};
388
+ }
340
389
  if (commands[id].type === 'boolean') {
341
390
  return `${commands[id].alias} => ${state.val ? commands[id].onStatus || _('ON-Status') : commands[id].offStatus || _('OFF-Status')}`;
342
391
  } else {
@@ -2100,11 +2149,15 @@ async function main() {
2100
2149
  await adapter.subscribeStatesAsync('communicate.request');
2101
2150
  await adapter.subscribeStatesAsync('communicate.response');
2102
2151
  await adapter.subscribeStatesAsync('communicate.responseSilent');
2152
+ await adapter.subscribeStatesAsync('communicate.responseJson');
2153
+ await adapter.subscribeStatesAsync('communicate.responseSilentJson');
2103
2154
 
2104
2155
  // clear states
2105
2156
  await adapter.setStateAsync('communicate.request', '', true);
2106
2157
  await adapter.setStateAsync('communicate.response', '', true);
2107
2158
  await adapter.setStateAsync('communicate.responseSilent', '', true);
2159
+ await adapter.setStateAsync('communicate.responseJson', '', true);
2160
+ await adapter.setStateAsync('communicate.responseSilentJson', '', true);
2108
2161
  await adapter.setStateAsync('communicate.pathFile', '', true);
2109
2162
 
2110
2163
  adapter.config.password = adapter.config.password || '';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "iobroker.telegram",
3
3
  "description": "The adapter allows to send and receive telegram messages from ioBroker and to be a broker.",
4
- "version": "1.11.1",
4
+ "version": "1.12.3",
5
5
  "author": "bluefox <dogafox@gmail.com>",
6
6
  "homepage": "https://github.com/iobroker-community-adapters/ioBroker.telegram",
7
7
  "repository": {
@@ -20,15 +20,15 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "node-telegram-bot-api": "^0.56.0",
23
- "@iobroker/adapter-core": "^2.5.1",
24
- "axios": "^0.25.0"
23
+ "@iobroker/adapter-core": "^2.6.0",
24
+ "axios": "^0.26.1"
25
25
  },
26
26
  "devDependencies": {
27
- "@alcalzone/release-script": "^3.5.0",
28
- "@alcalzone/release-script-plugin-iobroker": "^3.5.0",
29
- "@alcalzone/release-script-plugin-license": "^3.5.0",
27
+ "@alcalzone/release-script": "^3.5.6",
28
+ "@alcalzone/release-script-plugin-iobroker": "^3.5.7",
29
+ "@alcalzone/release-script-plugin-license": "^3.5.3",
30
30
  "gulp": "^4.0.2",
31
- "mocha": "^9.2.0",
31
+ "mocha": "^9.2.2",
32
32
  "chai": "^4.3.6"
33
33
  },
34
34
  "bugs": {
package/admin/index.html DELETED
@@ -1,336 +0,0 @@
1
- <html>
2
- <head>
3
- <!-- these 4 files always have to be included -->
4
- <link rel="stylesheet" type="text/css" href="../../lib/css/themes/jquery-ui/redmond/jquery-ui.min.css"/>
5
- <script type="text/javascript" src="../../lib/js/jquery-1.11.1.min.js"></script>
6
- <script type="text/javascript" src="../../socket.io/socket.io.js"></script>
7
- <script type="text/javascript" src="../../lib/js/jquery-ui-1.10.3.full.min.js"></script>
8
-
9
- <!-- these three files have to be always included -->
10
- <link rel="stylesheet" type="text/css" href="../../css/adapter.css"/>
11
- <script type="text/javascript" src="../../js/translate.js"></script>
12
- <script type="text/javascript" src="../../js/adapter-settings.js"></script>
13
- <script type="text/javascript" src="words.js"></script>
14
-
15
- <style>
16
- .help {
17
- font-size: small
18
- }
19
- .inputStyle {
20
- width: 300px;
21
- }
22
- </style>
23
- <!-- you have to define 2 functions in the global scope: -->
24
- <script type="text/javascript">
25
-
26
- function encrypt(key, value) {
27
- var result="";
28
- for(var i = 0; i < value.length; ++i) {
29
- result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
30
- }
31
- return result;
32
- }
33
-
34
- function decrypt(key, value) {
35
- var result = "";
36
- for(var i = 0; i < value.length; ++i) {
37
- result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
38
- }
39
- return result;
40
- }
41
-
42
- function showHideSettings() {
43
- if ($('#server').val() === 'true') {
44
- $('#tabs').tabs('option', 'disabled', []);
45
- $('.pollingIntervalSub').hide();
46
- $('.le-settings').show();
47
-
48
- if ($('#leEnabled').prop('checked')) {
49
- $('.le-sub-settings').show();
50
- if ($('#leUpdate').prop('checked')) {
51
- $('.le-sub-settings-update').show();
52
- } else {
53
- $('.le-sub-settings-update').hide();
54
- }
55
- } else {
56
- $('.le-sub-settings').hide();
57
- }
58
- } else {
59
- $('#tabs').tabs('option', 'disabled', [1]);
60
- $('.pollingIntervalSub').show();
61
- if($('#rememberUsers').prop('checked')) {
62
- $('.useUsernameSub').show();
63
- } else {
64
- $('.useUsernameSub').hide();
65
- }
66
- if ($('#proxy').prop('checked')) {
67
- $('.col-proxyHost').show();
68
- $('.col-proxyPort').show();
69
- $('.col-proxyLogin').show();
70
- $('.col-proxyPassword').show();
71
- } else {
72
- $('.col-proxyHost').hide();
73
- $('.col-proxyPort').hide();
74
- $('.col-proxyLogin').hide();
75
- $('.col-proxyPassword').hide();
76
- }
77
-
78
- }
79
-
80
- }
81
-
82
- // the function loadSettings has to exist ...
83
- function load(settings, onChange) {
84
- $('#tabs').tabs();
85
- settings.password = decrypt('Zgfr56gFe87jJON', settings.password);
86
-
87
- if (!settings.lePort) settings.lePort = 80;
88
- if (!settings.server) settings.server = 'false';
89
- if (!settings.pollingInterval) settings.pollingInterval = 300;
90
-
91
- getIPs(function(ips) {
92
- for (var i = 0; i < ips.length; i++) {
93
- $('#bind').append('<option value="' + ips[i].address + '">' + ips[i].name + '</option>');
94
- }
95
- $('#bind.value').val(settings.bind);
96
- });
97
-
98
- if (settings.restarted === undefined || settings.restarted === '_') settings.restarted = _('Started!');
99
- if (settings.restarting === undefined || settings.restarting === '_') settings.restarting = _('Restarting...');
100
-
101
- for (var key in settings) {
102
- if (!settings.hasOwnProperty(key)) continue;
103
- var $value = $('#' + key + '.value');
104
- if ($value.attr('type') === 'checkbox') {
105
- $value.prop('checked', settings[key]).change(function () {
106
- var id = $(this).attr('id');
107
- if (id === 'server' || id === 'leEnabled' || id === 'leUpdate' || id === 'rememberUsers' || id === 'proxy') showHideSettings();
108
- onChange();
109
- });
110
- } else {
111
- $value.val(settings[key]).change(function () {
112
- var id = $(this).attr('id');
113
- if (id === 'server' || id === 'leEnabled' || id === 'leUpdate' || id === 'rememberUsers' || id === 'proxy') showHideSettings();
114
- onChange();
115
- }).keyup(function () {
116
- $(this).trigger('change');
117
- });
118
- }
119
- }
120
-
121
- fillSelectCertificates('#certPublic', 'public', settings.certPublic);
122
- fillSelectCertificates('#certPrivate', 'private', settings.certPrivate);
123
- fillSelectCertificates('#certChained', 'chained', settings.certChained);
124
-
125
- getAdapterInstances('text2command', function (list) {
126
- var text = '<option value="">' + _('none') + '</option>';
127
- for (var l = 0; l < list.length; l++) {
128
- text += '<option value="' + list[l]._id +'" ' + (settings.text2command === list[l]._id ? 'selected' : '') + '>' + list[l]._id.replace('system.adapter.', '') + '</option>';
129
- }
130
- $('#text2command').html(text);
131
- });
132
- $('#passwordRepeat').val(settings.password);
133
-
134
- showHideSettings();
135
-
136
- // Signal to admin, that no changes yet
137
- onChange(false);
138
- }
139
-
140
- function save(callback) {
141
- // example: select elements with class=value and build settings object
142
- var obj = {};
143
- $('.value').each(function () {
144
- var $this = $(this);
145
- if ($this.attr('type') === 'checkbox') {
146
- obj[$this.attr('id')] = $this.prop('checked');
147
- } else {
148
- obj[$this.attr('id')] = $this.val();
149
- }
150
- });
151
-
152
- if ($('#server').val() === 'true') {
153
- if (!$('#leEnabled').prop('checked') && (!$('#certPublic').val() || !$('#certPrivate').val())) {
154
- showMessage(_('Set certificates or load it first in the system settings (right top).'));
155
- return;
156
- }
157
- if (!$('#url').val()) {
158
- showMessage(_('URL may not be empty'));
159
- }
160
- }
161
-
162
- if ($('#passwordRepeat').val() !== obj.password) {
163
- showMessage(_('Password confirmation is not equal with password'));
164
- return;
165
- }
166
- obj.password = encrypt('Zgfr56gFe87jJON', obj.password);
167
-
168
- callback(obj);
169
- }
170
- </script>
171
- </head>
172
- <body>
173
- <!-- you have to put your config page in a div with id adapter-container -->
174
- <div id="adapter-container">
175
- <table><tr>
176
- <td><img src="telegram.png" width="100px"></td>
177
- <td style="padding-top: 20px;padding-left: 10px"><h3 class="translate">telegram adapter settings</h3></td>
178
- </tr></table>
179
-
180
- <div id="tabs">
181
- <ul>
182
- <li><a href="#tabs-1" class="translate">Main settings</a></li>
183
- <li><a href="#tabs-2" class="translate">Server settings</a></li>
184
- </ul>
185
- <div id="tabs-1">
186
- <table style="width: 100%">
187
- <tr>
188
- <td colspan='3'><h4 class="translate" style="width: 90%">Main settings</h4></td>
189
- </tr>
190
- <tr>
191
- <td><label class="translate" for="server">Type</label></td>
192
- <td>
193
- <select id="server" class="value inputStyle" >
194
- <option value="false" class="translate">polling</option>
195
- <option value="true" class="translate">server</option>
196
- </select>
197
- </td>
198
- <td></td>
199
- </tr>
200
- <tr class="server pollingIntervalSub">
201
- <td class="translate">Polling interval (ms)</td>
202
- <td><input id="pollingInterval" class="value inputStyle" /></td>
203
- <td></td>
204
- </tr>
205
- <tr>
206
- <td class="translate">Token</td>
207
- <td><input id="token" class="value inputStyle" /></td>
208
- <td><a href="https://github.com/ioBroker/ioBroker.telegram#iobroker-telegram-adapter" target="_blank" class="translate help">Read README.md how to get token</a></td>
209
- </tr>
210
- <tr>
211
- <td class="translate">API URL</td>
212
- <td><input id="baseApiUrl" class="value inputStyle" /></td>
213
- </tr>
214
- <tr>
215
- <td class="translate">Password</td>
216
- <td><input id="password" class="value inputStyle" type="password"/></td>
217
- <td class="translate help">Leave it blank if no password desired</td>
218
- </tr>
219
- <tr>
220
- <td class="translate">Password repeat</td>
221
- <td><input id="passwordRepeat" class="inputStyle" type="password"/></td>
222
- <td class="translate help">Repeat password</td>
223
- </tr>
224
- <tr>
225
- <td class="translate">Text2Command Instance</td>
226
- <td><select id="text2command" class="value inputStyle"></select></td>
227
- <td class="translate help">All requests will be sent to this text2Command instance</td>
228
- </tr>
229
- <tr>
230
- <td class="translate">Store user's IDs</td>
231
- <td><input id="rememberUsers" class="value" type="checkbox"/></td>
232
- <td class="translate help">Remember authenticated users</td>
233
- </tr>
234
- <tr class="useUsernameSub">
235
- <td class="translate">Store username not firstname</td>
236
- <td><input id="useUsername" class="value" type="checkbox"/></td>
237
- <td class="translate help">Store username instead of firstname of remembered users</td>
238
- </tr>
239
- <tr>
240
- <td class="translate">Proxy Socks5 enable</td>
241
- <td><input id="proxy" class="value" type="checkbox"/></td>
242
- </tr>
243
- <tr class="col-proxyHost">
244
- <td class="translate" for="proxyHost">proxy Host</td>
245
- <td><input id="proxyHost" class="value" type="text"/></td>
246
- <td class="translate help">proxy Host</td>
247
- </tr>
248
- <tr class="col-proxyPort">
249
- <td class="translate" for="proxyPort">port</td>
250
- <td><input class="value number" id="proxyPort" size="5" maxlength="5" type="number"/></td>
251
- <td class="translate help">port</td>
252
- </tr>
253
- <tr class="col-proxyLogin">
254
- <td class="translate" for="proxyLogin">Login</td>
255
- <td><input id="proxyLogin" class="value" type="text"/></td>
256
- <td class="translate help">Login</td>
257
- </tr>
258
- <tr class="col-proxyPassword">
259
- <td class="translate" for="proxyPassword">password</td>
260
- <td><input id="proxyPassword" class="value" type="password"/></td>
261
- <std class="translate help">password</td>
262
- </tr>
263
- <tr>
264
- <td class="translate">Store raw request</td>
265
- <td><input id="storeRawRequest" class="value" type="checkbox"/></td>
266
- <td class="translate help">Remember raw request data</td>
267
- </tr>
268
- <tr>
269
- <td class="translate">Save media files</td>
270
- <td><input id="saveFiles" class="value" type="checkbox"/></td>
271
- <td class="translate help">Save media files</td>
272
- </tr>
273
- <tr>
274
- <td class="translate">Path</td>
275
- <td><input id="path" class="value inputStyle" /></td>
276
- <td class="translate help">The path where files will be stored</td>
277
- </tr>
278
- <tr>
279
- <td colspan='3'><h4 class="translate" style="width: 90%">Texts</h4></td>
280
- </tr>
281
- <tr>
282
- <td class="translate">"Started" text</td>
283
- <td><input id="restarted" class="value inputStyle"/></td>
284
- <td class="translate help">restarted_help</td>
285
- </tr>
286
- <tr>
287
- <td class="translate">"Restarting" text</td>
288
- <td><input id="restarting" class="value inputStyle"/></td>
289
- <td class="translate help">restarting_help</td>
290
- </tr>
291
- </table>
292
- </div>
293
- <div id="tabs-2">
294
- <table style="width: 100%">
295
- <tr class="server">
296
- <td ><label class="translate" for="url">URL</label></td>
297
- <td><input class="value inputStyle" id="url"/></td>
298
- <td class="translate help">url_help</td>
299
- </tr>
300
- <tr class="server">
301
- <td ><label class="translate" for="bind">IP</label></td>
302
- <td colspan="2"><select class="value inputStyle" id="bind"></select></td>
303
- <td></td>
304
- </tr>
305
- <tr class="server">
306
- <td><label class="translate" for="port">Port</label></td>
307
- <td><input class="value" id="port" size="5" maxlength="5" type="number"/></td>
308
- <td class="translate help">port_help</td>
309
- </tr>
310
- <tr class="server">
311
- <td><label class="translate" for="certPublic">Public certificate</label></td>
312
- <td><select id="certPublic" class="value" style="width: 200px"></select></td>
313
- <td></td>
314
- </tr>
315
- <tr class="server">
316
- <td><label class="translate" for="certPrivate">Private certificate</label></td>
317
- <td><select id="certPrivate" class="value" style="width: 200px"></select></td>
318
- <td></td>
319
- </tr>
320
- <tr class="server">
321
- <td><label class="translate" for="certChained">Chained certificate</label></td>
322
- <td><select id="certChained" class="value" style="width: 200px"></select></td>
323
- <td></td>
324
- </tr>
325
- <tr class="server">
326
- <td colspan='3'><h4 class="translate" style="width: 90%">Let's Encrypt settings</h4></td>
327
- </tr>
328
- <tr class="server le-settings"><td><label for="leEnabled" class="translate">Use Lets Encrypt certificates</label></td><td><input class="value" id="leEnabled" type="checkbox" /></td><td></td></tr>
329
- <tr class="server le-settings le-sub-settings"><td><label for="leUpdate" class="translate">Use this instance for automatic update</label></td><td><input class="value" id="leUpdate" type="checkbox" /></td><td></td></tr>
330
- <tr class="server le-settings le-sub-settings le-sub-settings-update"><td><label for="lePort" class="translate">Port to check the domain</label></td><td><input class="value number" id="lePort" type="number" size="5" maxlength="5" /></td><td></td></tr>
331
- </table>
332
- </div>
333
- </div>
334
- </div>
335
- </body>
336
- </html>