Skip to content

Commit

Permalink
Extended link button
Browse files Browse the repository at this point in the history
  • Loading branch information
GermanBluefox committed Aug 28, 2024
1 parent fc4255e commit e675ec8
Show file tree
Hide file tree
Showing 18 changed files with 286 additions and 15 deletions.
2 changes: 1 addition & 1 deletion admin/custom/customComponents.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion admin/custom/customComponents.js.map

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

This file was deleted.

53 changes: 53 additions & 0 deletions lib/i18n.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const fs = require('node:fs');
const path = require('node:path');

let language = 'en';
let words = null;

function init(lang) {
language = lang;
const files = fs.readdirSync(path.join(__dirname, '/i18n'));
words = {};
files.forEach(file => {
if (file.endsWith('.json')) {
const lang = file.split('.')[0];
const wordsForLanguage = JSON.parse(fs.readFileSync(path.join(__dirname, `/i18n/${file}`)).toString('utf8'));
Object.keys(wordsForLanguage).forEach(key => {
if (!words[key]) {
words[key] = {};
}
words[key][lang] = wordsForLanguage[key];
});
}
});
}

function getText(key, lang) {
lang = lang || language;
if (!language && lang) {
language = lang;
}
if (!words && !lang) {
throw new Error('i18n not initialized');
}
if (!words) {
init(lang);
}
if (!words[key]) {
return key;
}
return words[key][lang] || words[key].en || key;
}

function getAllTexts(key) {
if (!words) {
init();
}
return words[key];
}

module.exports = {
init,
t: getText,
tt: getAllTexts,
}
7 changes: 7 additions & 0 deletions lib/i18n/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Neue Geräte wurden gefunden",
"Notification is not actual. All found devices are already added.": "Benachrichtigung ist nicht aktuell. Alle gefundenen Geräte sind bereits hinzugefügt.",
"Save settings": "Einstellungen speichern",
"Open settings": "Einstellungen öffnen",
"Saved": "Gespeichert"
}
7 changes: 7 additions & 0 deletions lib/i18n/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "New devices found",
"Notification is not actual. All found devices are already added.": "Notification is not actual. All found devices are already added.",
"Save settings": "Save settings",
"Saved": "Saved",
"Open settings": "Open settings"
}
7 changes: 7 additions & 0 deletions lib/i18n/es.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Nuevos dispositivos encontrados",
"Notification is not actual. All found devices are already added.": "La notificación no es actual. Todos los dispositivos encontrados ya están agregados.",
"Open settings": "Abrir configuración",
"Save settings": "Guardar configuración",
"Saved": "Guardado"
}
7 changes: 7 additions & 0 deletions lib/i18n/fr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Nouveaux appareils trouvés",
"Notification is not actual. All found devices are already added.": "La notification n'est pas actuelle. Tous les appareils trouvés sont déjà ajoutés.",
"Open settings": "Ouvrir les paramètres",
"Save settings": "Enregistrer les paramètres",
"Saved": "Sauvé"
}
7 changes: 7 additions & 0 deletions lib/i18n/it.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Nuovi dispositivi trovati",
"Notification is not actual. All found devices are already added.": "La notifica non è effettiva. Tutti i dispositivi trovati sono già stati aggiunti.",
"Open settings": "Apri impostazioni",
"Save settings": "Salva impostazioni",
"Saved": "Salvato"
}
7 changes: 7 additions & 0 deletions lib/i18n/nl.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Nieuwe apparaten gevonden",
"Notification is not actual. All found devices are already added.": "Notificatie is niet actueel. Alle gevonden apparaten zijn al toegevoegd.",
"Open settings": "Instellingen openen",
"Save settings": "Instellingen opslaan",
"Saved": "Opgeslagen"
}
7 changes: 7 additions & 0 deletions lib/i18n/pl.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Znaleziono nowe urządzenia",
"Notification is not actual. All found devices are already added.": "Powiadomienie nie jest aktualne. Wszystkie znalezione urządzenia są już dodane.",
"Open settings": "Otwórz ustawienia",
"Save settings": "Zapisz ustawienia",
"Saved": "Zapisane"
}
7 changes: 7 additions & 0 deletions lib/i18n/pt.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Novos dispositivos encontrados",
"Notification is not actual. All found devices are already added.": "A notificação não é real. Todos os dispositivos encontrados já foram adicionados.",
"Open settings": "Abrir configurações",
"Save settings": "Salvar configurações",
"Saved": "Salvo"
}
7 changes: 7 additions & 0 deletions lib/i18n/ru.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "Найдены новые устройства",
"Notification is not actual. All found devices are already added.": "Уведомление не актуально. Все найденные устройства уже добавлены.",
"Open settings": "Открыть настройки",
"Save settings": "Сохранить настройки",
"Saved": "Сохранено"
}
7 changes: 7 additions & 0 deletions lib/i18n/zh-cn.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"New devices found": "发现新设备",
"Notification is not actual. All found devices are already added.": "通知不真实。所有找到的设备均已添加。",
"Open settings": "打开设置",
"Save settings": "保存设置",
"Saved": "已保存"
}
167 changes: 157 additions & 10 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const ip = require('ip');
const ping = require('./lib/ping');
const allowPing = require('./lib/setcup');
const adapterName = require('./package.json').name.split('.').pop();
const { init, tt } = require('./lib/i18n');
const {get} = require("axios");
let adapter;

