iobroker.telegram 3.4.1 → 3.5.1

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.
@@ -0,0 +1,87 @@
1
+ {
2
+ "Allow state control": "Разрешить контроль состояния",
3
+ "Auth_No": "Нет, сохранить данные Пользователей!",
4
+ "Auth_Yes": "Да, удалить всех Пользователей!",
5
+ "Authenticated Users": "Аутентифицированные пользователи",
6
+ "Buttons in line": "Кнопок в строке",
7
+ "Call text": "Вас вызывает ioBroker. В вашем доме что-то произошло.",
8
+ "Chained certificate": "'Chained' сертификат",
9
+ "Changed_Password": "Вы изменили пароль для своего Бота. Вы хотите удалить всех сохраненных пользователей сейчас? Затем каждый пользователь должен повторно аутентифицироваться с новым паролем, прежде чем они смогут снова связаться с ботом.",
10
+ "Command to show the keyboard": "Команда отображения клавиатуры",
11
+ "Done": "Готово",
12
+ "ID \"%s\" not found.": "Идентификатор \" %s\" не найден.",
13
+ "Ignore warning": "Игнорировать предупреждение",
14
+ "Invalid number %s": "Неверное число %s",
15
+ "Invalid password": "Неверный пароль!",
16
+ "Keyboard command": "Вызов клавиатуры",
17
+ "Leave it blank if no password desired": "Оставить пустым, если пароль не требуется",
18
+ "Let's Encrypt settings": "Настройки Let's Encrypt",
19
+ "Listen on all IPs": "Ожидать соединения на всех IP адресах",
20
+ "Login": "Имя пользователя для proxy",
21
+ "Main settings": "Основные настройки",
22
+ "Message ignored: ": "Сообщение проигнорировано: ",
23
+ "Messages": "Сообщения",
24
+ "No_Password": "Вы не задали пароль. Если вы не установите пароль для своего бота, каждый незнакомец сможет общаться с вашим ботом! Настоятельно рекомендуется установить пароль!",
25
+ "OFF-Command": "выключить",
26
+ "OFF-Status": "выключен(о/а)",
27
+ "ON-Command": "включить",
28
+ "ON-Status": "включен(о/а)",
29
+ "Please enter password in form \"/password phrase\"": "Пожалуйста введите пароль в формате: \"/password phrase\"",
30
+ "Polling interval (ms)": "Интервал опроса (мс)",
31
+ "Port": "Порт",
32
+ "Port to check the domain:": "Порт для проверки доменного имени",
33
+ "Private certificate": "'Private' сертификат",
34
+ "Proxy Socks5 enable": "Включить Socks5 прокси",
35
+ "Public certificate": "'Public' сертификат",
36
+ "Read README.md how to get token": "В README.md можно найти информацию, как получить токен",
37
+ "Reauthenticate Users?": "Повторить проверку подлинности пользователей?",
38
+ "Remember authenticated users": "Запоминать ID клиентов, которые ввели пароль, что бы в дальнейшем его не спрашивать",
39
+ "Remember raw request data": "Сохраните исходный запрос для дальнейшей обработки (Внимание может содержать важные для безопасности данные!)",
40
+ "Repeat password": "Повторите пароль",
41
+ "Restarting...": "Перезапуск бота.",
42
+ "Restarting... Reauthenticate!": "Перезапуск ... Повторно аутентифицировать!",
43
+ "Select option": "Выберите опцию",
44
+ "Server settings": "Настройки сервера",
45
+ "Set Password": "Установка пароля",
46
+ "Set certificates or load it first in the system settings (right top).": "Нужно выбрать сертификаты или сначала загрузить их в системных настройках (вверху справа).",
47
+ "Show the list of rooms before the device selection": "Показывать список комнат до выбора устройства",
48
+ "Started!": "Бот запущен!",
49
+ "Store username instead of firstname of remembered users": "Сохранять логины вместо имен для сохраненных пользователей",
50
+ "Text2Command info": "Все сообщения от клиентов будут пересылаться на этот экземпляр драйвера text2Command",
51
+ "Texts": "Тексты",
52
+ "URL may not be empty": "URL сервера не может быть пустым!",
53
+ "Use Lets Encrypt certificates:": "Использовать сертификаты Let's Encrypt",
54
+ "Use rooms in keyboard command": "Использовать комнаты в экранной клавиатуре",
55
+ "Use this instance for automatic update:": "Использовать этот экземпляр для обновления сертификатов",
56
+ "Warning!": "Внимание!",
57
+ "Welcome ": "Добро пожаловать ",
58
+ "ip": "IP",
59
+ "password": "Пароль",
60
+ "password repeat": "Повтор пароля",
61
+ "polling": "опрос",
62
+ "pollingInterval": "Интервал опроса",
63
+ "port_help": "Поддерживаются следующие порты: 443, 80, 88, 8443",
64
+ "proxy Host": "прокси-сервер",
65
+ "restarted": "Запущен",
66
+ "restarted_help": "Этот текст будет отправлен клиентам после запуска экземпляра адаптера. Оставьте пустым, чтобы ничего не отсылать.",
67
+ "restarting": "Остановка",
68
+ "restarting_help": "Этот текст будет отправлен клиентам после остановки экземпляра адаптера. Оставьте пустым, чтобы ничего не отсылать.",
69
+ "server": "сервер",
70
+ "telegram adapter settings": "Настройки адаптера telegram",
71
+ "text2command instance": "Экземпляр Text2Command",
72
+ "token": "Токен",
73
+ "type": "Тип",
74
+ "url": "URL",
75
+ "url_help": "например: \"https://mydomain.noip.com:8443\"",
76
+ "value as boolean": "логическое значение",
77
+ "value as number": "значение в виде число",
78
+ "value as string": "значение в виде строки",
79
+ "Do not authenticate new users": "Не аутентифицировать новых пользователей",
80
+ "Save media files": "Сохраняйте медиафайлы",
81
+ "All received files": "Все полученные файлы",
82
+ "Low": "Низкое качество",
83
+ "Medium": "Среднее качество",
84
+ "High": "Высокое качество",
85
+ "High definition": "Качество высокой четкости",
86
+ "Media file location": "Местоположение медиа-файла"
87
+ }
@@ -82,5 +82,6 @@
82
82
  "Low": "Низька якість",
83
83
  "Medium": "Середня якість",
84
84
  "High": "Висока якість",
85
- "High definition": "Висока якість"
85
+ "High definition": "Висока якість",
86
+ "Media file location": "Розташування медіафайлу"
86
87
  }
@@ -0,0 +1,87 @@
1
+ {
2
+ "Allow state control": "允许控制状态",
3
+ "Auth_No": "不,保留已保存的用户!",
4
+ "Auth_Yes": "是的,删除所有用户!",
5
+ "Authenticated Users": "认证用户",
6
+ "Buttons in line": "按钮排队",
7
+ "Call text": "这是ioBroker调用。你家出事了。",
8
+ "Chained certificate": "链式证书",
9
+ "Changed_Password": "您已更改Bot的密码。要立即删除所有已保存的用户吗?然后,每个用户必须使用新密码重新进行身份验证,然后才能再次与bot进行通信。",
10
+ "Command to show the keyboard": "用于显示键盘的命令",
11
+ "Done": "完毕",
12
+ "ID \"%s\" not found.": "找不到ID“%s”。",
13
+ "Ignore warning": "忽略警告",
14
+ "Invalid number %s": "无效的号码%s",
15
+ "Invalid password": "无效的密码!",
16
+ "Keyboard command": "键盘命令",
17
+ "Leave it blank if no password desired": "如果没有密码,请将其留空",
18
+ "Let's Encrypt settings": "我们加密设置",
19
+ "Listen on all IPs": "收听所有IP",
20
+ "Login": "代理用户名",
21
+ "Main settings": "主要设置",
22
+ "Message ignored: ": "讯息被忽略:",
23
+ "Messages": "信息内容",
24
+ "No_Password": "您没有选择密码..如果您没有为您的机器人设置密码,每个陌生人都可以与您的机器人通信!强烈建议设置密码!",
25
+ "OFF-Command": "离开",
26
+ "OFF-Status": "关掉",
27
+ "ON-Command": "上",
28
+ "ON-Status": "切换到",
29
+ "Please enter password in form \"/password phrase\"": "请以“ /密码短语”形式输入密码",
30
+ "Polling interval (ms)": "轮询间隔(ms)",
31
+ "Port": "端口",
32
+ "Port to check the domain:": "用于检查域的端口",
33
+ "Private certificate": "私人证书",
34
+ "Proxy Socks5 enable": "Proxy Socks5启用",
35
+ "Public certificate": "公共证书",
36
+ "Read README.md how to get token": "阅读README.md如何获取令牌",
37
+ "Reauthenticate Users?": "重新认证用户?",
38
+ "Remember authenticated users": "保存经过身份验证的用户以防止重复出现密码提示",
39
+ "Remember raw request data": "保存原始请求以进行进一步处理(注意:请求可能包含安全关键数据!)",
40
+ "Repeat password": "重复输入密码",
41
+ "Restarting...": "正在重新启动...",
42
+ "Restarting... Reauthenticate!": "正在重新启动...重新认证!",
43
+ "Select option": "选择选项",
44
+ "Server settings": "服务器设置",
45
+ "Set Password": "设置密码",
46
+ "Set certificates or load it first in the system settings (right top).": "设置证书或首先在系统设置中加载它(右上角)。",
47
+ "Show the list of rooms before the device selection": "在设备选择之前显示房间列表",
48
+ "Started!": "开始!",
49
+ "Store username instead of firstname of remembered users": "存储用户名而不是记住用户的名字",
50
+ "Text2Command info": "所有请求都将发送到此text2Command实例",
51
+ "Texts": "文本",
52
+ "URL may not be empty": "网址可能不是空的!",
53
+ "Use Lets Encrypt certificates:": "使用Let的加密证书",
54
+ "Use rooms in keyboard command": "在键盘命令中使用房间",
55
+ "Use this instance for automatic update:": "使用此实例进行自动更新",
56
+ "Warning!": "警告!",
57
+ "Welcome ": "欢迎",
58
+ "ip": "IP",
59
+ "password": "密码",
60
+ "password repeat": "密码重复",
61
+ "polling": "轮询",
62
+ "pollingInterval": "轮询间隔",
63
+ "port_help": "目前支持:443,80,88,8443",
64
+ "proxy Host": "代理主机",
65
+ "restarted": "入门",
66
+ "restarted_help": "适配器实例启动后,此文本将发送给客户端。留空以停用。",
67
+ "restarting": "停止",
68
+ "restarting_help": "一旦适配器实例即将停止,此文本将发送给客户端。留空以停用。",
69
+ "server": "服务器",
70
+ "telegram adapter settings": "电报适配器设置",
71
+ "text2command instance": "Text2Command实例",
72
+ "token": "代币",
73
+ "type": "类型",
74
+ "url": "网址",
75
+ "url_help": "比如“https://mydomain.noip.com:8443”",
76
+ "value as boolean": "布尔值",
77
+ "value as number": "价值作为数字",
78
+ "value as string": "值作为字符串",
79
+ "Do not authenticate new users": "不对新用户进行身份验证",
80
+ "Save media files": "保存媒体文件",
81
+ "All received files": "所有收到的文件",
82
+ "Low": "低质量",
83
+ "Medium": "中等质量",
84
+ "High": "高质量",
85
+ "High definition": "高清画质",
86
+ "Media file location": "媒体文件位置"
87
+ }
@@ -93,11 +93,31 @@
93
93
  "lg": 8,