let arp;
Expand All @@ -35,7 +37,7 @@ function startAdapter(options) {

adapter = new utils.Adapter(options);

adapter.on('message', obj => obj && obj.command && processMessage(obj));
adapter.on('message', obj => obj?.command && processMessage(obj));

adapter.on('ready', () => main(adapter));

Expand Down Expand Up @@ -119,8 +121,12 @@ async function browse(iface) {
}
}
}
if (!iface) {
adapter.log.warn(`Defined interface "${iface}" does not exists on this host`);
if (!iface || typeof iface === 'string') {
if (!iface) {
adapter.log.warn(`No interface selected`);
} else {
adapter.log.warn(`Defined interface "${iface}" does not exists on this host`);
}
runningBrowse = false;
return;
}
Expand Down Expand Up @@ -214,11 +220,90 @@ async function browse(iface) {
const newDevices = detectedIPs.filter(item => !item.ignore && !adapter.config.devices.find(dev => dev.ip === item.ip));
if (generateNotification && newDevices.length) {
const devices = newDevices.map(item => `${item.ip}${item.vendor && item.vendor !== '<random MAC>' ? ` [${item.vendor}]` : ''}`).join('\n');
await adapter.registerNotification('ping', 'newDevices', devices);
await adapter.registerNotification('ping', 'newDevices', devices, newDevices);
}
}

let temporaryAddressesToAdd = [];

function getGuiSchema(newDevices) {
const schema = {
type: 'panel',
items: {
_info: {
type: 'header',
size: 5,
text: tt('New devices found'),
sm: 12,
}
},
};

let added = 0;
newDevices?.forEach((device, i) => {
if (adapter.config.devices.find(dev => dev.ip === device.ip)) {
return;
}
added++;
schema.items[`_device_${i}_ip`] = {
newLine: true,
type: 'staticText',
noTranslation: true,
text: `${device.ip}${device.vendor || device.mac ? ` [${device.vendor || (device.mac || '').substring(0, 9)}]` : ''}`,
sm: 8,
style: {
marginTop: 5,
},
};
const included = !!temporaryAddressesToAdd.find(item => item.ip === device.ip);
schema.items[`_device_${i}_btn`] = {
type: 'sendto',
command: 'addIpAddress',
data: { ip: device.ip, vendor: device.vendor },
label: included ? '-' : '+',
noTranslation: true,
sm: 4,
variant: included ? 'text' : 'contained',
controlStyle: {
width: 30,
minWidth: 30,
},
};
});

if (!added) {
// delete info text
schema.items = {};
schema.items[`_noDevices`] = {
type: 'staticText',
text: tt('Notification is not actual. All found devices are already added.'),
sm: 12,
};
}

schema.items[`_open`] = {
newLine: true,
type: 'sendto',
command: 'openLink',
label: tt('Open settings'),
variant: 'contained',
icon: 'open',
};

if (temporaryAddressesToAdd.length) {
schema.items[`_save`] = {
type: 'sendto',
command: 'save',
label: tt('Save settings'),
variant: 'contained',
icon: 'save',
};
}

return schema;
}

function processMessage(obj) {
async function processMessage(obj) {
switch (obj.command) {
case 'ping': {
// Try to ping one IP or name
Expand All @@ -241,6 +326,66 @@ function processMessage(obj) {

break;
}

case 'addIpAddress': {
if (obj.message?.ip) {
const index = temporaryAddressesToAdd.findIndex(item => item.ip === obj.message.ip);
if (index === -1) {
temporaryAddressesToAdd.push({ ip: obj.message.ip, name: obj.message.vendor });
} else {
temporaryAddressesToAdd.splice(index, 1);
}
}

adapter.sendTo(obj.from, obj.command, {
command: {
command: 'nop',
refresh: !!obj.message?.ip,
},
}, obj.callback);

break;
}

case 'openLink': {
adapter.sendTo(obj.from, obj.command, {
command: {
command: 'link',
url: '#tab-instances/config/system.adapter.ping.0/_browse',
close: true,
},
}, obj.callback);
break;
}

case 'save': {
const config = await adapter.getForeignObjectAsync(`system.adapter.${adapter.namespace}`);
let changed = false;
temporaryAddressesToAdd.forEach(item => {
if (!config.native.devices.find(dev => dev.ip === item.ip)) {
config.native.devices.push({ enabled: true, ip: item.ip, name: item.name });
changed = true;
}
});
temporaryAddressesToAdd = [];
// adapter will be restarted
if (changed) {
await adapter.setForeignObjectAsync(config._id, config);
}
adapter.sendTo(obj.from, obj.command, {
command: {
command: 'message',
message: tt('Saved'),
refresh: true,
},
}, obj.callback);
break
}

case 'getNotificationSchema': {
adapter.sendTo(obj.from, obj.command, { schema: getGuiSchema(obj.message.actionData) }, obj.callback);
break;
}
}
}

Expand Down Expand Up @@ -439,16 +584,16 @@ async function syncObjects(preparedObjects, oldObjects) {
}

function prepareObjectsForHost(hostDevice, config) {
const host = config.ip.trim();
const name = config.name.trim();
const host = (config.ip || '').trim();
const name = (config.name || '').trim();
const idName = (config.use_name ? name || host : host).replace(FORBIDDEN_CHARS, '_').replace(/[.\s]+/g, '_');

if (config.extended_info) {
const channelID = {device: hostDevice, channel: idName};

const stateAliveID = {device: hostDevice, channel: idName, state: 'alive'};
const stateTimeID = {device: hostDevice, channel: idName, state: 'time'};
const stateRpsID = {device: hostDevice, channel: idName, state: 'rps'};
const stateAliveID = { device: hostDevice, channel: idName, state: 'alive' };
const stateTimeID = { device: hostDevice, channel: idName, state: 'time' };
const stateRpsID = { device: hostDevice, channel: idName, state: 'rps' };
return {
ping_task: {
host,
Expand Down Expand Up @@ -654,6 +799,8 @@ async function main(adapter) {
await adapter.setStateAsync('browse.progress', 0, true);
await adapter.setStateAsync('browse.status', '', true);

init();

adapter.config.autoDetect = parseInt(adapter.config.autoDetect, 10) || 0;

const res = await adapter.getStateAsync('browse.result');
Expand Down
1 change: 1 addition & 0 deletions src-admin/src/PingBrowseComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ class PingBrowseComponent extends ConfigGeneric {
{this.state.interfaces.map(item => {
const len = netMask2Count(item.netmask);
return <MenuItem
key={item.ip}
disabled={len > 4096}
value={item.ip}
>
Expand Down

0 comments on commit e675ec8

Please sign in to comment.