94
94
  "label": "Save media files"
95
95
  },
96
+ "saveFilesTo": {
97
+ "newLine": true,
98
+ "type": "select",
99
+ "sm": 12,
100
+ "md": 4,
101
+ "lg": 4,
102
+ "label": "Media file location",
103
+ "hidden": "!data.saveFiles",
104
+ "default": "filesystem",
105
+ "options": [
106
+ {
107
+ "label": "File system",
108
+ "value": "filesystem"
109
+ },
110
+ {
111
+ "label": "ioBroker database",
112
+ "value": "iobroker"
113
+ }
114
+ ]
115
+ },
96
116
  "saveFilesQuality": {
97
117
  "type": "select",
98
118
  "sm": 12,
99
- "md": 8,
100
- "lg": 8,
119
+ "md": 4,
120
+ "lg": 4,
101
121
  "label": "Quality of media files",
102
122
  "hidden": "!data.saveFiles",
103
123
  "default": "0",
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "telegram",
4
- "version": "3.4.1",
4
+ "version": "3.5.1",
5
5
  "news": {
6
+ "3.5.1": {
7
+ "en": "(klein0r) Fixed file handling for voice files\n(klein0r) Updated dependencies",
8
+ "de": "(klein0r) Fixed-Dateihandling für Sprachdateien\n(klein0r) Aktualisierte Abhängigkeiten",
9
+ "ru": "(клеин0р) Исправленная обработка файлов для голосовых файлов\n(клеин0р) Обновленные зависимости",
10
+ "pt": "(klein0r) Manipulação de arquivos fixos para arquivos de voz\n(klein0r) Dependências atualizadas",
11
+ "nl": "(klein0r) Vaste bestandsbehandeling voor spraakbestanden\n(klein0r) Bijgewerkte afhankelijkheden",
12
+ "fr": "(klein0r) Gestion des fichiers fixes pour les fichiers vocaux\n(klein0r) Dépendances actualisées",
13
+ "it": "(Klein0r) Gestione file fisso per file vocali\n(Klein0r) Dipendenze aggiornate",
14
+ "es": "(klein0r) Manejo de archivos fijo para archivos de voz\n(klein0r) Dependencias actualizadas",
15
+ "pl": "(klein0r) Naprawiono obsługę plików głosowych\n(klein0r) Aktualizacja zależności",
16
+ "uk": "(klein0r) Виправлена обробка файлів для голосових файлів\n(klein0r) Оновлені залежності",
17
+ "zh-cn": "(鸣笛0r) 语音文件的固定文件处理\n(鸣笛0r) 更新的依赖关系"
18
+ },
19
+ "3.5.0": {
20
+ "en": "Added option to save media files into ioBroker file system (files tab)",
21
+ "de": "Option zum Speichern von Mediendateien in ioBroker Dateisystem (Datei-Tab)",
22
+ "ru": "Добавлена опция для сохранения медиа-файлов в файловой системе ioBroker (вкладка файлов)",
23
+ "pt": "Adicionado opção para salvar arquivos de mídia no sistema de arquivo ioBroker (arquivos guia)",
24
+ "nl": "Toegevoegd optie om mediabestanden op te slaan in ioBroker bestandssysteem (tabblad bestanden)",
25
+ "fr": "Ajout de l'option pour enregistrer les fichiers multimédias dans le système de fichiers ioBroker (onglet fichiers)",
26
+ "it": "Aggiunta opzione per salvare i file multimediali in ioBroker file system (file scheda)",
27
+ "es": "Añadido opción para guardar los archivos multimedia en el sistema de archivos ioBroker (tapa de archivos)",
28
+ "pl": "Dodano opcję zapisu plików multimedialnych do systemu plików jOBroker (zakładka plików)",
29
+ "uk": "Додано параметр для збереження медіа файлів в файлову систему ioBroker (посилання на файли)",
30
+ "zh-cn": "添加了将媒体文件保存到 ioBroker 文件系统的选项( 文件标签)"
31
+ },
6
32
  "3.4.1": {
7
33
  "en": "Blockly 9 compatibility for new ask block",
8
34
  "de": "Blockly 9 Kompatibilität für neuen Frageblock",
@@ -67,32 +93,6 @@
67
93
  "pl": "Adapter został przeniesiony na '@ iobroker / webserver'\nAdapter obsługuje kontroler js- 6 teraz\nZaktualizowano zależności",
68
94
  "uk": "Адаптер мігрований до `@iobroker/webserver й\nАдаптер підтримує js-controller 6 тепер\nЗалежність було оновлено",
69
95
  "zh-cn": "适配器已迁移到 XQio 经纪人/网络服务器 `\n适配器支持 js 控制器 6 现在\n依赖关系已更新"
70
- },
71
- "3.2.1": {
72
- "en": "An error at providing error information has been fixed.",
73
- "de": "Es wurde ein Fehler bei der Bereitstellung von Fehlerinformationen behoben.",
74
- "ru": "Установлена ошибка в предоставлении информации об ошибках.",
75
- "pt": "Foi corrigido um erro ao fornecer informações de erro.",
76
- "nl": "Er is een fout opgetreden bij het verstrekken van foutinformatie.",
77
- "fr": "Une erreur a été corrigée pour fournir des informations sur les erreurs.",
78
- "it": "È stato corretto un errore nel fornire informazioni di errore.",
79
- "es": "Se ha corregido un error al proporcionar información de error.",
80
- "pl": "Ustalono błąd w przekazywaniu informacji o błędzie.",
81
- "uk": "Виправлено помилку при наданні інформації про помилки.",
82
- "zh-cn": "提供错误信息时的错误已被修正 ."
83
- },
84
- "3.2.0": {
85
- "en": "Adapter requires node.js 18 and js-controller >= 5 now\nThe current error is added as a separate property error to the response object (messageId) now.\nAdded units to responses\nDependencies have been updated0",
86
- "de": "Adapter benötigt node.js 18 und js-controller >= 5 jetzt\nDer aktuelle Fehler wird nun als separate Eigenschaft error zum Antwortobjekt (messageId) hinzugefügt.\nEinheiten zu Antworten hinzugefügt\nAbhängigkeiten wurden aktualisiert0",
87
- "ru": "Адаптер требует node.js 18 и js-controller >= 5 сейчас\nТекущая ошибка добавляется как отдельная ошибка свойства объекту ответа (messageId) сейчас.\nДобавленные единицы к ответам\nЗависимость обновлена0",
88
- "pt": "Adapter requer node.js 18 e js-controller >= 5 agora\nO erro atual é adicionado como um erro de propriedade separado ao objeto de resposta (messageId) agora.\nUnidades adicionadas a respostas\nAs dependências foram atualizadas0",
89
- "nl": "Adapter vereist node.js 18 en js-controller Nu 5\nDe huidige fout wordt toegevoegd als een aparte eigenschap fout aan het antwoord object (messageId) nu.\nToegevoegde eenheden aan antwoorden\nAfhankelijkheden zijn bijgewerkt0",
90
- "fr": "Adaptateur nécessite node.js 18 et js-controller >= 5 maintenant\nL'erreur courante est ajoutée comme une erreur de propriété séparée à l'objet response (messageId) maintenant.\nAjout d'unités aux réponses\nLes dépendances ont été mises à jour0",
91
- "it": "Adattatore richiede node.js 18 e js-controller >= 5 ora\nL'errore corrente viene aggiunto come errore di proprietà separato all'oggetto di risposta (messageId) ora.\nUnità aggiunte alle risposte\nLe dipendenze sono state aggiornate0",
92
- "es": "Adaptador requiere node.js 18 y js-controller √= 5 ahora\nEl error actual se añade como un error de propiedad separado al objeto de respuesta (messageId) ahora.\nUnidades adicionales a respuestas\nSe han actualizado las dependencias0",
93
- "pl": "Adapter wymaga node.js 18 i sterownika js- > = 5 teraz\nBieżący błąd jest dodawany jako osobny błąd właściwości do obiektu odpowiedzi (messageId).\nDodano jednostki do odpowiedzi\nUaktualniono zależności0",
94
- "uk": "Адаптер вимагає node.js 18 і js-controller >= 5 тепер\nПоточна помилка додана як окрема помилка власності на об'єкт відповіді (messageId) тепер.\nДодано блоки для відповіді\nЗалежність було оновлено0",
95
- "zh-cn": "适配器需要节点.js 18和js控制器 QQ 现在5号\n当前错误作为单独属性错误添加到现在的响应对象(messageId)中.\n答复中增加的单位\n依赖关系已更新0"
96
96
  }
97
97
  },
98
98
  "messages": [
@@ -161,7 +161,8 @@
161
161
  "it": "Telegram",
162
162
  "es": "Telegram",
163
163
  "pl": "Telegram",
164
- "zh-cn": "Telegram"
164
+ "zh-cn": "Telegram",
165
+ "uk": "Телеграма"
165
166
  },
166
167
  "desc": {
167
168
  "en": "This adapter allows to send and receive telegram messages from ioBroker and to be a bot",
@@ -173,7 +174,8 @@
173
174
  "it": "Questo adattatore consente di inviare e ricevere messaggi di telegram da ioBroker e di essere un bot",
174
175
  "es": "Este adaptador permite enviar y recibir mensajes de telegrama de ioBroker y ser un bot",
175
176
  "pl": "Ten adapter umożliwia wysyłanie i odbieranie wiadomości telegramów z ioBroker i bycie botem",
176
- "zh-cn": "该适配器允许从ioBroker发送和接收电报消息并成为机器人"
177
+ "zh-cn": "该适配器允许从ioBroker发送和接收电报消息并成为机器人",
178
+ "uk": "Цей адаптер дозволяє відправляти та отримувати телеграми від ioBroker і бути ботом"
177
179
  },
178
180
  "authors": [
179
181
  "bluefox <dogafox@gmail.com>",
@@ -264,6 +266,7 @@
264
266
  "doNotAcceptNewUsers": false,
265
267
  "useUsername": false,
266
268
  "saveFiles": false,
269
+ "saveFilesTo": "filesystem",
267
270
  "saveFilesQuality": "",
268
271
  "allowStates": true,
269
272
  "proxy": false,
@@ -288,6 +291,27 @@
288
291
  "leCheckPort": 80
289
292
  },
290
293
  "instanceObjects": [
294
+ {
295
+ "_id": "",
296
+ "type": "meta",
297
+ "common": {
298
+ "name": {
299
+ "en": "Meta storage for media files",
300
+ "de": "Meta-Speicher für Mediendateien",
301
+ "ru": "Мета-хранилище для медиафайлов",
302
+ "pt": "Meta armazenamento para arquivos de mídia",
303
+ "nl": "Meta-opslag voor mediabestanden",
304
+ "fr": "Stockage de métadonnées pour les fichiers multimédias",
305
+ "it": "Meta storage per file multimediali",
306
+ "es": "Meta almacenamiento para archivos multimedia",
307
+ "pl": "Meta do przechowywania plików medialnych",
308
+ "uk": "Мета зберігання для медіа файлів",
309
+ "zh-cn": "媒体文件的元存储"
310
+ },
311
+ "type": "meta.user"
312
+ },
313
+ "native": {}
314
+ },
291
315
  {
292
316
  "_id": "info",
293
317
  "type": "channel",
package/main.js CHANGED
@@ -173,6 +173,28 @@ function startAdapter(options) {
173
173
  });
174
174
  }, 10000);
175
175
 
176
+ tmpDirName = path.join(utils.getAbsoluteDefaultDataDir(), adapter.namespace.replace('.', '_'));
177
+
178
+ // Create file system directories for media files
179
+ if (adapter.config.saveFilesTo == 'filesystem') {
180
+ try {
181
+ !fs.existsSync(tmpDirName) && fs.mkdirSync(tmpDirName);
182
+
183
+ const subDirectories = ['voice'];
184
+ if (adapter.config.saveFiles) {
185
+ // Create subdirs for other attachment types
186
+ subDirectories.push('photo', 'video', 'audio', 'document');
187
+ }
188
+
189
+ for (const subDir of subDirectories) {
190
+ const subDirPath = path.join(tmpDirName, subDir);
191
+ !fs.existsSync(subDirPath) && fs.mkdirSync(subDirPath);
192
+ }
193
+ } catch (e) {
194
+ adapter.log.error(`Cannot create tmp directory: ${tmpDirName}`);
195
+ }
196
+ }
197
+
176
198
  if (adapter.config.server) {
177
199
  adapter.config.port = parseInt(adapter.config.port, 10);
178
200
 
@@ -364,13 +386,6 @@ function startAdapter(options) {
364
386
 
365
387
  server.settings = adapter.config;
366
388
 
367
- tmpDirName = path.join(utils.getAbsoluteDefaultDataDir(), adapter.namespace.replace('.', '_'));
368
- try {
369
- !fs.existsSync(tmpDirName) && fs.mkdirSync(tmpDirName);
370
- } catch (e) {
371
- adapter.log.error(`Cannot create tmp directory: ${tmpDirName}`);
372
- }
373
-
374
389
  return adapter;
375
390
  }
376
391
 
@@ -926,6 +941,8 @@ function sendMessage(text, user, chatId, options) {
926
941
  }
927
942
 
928
943
  function saveFile(fileID, fileName, callback) {
944
+ adapter.log.debug(`Saving media file ${fileID} to ${fileName} (location = ${adapter.config.saveFilesTo})`);
945
+
929
946
  bot.getFileLink(fileID)
930
947
  .then(url => {
931
948
  adapter.log.debug(`Received message: ${url}`);
@@ -934,27 +951,44 @@ function saveFile(fileID, fileName, callback) {
934
951
  const buf = [];
935
952
  res.on('data', data => buf.push(data));
936
953
  res.on('end', () => {
937
- const fileLocation = path.join(tmpDirName, fileName);
938
- try {
939
- fs.writeFileSync(fileLocation, Buffer.concat(buf));
940
- } catch (err) {
941
- return callback({error: `Error: ${err}`});
942
- }
954
+ if (adapter.config.saveFilesTo == 'filesystem') {
955
+ const fileLocation = path.join(tmpDirName, fileName);
956
+ try {
957
+ fs.writeFileSync(fileLocation, Buffer.concat(buf));
943
958
 
944
- callback({
945
- info: `It's saved! : ${fileLocation}`,
946
- path: fileLocation
947
- });
959
+ callback({
960
+ info: `media file has been saved to "${adapter.config.saveFilesTo}": ${fileLocation}`,
961
+ location: adapter.config.saveFilesTo,
962
+ path: fileLocation
963
+ });
964
+ } catch (err) {
965
+ return callback({ error: `Error: ${err}` });
966
+ }
967
+ } else if (adapter.config.saveFilesTo == 'iobroker') {
968
+ try {
969
+ const fileLocation = path.join(tmpDirName, fileName); // TODO: check new urn format https://github.com/ioBroker/ioBroker.js-controller/issues/2710
970
+
971
+ adapter.writeFileAsync(adapter.namespace, fileName, Buffer.concat(buf))
972
+ .then(() => {
973
+ callback({
974
+ info: `media file has been saved to "${adapter.config.saveFilesTo}": ${fileLocation}`,
975
+ location: adapter.config.saveFilesTo,
976
+ path: fileLocation,
977
+ });
978
+ });
979
+ } catch (err) {
980
+ return callback({ error: `Error: ${err}` });
981
+ }
982
+ }
948
983
  });
949
984
 
950
- res.on('error', err =>
951
- callback({error: `Error: ${err}`}));
985
+ res.on('error', err => callback({ error: `Error: ${err}` }));
952
986
  } else {
953
- callback({error: 'Error: statusCode !== 200'});
987
+ callback({ error: 'Error: statusCode !== 200' });
954
988
  }
955
989
  });
956
990
  })
957
- .catch(err => callback({error: `Error bot.getFileLink: ${err}`}));
991
+ .catch(err => callback({ error: `Error bot.getFileLink: ${err}` }));
958
992
  }
959
993
 
960
994
  function getMessage(msg) {
@@ -963,8 +997,6 @@ function getMessage(msg) {
963
997
 
964
998
  if (msg.voice) {
965
999
  try {
966
- const voiceFile = path.join(tmpDirName, 'voice');
967
- !fs.existsSync(voiceFile) && fs.mkdirSync(voiceFile);
968
1000
  saveFile(msg.voice.file_id, adapter.config.saveFiles ? `/voice/${date}.ogg` : '/voice/temp.ogg', res => {
969
1001
  if (!res.error) {
970
1002
  adapter.log.info(res.info);
@@ -978,9 +1010,6 @@ function getMessage(msg) {
978
1010
  }
979
1011
  } else if (adapter.config.saveFiles && msg.photo) {
980
1012
  try {
981
- const photoFile = path.join(tmpDirName, 'photo');
982
- !fs.existsSync(photoFile) && fs.mkdirSync(photoFile);
983
-
984
1013
  const qualityMap = {
985
1014
  0: 'low',
986
1015
  1: 'med',
@@ -1007,7 +1036,7 @@ function getMessage(msg) {
1007
1036
 
1008
1037
  let fileName = '';
1009
1038
  if (msg.media_group_id) {
1010
- if (!mediaGroupExport.hasOwnProperty(msg.media_group_id)) {
1039
+ if (!Object.prototype.hasOwnProperty.call(mediaGroupExport, msg.media_group_id)) {
1011
1040
  const id = Object.keys(mediaGroupExport).length;
1012
1041
  mediaGroupExport[msg.media_group_id] = {
1013
1042
  id,
@@ -1042,8 +1071,6 @@ function getMessage(msg) {
1042
1071
  }
1043
1072
  } else if (adapter.config.saveFiles && msg.video) {
1044
1073
  try {
1045
- const videoFile = path.join(tmpDirName, 'video');
1046
- !fs.existsSync(videoFile) && fs.mkdirSync(videoFile);
1047
1074
  saveFile(msg.video.file_id, `/video/${date}.mp4`, res => {
1048
1075
  if (!res.error) {
1049
1076
  adapter.log.info(res.info);
@@ -1057,8 +1084,6 @@ function getMessage(msg) {
1057
1084
  }
1058
1085
  } else if (adapter.config.saveFiles && msg.audio) {
1059
1086
  try {
1060
- const audioFile = path.join(tmpDirName, 'audio');
1061
- !fs.existsSync(audioFile) && fs.mkdirSync(audioFile);
1062
1087
  saveFile(msg.audio.file_id, `/audio/${date}.mp3`, res => {
1063
1088
  if (!res.error) {
1064
1089
  adapter.log.info(res.info);
@@ -1072,8 +1097,6 @@ function getMessage(msg) {
1072
1097
  }
1073
1098
  } else if (adapter.config.saveFiles && msg.document) {
1074
1099
  try {
1075
- const documentFile = path.join(tmpDirName, 'document');
1076
- !fs.existsSync(documentFile) && fs.mkdirSync(documentFile);
1077
1100
  saveFile(msg.document.file_id, `/document/${msg.document.file_name}`, res => {
1078
1101
  if (!res.error) {
1079
1102
  adapter.log.info(res.info);
@@ -1723,10 +1746,10 @@ function processTelegramText(msg) {
1723
1746
  });
1724
1747
  }
1725
1748
 
1726
- adapter.setState('communicate.requestChatId', msg.chat.id, true, err => err && adapter.log.error(err));
1727
- adapter.setState('communicate.requestMessageId', msg.message_id, true, err => err && adapter.log.error(err));
1728
- adapter.setState('communicate.requestUserId', msg.from && msg.from.id !== undefined && msg.from.id !== null ? msg.from.id.toString() : '', true, err => err && adapter.log.error(err));
1729
- adapter.setState('communicate.request', `[${user}]${msg.text}`, true, err => err && adapter.log.error(err));
1749
+ adapter.setState('communicate.requestChatId', { val: msg.chat.id, ack: true });
1750
+ adapter.setState('communicate.requestMessageId', { val: msg.message_id, ack: true });
1751
+ adapter.setState('communicate.requestUserId', { val: msg.from && msg.from.id !== undefined && msg.from.id !== null ? msg.from.id.toString() : '', ack: true });
1752
+ adapter.setState('communicate.request', { val: `[${user}]${msg.text}`, ack: true });
1730
1753
  }
1731
1754
 
1732
1755
  function connect() {
@@ -1811,8 +1834,7 @@ function connect() {
1811
1834
  connectionState(true);
1812
1835
 
1813
1836
  if (adapter.config.storeRawRequest) {
1814
- adapter.setState('communicate.requestRaw', JSON.stringify(msg), true, err =>
1815
- err && adapter.log.error(err));
1837
+ adapter.setState('communicate.requestRaw', { val: JSON.stringify(msg, null, 2), ack: true });
1816
1838
  }
1817
1839
 
1818
1840
  getMessage(msg);
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": "3.4.1",
4
+ "version": "3.5.1",
5
5
  "author": {
6
6
  "name": "bluefox",
7
7
  "email": "dogafox@gmail.com"
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "devDependencies": {
44
44
  "@alcalzone/release-script": "^3.7.0",
45
- "@alcalzone/release-script-plugin-iobroker": "^3.7.0",
45
+ "@alcalzone/release-script-plugin-iobroker": "^3.7.1",
46
46
  "@alcalzone/release-script-plugin-license": "^3.7.0",
47
47
  "@alcalzone/release-script-plugin-manual-review": "^3.7.0",
48
48
  "@iobroker/adapter-dev": "^1.3.0",
@@ -1,86 +0,0 @@
1
- {
2
- "Allow state control": "Permitir el control del estado",
3
- "Auth_No": "No, mantén a los usuarios guardados!",
4
- "Auth_Yes": "Sí, borra todos los usuarios!",
5
- "Authenticated Users": "Usuarios autenticados",
6
- "Buttons in line": "Botones en linea",
7
- "Call text": "Esta es la llamada ioBroker. Algo ha sucedido en tu casa.",
8
- "Chained certificate": "Certificado encadenado",
9
- "Changed_Password": "Has cambiado la contraseña de tu Bot. ¿Desea eliminar todos los usuarios guardados ahora? Luego, cada usuario debe volver a autenticarse con la nueva contraseña antes de poder comunicarse con el bot nuevamente.",
10
- "Command to show the keyboard": "Comando para mostrar el teclado",
11
- "Done": "Hecho",
12
- "ID \"%s\" not found.": "No se encontró el ID \"%s\".",
13
- "Ignore warning": "Ignorar la advertencia",
14
- "Invalid number %s": "Número inválido %s",
15
- "Invalid password": "¡Contraseña invalida!",
16
- "Keyboard command": "Comando del teclado",
17
- "Leave it blank if no password desired": "Déjelo en blanco si no desea una contraseña",
18
- "Let's Encrypt settings": "Vamos a cifrar la configuración",
19
- "Listen on all IPs": "Escuchar en todas las direcciones IP",
20
- "Login": "Iniciar sesión",
21
- "Main settings": "Ajustes principales",
22
- "Message ignored: ": "Mensaje ignorado: ",
23
- "Messages": "Mensajes",
24
- "No_Password": "No seleccionó una contraseña ... ¡Si no configura una contraseña para su bot, todos los extraños podrán comunicarse con su bot! Es muy recomendable establecer una contraseña!",
25
- "OFF-Command": "Fuera de comando",
26
- "OFF-Status": "Estado apagado",
27
- "ON-Command": "ON-Command",
28
- "ON-Status": "Estado de encendido",
29
- "Please enter password in form \"/password phrase\"": "Por favor, introduzca la contraseña en el formulario \"/frase de contraseña\"",
30
- "Polling interval (ms)": "Intervalo de sondeo (ms)",
31
- "Port": "Port",
32
- "Port to check the domain:": "Puerto para verificar el dominio",
33
- "Private certificate": "Certificado privado",
34
- "Proxy Socks5 enable": "Proxy Socks5 habilita",
35
- "Public certificate": "Certificado público",
36
- "Read README.md how to get token": "Lea README.md cómo obtener token",
37
- "Reauthenticate Users?": "¿Reautenticar usuarios?",
38
- "Remember authenticated users": "Recuerde usuarios autenticados",
39
- "Remember raw request data": "Guarde la solicitud original para un procesamiento posterior (¡la precaución puede contener datos críticos para la seguridad!)",
40
- "Repeat password": "repite la contraseña",
41
- "Restarting...": "Reiniciando ...",
42
- "Restarting... Reauthenticate!": "Reiniciando ... ¡Vuelve a autenticarte!",
43
- "Select option": "Seleccionar opción",
44
- "Server settings": "Configuración del servidor",
45
- "Set Password": "Configurar la clave",
46
- "Set certificates or load it first in the system settings (right top).": "Establezca certificados o cárguelos primero en la configuración del sistema (arriba a la derecha).",
47
- "Show the list of rooms before the device selection": "Mostrar la lista de habitaciones antes de la selección del dispositivo.",
48
- "Started!": "¡Empezado!",
49
- "Store username instead of firstname of remembered users": "Store username instead of firstname of remembered users",
50
- "Text2Command info": "Todas las solicitudes se enviarán a esta instancia de text2Command",
51
- "Texts": "Textos",
52
- "URL may not be empty": "La URL no puede estar vacía",
53
- "Use Lets Encrypt certificates:": "Utilice los certificados Let's Encrypt",
54
- "Use rooms in keyboard command": "Usa las habitaciones en el comando del teclado",
55
- "Use this instance for automatic update:": "Use esta instancia para la actualización automática",
56
- "Warning!": "¡Advertencia!",
57
- "Welcome ": "Bienvenido ",
58
- "ip": "IP",
59
- "password": "Contraseña",
60
- "password repeat": "Repite la contraseña",
61
- "polling": "votación",
62
- "pollingInterval": "Intervalo de votación",
63
- "port_help": "Actualmente compatible: 443, 80, 88, 8443",
64
- "proxy Host": "host proxy",
65
- "restarted": "Empezado",
66
- "restarted_help": "Este texto se enviará a los clientes una vez que se inicie la instancia del adaptador. Dejar en blanco para desactivar.",
67
- "restarting": "Reiniciar",
68
- "restarting_help": "Este texto se enviará a los clientes una vez que se detenga la instancia del adaptador. Dejar en blanco para desactivar.",
69
- "server": "servidor",
70
- "telegram adapter settings": "configuración del adaptador de telegrama",
71
- "text2command instance": "Instancia Text2Command",
72
- "token": "Token",
73
- "type": "Tipo",
74
- "url": "URL",
75
- "url_help": "como \"https://mydomain.noip.com:8443\"",
76
- "value as boolean": "valor como booleano",
77
- "value as number": "valor como numero",
78
- "value as string": "valor como cadena",
79
- "Do not authenticate new users": "No autenticar nuevos usuarios",
80
- "Save media files": "Guardar archivos multimedia",
81
- "All received files": "Todos los archivos recibidos",
82
- "Low": "Baja calidad",
83
- "Medium": "Calidad media",
84
- "High": "Alta calidad",
85
- "High definition": "calidad de alta definición"
86
- }