From db7795eecb331e8105dbde1ac29d37e4f33de67b Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 27 Oct 2026 14:57:45 +0200 Subject: [PATCH] feat(iot-hub): device install form for LoRaWAN packages - The device install form shows placeholders, templated defaults, an Advanced section and a ThingsBoard connection section with the MQTT host and port, cleans pasted values, shows errors after the user leaves a field and does not let the browser autofill ThingsBoard credentials. - A field marked by the package checks the integration connection. - The TTN and TTI install methods are named The Things Stack Sandbox and The Things Stack Cloud. - The TTN converter metadata includes the coding rate and the gateway channel. - Deleting or updating a device package keeps the integrations, converters and other entities that another installed device package uses, and the delete dialog names them before the user confirms. - The Open button of an installed item names what it opens. --- .../server/controller/IotHubController.java | 16 +- .../service/iot_hub/DefaultIotHubService.java | 62 ++- .../iot_hub/InstalledItemKeptEntities.java | 30 ++ .../server/service/iot_hub/IotHubService.java | 3 + .../system/DefaultSystemSecurityService.java | 9 +- .../security/system/ResolvedBaseUrl.java | 10 + .../system/SystemSecurityService.java | 2 + .../iot_hub/DefaultIotHubServiceTest.java | 94 +++- .../DefaultSystemSecurityServiceTest.java | 51 ++ .../device/DeviceConnectivityHostSource.java | 15 + .../dao/device/DeviceConnectivityService.java | 14 +- .../ThingsStackConverterUnwrapper.java | 15 + .../wrapper/ConverterUnwrapperTest.java | 16 + common/integration/mqtt-integrations/pom.xml | 5 + .../mqtt/basic/BasicMqttIntegration.java | 2 + .../TtnIntegrationCheckConnectionTest.java | 62 +++ .../device/DeviceConnectivityServiceImpl.java | 20 +- .../ResolvedDeviceConnectivityInfo.java | 11 + .../DeviceConnectivityServiceImplTest.java | 119 +++++ .../src/app/core/http/iot-hub-api.service.ts | 15 +- .../device-install-dialog.component.html | 42 +- .../device-install-dialog.component.scss | 17 + .../device-install-dialog.component.ts | 453 +++++++++++++++++- .../install-form-renderer.component.html | 136 +++++- .../install-form-renderer.component.scss | 7 - .../install-form-renderer.component.ts | 126 ++++- .../iot-hub/iot-hub-actions.service.ts | 26 +- .../iot-hub-delete-dialog.component.html | 5 +- .../iot-hub-delete-dialog.component.scss | 8 +- .../iot-hub-delete-dialog.component.ts | 27 +- ...t-hub-installed-items-table.component.html | 16 +- ...iot-hub-installed-items-table.component.ts | 23 + .../iot-hub/iot-hub-markdown.component.ts | 12 +- .../models/iot-hub/device-package.models.ts | 36 +- .../iot-hub/iot-hub-installed-item.models.ts | 25 +- .../src/app/shared/models/settings.models.ts | 9 + .../en_US/iot-hub/device-connection-host.md | 12 + .../assets/locale/locale.constant-ar_AE.json | 4 +- .../assets/locale/locale.constant-ca_ES.json | 4 +- .../assets/locale/locale.constant-da_DK.json | 4 +- .../assets/locale/locale.constant-de_DE.json | 4 +- .../assets/locale/locale.constant-el_GR.json | 4 +- .../assets/locale/locale.constant-en_US.json | 34 +- .../assets/locale/locale.constant-es_ES.json | 4 +- .../assets/locale/locale.constant-fr_FR.json | 4 +- .../assets/locale/locale.constant-hi_IN.json | 4 +- .../assets/locale/locale.constant-it_IT.json | 4 +- .../assets/locale/locale.constant-ja_JP.json | 4 +- .../assets/locale/locale.constant-ka_GE.json | 2 +- .../assets/locale/locale.constant-lt_LT.json | 4 +- .../assets/locale/locale.constant-lv_LV.json | 2 +- .../assets/locale/locale.constant-nl_NL.json | 4 +- .../assets/locale/locale.constant-no_NO.json | 4 +- .../assets/locale/locale.constant-pl_PL.json | 4 +- .../assets/locale/locale.constant-pt_BR.json | 4 +- .../assets/locale/locale.constant-tr_TR.json | 4 +- .../assets/locale/locale.constant-uk_UA.json | 4 +- .../assets/locale/locale.constant-zh_CN.json | 4 +- 58 files changed, 1506 insertions(+), 155 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java create mode 100644 application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java create mode 100644 common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java create mode 100644 common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java create mode 100644 dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java create mode 100644 dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java create mode 100644 ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index f3d32fedc8..1645505c00 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -32,10 +32,13 @@ import java.util.UUID; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; +import org.thingsboard.server.dao.device.DeviceConnectivityHostSource; import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; +import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; import org.thingsboard.server.service.iot_hub.InstallPlanResult; @@ -153,13 +156,22 @@ public class IotHubController extends BaseController { iotHubService.deleteInstalledItem(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/installedItems/{installedItemId}/keptEntities") + @ResponseBody + public InstalledItemKeptEntities getInstalledItemKeptEntities(@PathVariable UUID installedItemId) throws ThingsboardException { + checkAllPermissions(); + return iotHubService.findKeptEntities(getTenantId(), new IotHubInstalledItemId(installedItemId)); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/connectivity") @ResponseBody public JsonNode getConnectivitySettings(HttpServletRequest request) throws Exception { checkAllPermissions(); - String baseUrl = systemSecurityService.getBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request); - return deviceConnectivityService.getConnectivityInfo(baseUrl); + ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request); + return deviceConnectivityService.getConnectivityInfo(baseUrl.url(), + baseUrl.fromRequest() ? DeviceConnectivityHostSource.REQUEST : DeviceConnectivityHostSource.BASE_URL); } private void checkAllPermissions() throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 06ef375109..a3cf0599fa 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -42,6 +42,8 @@ import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemD import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.exception.EntitiesLimitExceededException; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.service.solutions.SolutionService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import org.thingsboard.server.common.data.permission.Operation; @@ -58,6 +60,7 @@ import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.group.EntityGroupService; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.rule.RuleChainService; @@ -79,10 +82,12 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; @@ -118,6 +123,7 @@ public class DefaultIotHubService implements IotHubService { private final CalculatedFieldService calculatedFieldService; private final DeviceProfileService deviceProfileService; private final DeviceService deviceService; + private final EntityService entityService; private final TbDeviceService tbDeviceService; private final SolutionService solutionService; private final EntityGroupService entityGroupService; @@ -456,7 +462,7 @@ public class DefaultIotHubService implements IotHubService { case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); case "DEVICE" -> { DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor; - deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); + deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); dd.setCreatedEntityIds(null); dd.setDashboardId(null); } @@ -704,13 +710,24 @@ public class DefaultIotHubService implements IotHubService { } } - private void deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { + /** + * Deletes what a device package created, except the entities another installed device package + * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. + */ + private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, + List createdEntityIds, SecurityUser user) { if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); List reversed = new ArrayList<>(createdEntityIds); Collections.reverse(reversed); for (EntityId entityId : reversed) { + Set usedBy = usedByOtherPackages.get(entityId.getId()); + if (usedBy != null) { + log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); + continue; + } try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { @@ -719,6 +736,45 @@ public class DefaultIotHubService implements IotHubService { } } + /** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */ + @Override + public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) { + IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); + if (installedItem == null) { + throw new IllegalArgumentException("Installed item not found"); + } + List kept = new ArrayList<>(); + Set usedByItems = new HashSet<>(); + if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); + for (EntityId entityId : dd.getCreatedEntityIds()) { + Set usedBy = usedByOtherPackages.get(entityId.getId()); + if (usedBy != null) { + kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); + usedByItems.addAll(usedBy); + } + } + } + return new InstalledItemKeptEntities(kept, usedByItems.size()); + } + + private Map> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { + Map> usedBy = new HashMap<>(); + PageLink pageLink = new PageLink(100); + PageData page; + do { + page = iotHubInstalledItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); + for (IotHubInstalledItem item : page.getData()) { + if (!item.getId().equals(installedItemId) + && item.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { + dd.getCreatedEntityIds().forEach(id -> usedBy.computeIfAbsent(id.getId(), k -> new HashSet<>()).add(item.getId())); + } + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + return usedBy; + } + private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { switch (entityId.getEntityType()) { case DEVICE -> { @@ -797,7 +853,7 @@ public class DefaultIotHubService implements IotHubService { } } } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { - deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); + deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); } else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) { try { solutionService.deleteSolution(tenantId, st, user); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java new file mode 100644 index 0000000000..021cfe5be5 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.iot_hub; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.id.EntityId; + +import java.util.List; + +/** What deleting an installed item keeps, because other installed items use it too. */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class InstalledItemKeptEntities { + + private List entities; + // How many other installed items use at least one of the kept entities + private int usedByItemsCount; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class KeptEntity { + private EntityId entityId; + private String name; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index b934344e91..e1d0cd666b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode; import jakarta.servlet.http.HttpServletRequest; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.service.security.model.SecurityUser; @@ -20,6 +21,8 @@ public interface IotHubService { void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); + InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); + InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java index 57ada98db3..5a582026fd 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java +++ b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java @@ -249,6 +249,11 @@ public class DefaultSystemSecurityService implements SystemSecurityService { @Override public String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) { + return resolveBaseUrl(tenantId, customerId, httpServletRequest).url(); + } + + @Override + public ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) { String baseUrl = null; AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general"); @@ -262,10 +267,10 @@ public class DefaultSystemSecurityService implements SystemSecurityService { } if (StringUtils.isEmpty(baseUrl) && httpServletRequest != null) { - baseUrl = MiscUtils.constructBaseUrl(httpServletRequest); + return new ResolvedBaseUrl(MiscUtils.constructBaseUrl(httpServletRequest), true); } - return formatBaseUrl(baseUrl); + return new ResolvedBaseUrl(formatBaseUrl(baseUrl), false); } @Override diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java b/application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java new file mode 100644 index 0000000000..33b7c49e47 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.security.system; + +/** + * Base URL as returned by {@link SystemSecurityService#getBaseUrl}, and whether it was built from + * the request rather than taken from the Base URL in General settings. + */ +public record ResolvedBaseUrl(String url, boolean fromRequest) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java index df462aaf77..d1394bf280 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java +++ b/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java @@ -33,6 +33,8 @@ public interface SystemSecurityService { String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest); + ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest); + void logLoginAction(User user, Object authenticationDetails, ActionType actionType, Exception e); void logLoginAction(User user, Object authenticationDetails, ActionType actionType, String provider, Exception e); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 2f1a0ada5b..0f0068872c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -13,14 +14,27 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService; +import org.thingsboard.server.service.entitiy.device.TbDeviceService; import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; +import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -48,6 +62,16 @@ class DefaultIotHubServiceTest { private IotHubRestClient iotHubRestClient; @Mock private IotHubInstalledItemService iotHubInstalledItemService; + @Mock + private DeviceService deviceService; + @Mock + private EntityService entityService; + @Mock + private TbDeviceService tbDeviceService; + @Mock + private DashboardService dashboardService; + @Mock + private TbDashboardService tbDashboardService; @Spy @InjectMocks @@ -411,4 +435,72 @@ class DefaultIotHubServiceTest { assertThat(result.isRolledBack()).isFalse(); assertThat(result.getErrorMessage()).contains("install failed"); } + + @Test + void deleteInstalledItem_devicePackage_keepsEntitiesAnotherDevicePackageUses() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem deleted = devicePackage(deviceId, sharedDashboardId); + IotHubInstalledItem other = devicePackage(sharedDashboardId); + other.setItemName("Other package"); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); + Device device = new Device(deviceId); + when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceService).delete(device, user); + verify(dashboardService, never()).findDashboardById(any(), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + } + + @Test + void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() { + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID()); + DeviceProfileId sharedProfileId = new DeviceProfileId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(sharedProfileId, deviceId, sharedDashboardId); + IotHubInstalledItem first = devicePackage(sharedProfileId, sharedDashboardId); + IotHubInstalledItem second = devicePackage(sharedDashboardId); + IotHubInstalledItem unrelated = devicePackage(new DeviceId(UUID.randomUUID())); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false)); + when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile")); + when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).containsExactly( + new InstalledItemKeptEntities.KeptEntity(sharedProfileId, "Shared profile"), + new InstalledItemKeptEntities.KeptEntity(sharedDashboardId, "Shared dashboard")); + assertThat(kept.getUsedByItemsCount()).isEqualTo(2); + } + + @Test + void findKeptEntities_devicePackageSharingNothing_keepsNothing() { + IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID())); + IotHubInstalledItem other = devicePackage(new DeviceId(UUID.randomUUID())); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).isEmpty(); + assertThat(kept.getUsedByItemsCount()).isZero(); + } + + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setCreatedEntityIds(List.of(createdEntityIds)); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setDescriptor(descriptor); + return item; + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java index 8ffd947991..9a46775ede 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java @@ -8,11 +8,14 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; @@ -30,6 +33,7 @@ import org.thingsboard.server.service.security.permission.UserPermissionsService import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -201,4 +205,51 @@ public class DefaultSystemSecurityServiceTest { verify(mailService).sendAccountLockoutEmail(eq(tenantId), eq(username), eq(notificationEmail), eq(5)); } + @Test + public void resolveBaseUrlTakesRequestUrlWhenDifferentUrlsAreAllowed() { + givenGeneralSettings("https://tb.example.com", false); + + ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request()); + + assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080"); + assertThat(baseUrl.fromRequest()).isTrue(); + } + + @Test + public void resolveBaseUrlTakesSettingsUrlWhenDifferentUrlsAreProhibited() { + givenGeneralSettings("https://tb.example.com", true); + + ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request()); + + assertThat(baseUrl.url()).isEqualTo("https://tb.example.com"); + assertThat(baseUrl.fromRequest()).isFalse(); + } + + @Test + public void resolveBaseUrlFallsBackToRequestWhenSettingsUrlIsEmpty() { + givenGeneralSettings("", true); + + ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request()); + + assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080"); + assertThat(baseUrl.fromRequest()).isTrue(); + assertThat(systemSecurityService.getBaseUrl(tenantId, null, request())).isEqualTo(baseUrl.url()); + } + + private void givenGeneralSettings(String baseUrl, boolean prohibitDifferentUrl) { + AdminSettings generalSettings = new AdminSettings(); + generalSettings.setJsonValue(JacksonUtil.newObjectNode() + .put("baseUrl", baseUrl) + .put("prohibitDifferentUrl", prohibitDifferentUrl)); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general")).thenReturn(generalSettings); + } + + private static MockHttpServletRequest request() { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setScheme("http"); + request.setServerName("192.168.1.10"); + request.setServerPort(8080); + return request; + } + } diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java new file mode 100644 index 0000000000..4091794979 --- /dev/null +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.device; + +/** + * Where the host of a transport in the device connectivity info comes from. + */ +public enum DeviceConnectivityHostSource { + /** Set explicitly in the Device connectivity settings. */ + DEVICE_CONNECTIVITY, + /** Taken from the Base URL in General settings. */ + BASE_URL, + /** Taken from the address of the request. */ + REQUEST +} diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java index 4bd0ab255d..48da435d32 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java @@ -13,7 +13,19 @@ public interface DeviceConnectivityService { JsonNode findDevicePublishTelemetryCommands(String baseUrl, Device device) throws URISyntaxException; - JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException; + /** + * Resolved host and port of each enabled transport, with the source of the host. + * A blank port is replaced with the standard port of the protocol. + */ + JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException; + + /** + * Same as {@link #getConnectivityInfo(String, DeviceConnectivityHostSource)}, with a base URL + * built from the request. + */ + default JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException { + return getConnectivityInfo(baseUrl, DeviceConnectivityHostSource.REQUEST); + } Resource getPemCertFile(String protocol); diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java index b7d0f67211..c26ecaffd3 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java @@ -58,9 +58,24 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper { .put("simulated", "/simulated") .put("rssi", "") .put("snr", "") + .put("channel", "") .build(); } + @Override + protected void addGatewayAdditionalInfo(Map kvMap, JsonNode payloadJson) { + super.addGatewayAdditionalInfo(kvMap, payloadJson); + JsonNode rxMetadata = findByMaxRssi(payloadJson.at(getGatewayInfoPath())); + if (rxMetadata != null && rxMetadata.has("channel_index")) { + kvMap.put("channel", rxMetadata.get("channel_index").asInt()); + } + // The Things Stack moved the coding rate from the settings into the LoRa data rate + JsonNode loraCodingRate = payloadJson.at("/uplink_message/settings/data_rate/lora/coding_rate"); + if (!kvMap.containsKey("codeRate") && loraCodingRate.isTextual()) { + kvMap.put("codeRate", loraCodingRate.asText()); + } + } + @Override protected String getGatewayInfoPath() { return "/uplink_message/rx_metadata"; diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java index c3c154ad2f..7463b97003 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java @@ -196,6 +196,22 @@ public class ConverterUnwrapperTest { assertEquals(ContentType.JSON, result.getSecond().getContentType()); } + @Test + public void thingsStackConverterWrapperTakesCodingRateFromLoraDataRateAndChannelFromStrongestGateway() throws Exception { + ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.TTN).get(); + ObjectNode payloadMsg = JacksonUtil.fromString(readPayloadFromFile("ThingsStackPayload.json"), ObjectNode.class); + ObjectNode settings = (ObjectNode) payloadMsg.at("/uplink_message/settings"); + settings.remove("coding_rate"); + ((ObjectNode) settings.at("/data_rate/lora")).put("coding_rate", "4/6"); + ((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/0")).put("channel_index", 3); + ((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/1")).put("channel_index", 5); + + Map kvMap = wrapper.unwrap(JacksonUtil.writeValueAsBytes(payloadMsg), + new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond().getKvMap(); + + assertThat(kvMap).containsEntry("codeRate", "4/6").containsEntry("channel", 3).containsEntry("rssi", -22); + } + @Test public void thingsParkConverterWrapperTest() throws Exception { ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.THINGPARK).get(); diff --git a/common/integration/mqtt-integrations/pom.xml b/common/integration/mqtt-integrations/pom.xml index 89b3025891..b3d3a1dcb0 100644 --- a/common/integration/mqtt-integrations/pom.xml +++ b/common/integration/mqtt-integrations/pom.xml @@ -70,6 +70,11 @@ 4.13.2 test + + org.mockito + mockito-core + test + diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java index f82aabcb56..33020d91cf 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java @@ -101,6 +101,8 @@ public class BasicMqttIntegration extends AbstractMqttIntegration ctx.getIntegrationConnectTimeoutSec() && ctx.getIntegrationConnectTimeoutSec() > 0) { log.debug("Reduce connection timeout sec down to the limit [{}]", mqttClientConfiguration.getConnectTimeoutSec()); mqttClientConfiguration.setConnectTimeoutSec(ctx.getIntegrationConnectTimeoutSec()); diff --git a/common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java b/common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java new file mode 100644 index 0000000000..2270fa22e6 --- /dev/null +++ b/common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.mqtt.ttn; + +import io.netty.channel.nio.NioEventLoopGroup; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.integration.api.IntegrationContext; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.integration.IntegrationType; + +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class TtnIntegrationCheckConnectionTest { + + private NioEventLoopGroup eventLoopGroup; + private ExecutorService executor; + private IntegrationContext context; + + @Before + public void setUp() { + eventLoopGroup = new NioEventLoopGroup(1); + executor = Executors.newSingleThreadExecutor(); + context = Mockito.mock(IntegrationContext.class); + Mockito.when(context.getEventLoopGroup()).thenReturn(eventLoopGroup); + Mockito.when(context.getExecutorService()).thenReturn(executor); + Mockito.when(context.getIntegrationConnectTimeoutSec()).thenReturn(1); + Mockito.when(context.getMqttClientRetransmissionMaxAttempts()).thenReturn(1); + Mockito.when(context.getMqttClientRetransmissionInitialDelayMillis()).thenReturn(1000L); + Mockito.when(context.getMqttClientRetransmissionJitterFactor()).thenReturn(0.1); + } + + @After + public void tearDown() { + eventLoopGroup.shutdownGracefully(); + executor.shutdownNow(); + } + + // The check runs the same TTN setup as a running integration, which refuses empty credentials + @Test + public void checkRefusesEmptyCredentialsBeforeConnecting() { + Integration integration = new Integration(); + integration.setId(new IntegrationId(UUID.randomUUID())); + integration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + integration.setType(IntegrationType.TTN); + integration.setConfiguration(JacksonUtil.toJsonNode("{\"clientConfiguration\":{\"host\":\"eu1\",\"port\":8883," + + "\"connectTimeoutSec\":1,\"ssl\":true,\"credentials\":{\"type\":\"basic\",\"username\":\"\",\"password\":\"\"}}}")); + + ThingsboardException e = Assert.assertThrows(ThingsboardException.class, + () -> new TtnIntegration().doCheckConnection(integration, context)); + Assert.assertTrue(e.getMessage(), e.getMessage().contains("Application Credentials")); + } +} diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java index 8cb6d64c00..50ae0fcd43 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java @@ -63,6 +63,13 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService public static final String DEFAULT_DEVICE_TELEMETRY_TOPIC = "v1/devices/me/telemetry"; public static final String HTTP_DEFAULT_PORT = "80"; public static final String HTTPS_DEFAULT_PORT = "443"; + private static final Map STANDARD_PORTS = Map.of( + HTTP, HTTP_DEFAULT_PORT, + HTTPS, HTTPS_DEFAULT_PORT, + MQTT, "1883", + MQTTS, "8883", + COAP, "5683", + COAPS, "5684"); private final Map certs = new ConcurrentHashMap<>(); @@ -199,17 +206,16 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService } @Override - public JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException { + public JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException { String[] protocols = {HTTP, HTTPS, MQTT, MQTTS, COAP, COAPS}; - Map result = new LinkedHashMap<>(); + Map result = new LinkedHashMap<>(); for (String protocol : protocols) { DeviceConnectivityInfo info = getConnectivity(protocol); if (info != null && info.isEnabled()) { - DeviceConnectivityInfo resolved = new DeviceConnectivityInfo(); - resolved.setEnabled(true); - resolved.setHost(getHost(baseUrl, info, protocol)); - resolved.setPort(getPort(info)); - result.put(protocol, resolved); + result.put(protocol, new ResolvedDeviceConnectivityInfo(true, + getHost(baseUrl, info, protocol), + StringUtils.isBlank(info.getPort()) ? STANDARD_PORTS.get(protocol) : info.getPort(), + StringUtils.isNotBlank(info.getHost()) ? DeviceConnectivityHostSource.DEVICE_CONNECTIVITY : baseUrlSource)); } } return JacksonUtil.valueToTree(result); diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java b/dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java new file mode 100644 index 0000000000..64325ce821 --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.device; + +/** + * Host and port of an enabled transport as returned by {@link DeviceConnectivityService#getConnectivityInfo}, + * with the source of the host. Kept apart from {@link DeviceConnectivityInfo}, which models the stored settings. + */ +public record ResolvedDeviceConnectivityInfo(boolean enabled, String host, String port, + DeviceConnectivityHostSource hostSource) { +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java b/dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java new file mode 100644 index 0000000000..2a91a14654 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.device; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DeviceConnectivityServiceImplTest { + + private static final String BASE_URL = "http://192.168.1.10:8080"; + + @Mock + private AdminSettingsService adminSettingsService; + @Mock + private DeviceCredentialsService deviceCredentialsService; + @Mock + private DeviceProfileService deviceProfileService; + @InjectMocks + private DeviceConnectivityServiceImpl service; + + @Test + void configuredHostIsReportedAsDeviceConnectivity() throws Exception { + givenConnectivity(""" + {"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}"""); + + JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); + + assertThat(mqtt.get("host").asText()).isEqualTo("10.0.0.5"); + assertThat(mqtt.get("port").asText()).isEqualTo("1884"); + assertThat(mqtt.get("hostSource").asText()).isEqualTo("DEVICE_CONNECTIVITY"); + } + + @Test + void blankHostTakesBaseUrlAndItsSource() throws Exception { + givenConnectivity(""" + {"mqtt": {"enabled": true, "host": "", "port": "1883"}}"""); + + JsonNode fromRequest = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); + JsonNode fromBaseUrl = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.BASE_URL).get("mqtt"); + + assertThat(fromRequest.get("host").asText()).isEqualTo("192.168.1.10"); + assertThat(fromRequest.get("hostSource").asText()).isEqualTo("REQUEST"); + assertThat(fromBaseUrl.get("hostSource").asText()).isEqualTo("BASE_URL"); + } + + @Test + void blankPortIsReplacedWithStandardPort() throws Exception { + givenConnectivity(""" + {"http": {"enabled": true, "host": "", "port": ""}, + "https": {"enabled": true, "host": "", "port": ""}, + "mqtt": {"enabled": true, "host": "", "port": ""}, + "mqtts": {"enabled": true, "host": "", "port": ""}, + "coap": {"enabled": true, "host": "", "port": ""}, + "coaps": {"enabled": true, "host": "", "port": ""}}"""); + + JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST); + + assertThat(info.get("http").get("port").asText()).isEqualTo("80"); + assertThat(info.get("https").get("port").asText()).isEqualTo("443"); + assertThat(info.get("mqtt").get("port").asText()).isEqualTo("1883"); + assertThat(info.get("mqtts").get("port").asText()).isEqualTo("8883"); + assertThat(info.get("coap").get("port").asText()).isEqualTo("5683"); + assertThat(info.get("coaps").get("port").asText()).isEqualTo("5684"); + } + + @Test + void disabledProtocolIsLeftOut() throws Exception { + givenConnectivity(""" + {"mqtt": {"enabled": true, "host": "", "port": "1883"}, + "coap": {"enabled": false, "host": "", "port": "5683"}}"""); + + JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST); + + assertThat(info.has("mqtt")).isTrue(); + assertThat(info.has("coap")).isFalse(); + } + + @Test + void responseHasTheFieldsTheUiReads() throws Exception { + givenConnectivity(""" + {"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}"""); + + JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); + + assertThat(mqtt.fieldNames()).toIterable() + .containsExactlyInAnyOrder("enabled", "host", "port", "hostSource"); + assertThat(mqtt.get("enabled").asBoolean()).isTrue(); + } + + @Test + void overloadWithoutSourceReportsRequest() throws Exception { + givenConnectivity(""" + {"mqtt": {"enabled": true, "host": "", "port": "1883"}}"""); + + JsonNode mqtt = service.getConnectivityInfo(BASE_URL).get("mqtt"); + + assertThat(mqtt.get("host").asText()).isEqualTo("192.168.1.10"); + assertThat(mqtt.get("hostSource").asText()).isEqualTo("REQUEST"); + } + + private void givenConnectivity(String json) { + AdminSettings settings = new AdminSettings(); + settings.setJsonValue(JacksonUtil.toJsonNode(json)); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "connectivity")).thenReturn(settings); + } + +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 439976d6c5..49da0f4e6a 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -13,13 +13,13 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; import { AppState } from '@core/core.state'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; -import { DeviceConnectivitySettings } from '@shared/models/settings.models'; +import { ResolvedDeviceConnectivitySettings } from '@shared/models/settings.models'; import { environment as env } from '@env/environment'; export function tbVersionToInt(version: string): number { @@ -170,8 +170,8 @@ export class IotHubApiService { }); } - public getConnectivitySettings(config?: IotHubRequestConfig): Observable { - return this.http.get( + public getConnectivitySettings(config?: IotHubRequestConfig): Observable { + return this.http.get( `/api/iot-hub/connectivity`, { params: this.buildParams(config) } ); @@ -269,6 +269,13 @@ export class IotHubApiService { ); } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { + return this.http.get( + `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, + { params: this.buildParams(config) } + ); + } + public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { return this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 3bc2fbcbd4..8f36545817 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -49,13 +49,43 @@ } @case ('form') { -
+
+ [reviewMode]="reviewMode" + [checkConnectionTemplate]="connectionCheckOf(ws) && hasCheckConnectionField(ws) ? checkConnectionTpl : null"> + +
+ + @switch (connectionCheckMessage(ws)) { + @case ('checking') { + + } + @case ('success') { + + check_circle + {{ 'iot-hub.connection-check-success' | translate }} + + } + @case ('error') { + + error + {{ 'iot-hub.connection-check-failed' | translate }} + + } + } +
+
+ @if (connectionCheckOf(ws) && !hasCheckConnectionField(ws)) { + + }
} @@ -207,7 +237,7 @@ @for (ws of wizardSteps; track ws.label) { {{ ws.label }} @@ -252,7 +282,11 @@ @case ('form') { } @case ('progress') { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss index 9ab0b87e94..c57e41aebd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss @@ -195,6 +195,23 @@ } } +.tb-connection-check-result { + font-size: 14px; + color: #198038; + + mat-icon { + color: #198038; + } + + &.tb-connection-check-error { + color: #dd2c00; + + mat-icon { + color: #dd2c00; + } + } +} + .tb-progress-divider { width: 1px; height: 16px; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ee4a325742..9b265718b4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -7,10 +7,10 @@ import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; +import { AbstractControl, UntypedFormControl, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms'; import { MatStepper } from '@angular/material/stepper'; import { StepperSelectionEvent } from '@angular/cdk/stepper'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, Subscription } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -29,6 +29,7 @@ import { IntegrationService } from '@core/http/integration.service'; import { Converter, ConverterType } from '@shared/models/converter.models'; import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service'; import { + cleanFormFieldValue, DeviceInstallStep, DevicePackageInfo, ENTITY_STEP_TYPES, @@ -38,10 +39,16 @@ import { FormFieldType, installMethodIcons as INSTALL_METHOD_ICONS, installMethodLabels as INSTALL_METHOD_LABELS, + InstallMethod, InstallStepType, stepTypeAliasMap } from '@shared/models/iot-hub/device-package.models'; import { mergeMap } from 'rxjs/operators'; +import { + DeviceConnectivityHostSource, + DeviceConnectivityProtocol, + ResolvedDeviceConnectivityInfo +} from '@shared/models/settings.models'; export interface DeviceInstallDialogData { item: MpItemVersionView; @@ -63,15 +70,127 @@ export interface WizardStep { markdown?: string; // Form formFields?: FormFieldDefinition[]; + // Fields the dialog adds on top of the package's form file + extraFormFields?: FormFieldDefinition[]; + // Key of the step's form values in the install state; the label when not set + stateKey?: string; formGroup?: UntypedFormGroup; + // Connection check of the integration the form configures; null when the form configures none + connectionCheck?: ConnectionCheck | null; // Progress entitySteps?: EntityStepProgress[]; progressError?: string; progressDone?: boolean; } +export interface ConnectionCheck { + // The INTEGRATION step template that the form values fill + template: string; + status: 'idle' | 'checking' | 'success' | 'error'; + // The values the status is for, as JSON: only the fields the integration template uses + checkedValues?: string; + // The result shows next to the button for a few seconds after the check + resultVisible?: boolean; + resultTimer?: ReturnType; +} + const ENTITY_STEP_MIN_DELAY = 2000; +const CONNECTION_CHECK_RESULT_MS = 5000; const DEFAULT_RANDOM_SIZE = 20; +const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost'; +const TRANSPORT_PORT_FIELD_KEY = 'tbTransportPort'; +// Not the translated label, so review mode finds the values in any UI language +const TRANSPORT_STEP_STATE_KEY = 'tbTransportConnection'; + +/** + * A transport whose ${.host} / ${.port} the install form lets the user check, + * with the translation keys of its fields. The wording is per transport (the label, the hints and + * the help popup name the protocol and its default port), so each entry brings its own keys. + */ +interface HostFieldTransport { + protocol: DeviceConnectivityProtocol; + hostLabel: string; + portLabel: string; + // Hint by the source of the host; REQUEST is used when the source is unknown + hostHints: Partial> & { REQUEST: string }; + // Hint by the source of a host that resolved to a loopback address; loopbackHint when there is none + loopbackHints: Partial>; + loopbackHint: string; + // Review mode: the stored value is shown without its source + reviewHostHint: string; + // Host set in Device connectivity: the fields are read-only + configuredHint: string; + hostError: string; + portError: string; + helpPopupId: string; + helpPopupText: string; +} + +// Install methods whose packages get the transport fields. Other methods use the host differently +// (a ChirpStack package builds the ThingsBoard URL from it, a gateway puts it into docker-compose) +// and keep the resolved value until they are handled separately. +const HOST_FIELD_TRANSPORTS = new Map([ + [InstallMethod.DIRECT_MQTT, { + protocol: 'mqtt', + hostLabel: 'iot-hub.device-install-mqtt-host', + portLabel: 'iot-hub.device-install-mqtt-port', + hostHints: { + REQUEST: 'iot-hub.device-install-mqtt-host-request-hint', + BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-hint' + }, + loopbackHints: { + REQUEST: 'iot-hub.device-install-mqtt-host-opened-via-loopback-hint', + BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-loopback-hint' + }, + loopbackHint: 'iot-hub.device-install-mqtt-host-loopback-hint', + reviewHostHint: 'iot-hub.device-install-mqtt-host-hint', + configuredHint: 'iot-hub.device-install-mqtt-host-configured-hint', + hostError: 'iot-hub.device-install-transport-host-error', + portError: 'iot-hub.device-install-transport-port-error', + helpPopupId: 'iot-hub/device-connection-host', + helpPopupText: 'iot-hub.device-install-which-host' + }] +]); + +/** + * Reduces what a user may paste (a URL, host:port, [IPv6]:port) to the bare host: the port is + * a separate setting, and the scheme or path would end up in the firmware as part of the host. + */ +const toBareHost = (value: string): string => { + const hostPort = value.trim().replace(/^[a-z][a-z\d+.-]*:\/\//i, '').replace(/[/?#].*$/, ''); + const bracketed = hostPort.match(/^\[([^\]]*)](:\d*)?$/); + if (bracketed) { + return bracketed[1]; + } + // A bare IPv6 address has several colons; a single one separates the port. + const parts = hostPort.split(':'); + return parts.length === 2 ? parts[0] : hostPort; +}; + +// localhost, 127.0.0.0/8, ::1 and 0.0.0.0: a device can't reach the server at any of them. +// Unlike DeviceConnectivityUtil.isLocalhost this doesn't resolve hostnames, and it also +// rejects 0.0.0.0, which isn't a loopback address but is just as unreachable. +// Takes a bare host (see toBareHost). +const isLoopbackHost = (host: string): boolean => { + const h = host.toLowerCase(); + return h === 'localhost' || h === '::1' || h === '0.0.0.0' || /^127(\.\d{1,3}){3}$/.test(h); +}; + +// Host name, IPv4 or IPv6 characters only: the value goes into C string literals and JSON templates. +const HOST_PATTERN = /^[a-z\d._:-]+$/i; + +const transportHostValidator = (control: AbstractControl): ValidationErrors | null => { + if (!control.value) { + return null; + } + const host = toBareHost(control.value); + return !HOST_PATTERN.test(host) || isLoopbackHost(host) ? { transportHost: true } : null; +}; + +const isValidPort = (port: number): boolean => Number.isInteger(port) && port >= 1 && port <= 65535; + +const transportPortValidator = (control: AbstractControl): ValidationErrors | null => + control.value === null || control.value === '' || isValidPort(Number(control.value)) ? null : { transportPort: true }; @Component({ selector: 'tb-device-install-dialog', @@ -108,15 +227,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; + private formTemplateSubscriptions: Subscription[] = []; entityOutputs = new Map(); transportVars: Record = {}; // Routing key pre-allocated for the in-flight INTEGRATION step so ${routingKey} // placeholders (e.g. inside clientConfiguration.httpEndpoint emitted by the // export pipeline) substitute to the value we'll save. private pendingRoutingKey: string | undefined; + // protocol → where the server took its host from + private transportHostSources: Partial> = {}; // form-field key → declared type. Used by resolveTemplateJson() to emit BOOLEAN/INTEGER // placeholders as raw JSON values instead of quoted strings. private fieldTypes = new Map(); + // Transport whose ${.host} the transport host field overrides + private hostFieldProtocol: DeviceConnectivityProtocol | null = null; gatewayDockerComposeContent: string | null = null; resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this); @@ -175,10 +299,11 @@ export class TbDeviceInstallDialogComponent extends DialogComponent subscription.unsubscribe()); + this.wizardSteps?.forEach(ws => clearTimeout(ws.connectionCheck?.resultTimer)); for (const url of this.zipImages.values()) { URL.revokeObjectURL(url); } @@ -299,7 +428,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { const step = this.currentWizardStep; if (!step) { return; @@ -308,6 +437,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.checkConnection); + } + + /** The result of the last check, while the form still has the values it checked. */ + connectionCheckResult(ws: WizardStep): ConnectionCheck['status'] | undefined { + const check = this.connectionCheckOf(ws); + if (!check || check.status === 'idle') { + return undefined; + } + if (check.status === 'checking' || check.checkedValues === this.checkedValuesOf(ws, check)) { + return check.status; + } + return undefined; + } + + async checkConnection(ws: WizardStep): Promise { + const check = this.connectionCheckOf(ws); + if (!check) { + return true; + } + if (ws.formGroup.invalid) { + ws.formGroup.markAllAsTouched(); + return false; + } + this.cleanFormStep(ws); + const values = ws.formGroup.getRawValue(); + check.status = 'checking'; + this.cdr.detectChanges(); + const committedValues = this.formValues; + let body: any; + try { + // The integration is built the way Provisioning builds it, from the values not committed yet + this.formValues = { ...committedValues, ...values }; + body = this.resolveTemplateJson(this.zipFiles.get(check.template)); + } finally { + this.formValues = committedValues; + } + // The check requires a routing key; Provisioning adds one the same way + if (!body.routingKey) body.routingKey = this.generateUuid(); + if (!body.configuration) body.configuration = {}; + if (body.configuration.metadata == null) body.configuration.metadata = {}; + try { + await firstValueFrom(this.integrationService.checkIntegrationConnection(body, { ignoreErrors: true })); + check.status = 'success'; + } catch { + check.status = 'error'; + } + check.checkedValues = this.checkedValuesOf(ws, check); + check.resultVisible = true; + clearTimeout(check.resultTimer); + check.resultTimer = setTimeout(() => { + check.resultVisible = false; + this.cdr.detectChanges(); + }, CONNECTION_CHECK_RESULT_MS); + this.cdr.detectChanges(); + return check.status === 'success'; + } + + /** What shows next to the button: the spinner while checking, then the result for a few seconds. */ + connectionCheckMessage(ws: WizardStep): ConnectionCheck['status'] | undefined { + const check = this.connectionCheckOf(ws); + if (check?.status === 'checking') { + return 'checking'; + } + return check?.resultVisible && check.checkedValues === this.checkedValuesOf(ws, check) ? check.status : undefined; + } + + /** True when the last check of the current values failed, so Next continues anyway. */ + get continueAnyway(): boolean { + const step = this.currentWizardStep; + return !!step && this.connectionCheckResult(step) === 'error'; + } + + /** + * The values of the connection fields: the ones the integration template puts into its configuration + * (host, port, credentials), not e.g. its name. Other fields don't reset the check result. + */ + private checkedValuesOf(ws: WizardStep, check: ConnectionCheck): string { + const content = this.zipFiles.get(check.template) ?? ''; + const configurationStart = content.indexOf('"configuration"'); + const template = configurationStart >= 0 ? content.substring(configurationStart) : content; + const values = this.cleanedFormValues(ws); + const used = ws.formFields + .filter(field => template.includes(`\${${field.key}}`)) + .map(field => [field.key, values[field.key]]); + return JSON.stringify(used); + } + + private findIntegrationTemplate(ws: WizardStep): string | undefined { + for (const step of this.wizardSteps.flatMap(w => w.rawSteps)) { + if (step.type !== InstallStepType.INTEGRATION || !step.template) { + continue; + } + const content = this.zipFiles.get(step.template) ?? ''; + if (ws.formFields.some(field => content.includes(`\${${field.key}}`))) { + return step.template; + } + } + return undefined; + } + onStepSelectionChange(event: StepperSelectionEvent): void { if (event.selectedIndex <= event.previouslySelectedIndex) { return; } // Forward moves can come from the stepper header, which bypasses nextStep(), // so commit every step being passed over here. + let formValuesChanged = false; for (let i = event.previouslySelectedIndex; i < event.selectedIndex; i++) { const ws = this.wizardSteps[i]; if (ws.type === 'form') { + // Keep the bare host, so the stored state and the form after Back show what the device gets + const hostControl = ws.formGroup.get(TRANSPORT_HOST_FIELD_KEY); + if (hostControl?.enabled && hostControl.value) { + hostControl.setValue(toBareHost(hostControl.value), { emitEvent: false }); + } + this.cleanFormStep(ws); Object.assign(this.formValues, ws.formGroup.getRawValue()); + formValuesChanged = true; } ws.completed = true; } + if (formValuesChanged) { + // Instruction steps stay rendered, and their markdown only changes when the resolver does: + // after Back and a corrected value, they would otherwise keep showing the old one. + this.resolveMarkdownVariable = this._resolveMarkdownVariable.bind(this); + } this.onStepActivated(this.wizardSteps[event.selectedIndex]); } @@ -498,6 +762,18 @@ export class TbDeviceInstallDialogComponent extends DialogComponent s.type === 'GATEWAY'); if (gatewayStep?.dockerCompose) { const raw = this.zipFiles.get(gatewayStep.dockerCompose); @@ -665,6 +943,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent.host} and ${.port} into sketches and templates. Show them + * in the last form before the host is first used. When the system administrator set the host in + * Device connectivity, they are read-only. Otherwise the user can correct them — and must, when + * the host resolved to localhost, which on the device is the device itself. + */ + private addTransportFields(fromIndex: number): void { + this.hostFieldProtocol = null; + const transport = HOST_FIELD_TRANSPORTS.get(this.selectedInstallMethod); + const protocol = transport?.protocol; + const resolvedHost = protocol ? this.transportVars[`${protocol}.host`] : undefined; + if (resolvedHost === undefined) { + return; + } + const steps = this.wizardSteps.slice(fromIndex); + const firstUse = steps.findIndex(ws => this.usesVariable(ws, `${protocol}.host`)); + if (firstUse < 0) { + return; + } + const loopback = !resolvedHost || isLoopbackHost(resolvedHost); + const hostSource = this.transportHostSources[protocol]; + const readOnly = hostSource === 'DEVICE_CONNECTIVITY' && !loopback; + let formStep = steps.slice(0, firstUse).reverse().find(ws => ws.type === 'form'); + if (!formStep) { + formStep = { + type: 'form', + label: this.translate.instant('iot-hub.device-install-transport-host-step'), + stateKey: TRANSPORT_STEP_STATE_KEY, + rawSteps: [], + completed: this.reviewMode + }; + this.wizardSteps.splice(fromIndex + firstUse, 0, formStep); + } + let hostHint: string; + if (readOnly) { + hostHint = transport.configuredHint; + } else if (this.reviewMode) { + hostHint = transport.reviewHostHint; + } else if (loopback) { + hostHint = (hostSource && transport.loopbackHints[hostSource]) || transport.loopbackHint; + } else { + hostHint = (hostSource && transport.hostHints[hostSource]) || transport.hostHints.REQUEST; + } + const helpPopupId = readOnly ? undefined : transport.helpPopupId; + const group = this.translate.instant('iot-hub.device-install-thingsboard-connection'); + formStep.extraFormFields = [{ + key: TRANSPORT_HOST_FIELD_KEY, + label: this.translate.instant(transport.hostLabel), + type: FormFieldType.STRING, + defaultValue: loopback ? '' : resolvedHost, + required: true, + readOnly, + helpText: this.translate.instant(hostHint, { host: resolvedHost }), + // Shown on the transportHost error of transportHostValidator + errorMessage: this.translate.instant(transport.hostError), + helpPopupId, + helpPopupText: helpPopupId ? this.translate.instant(transport.helpPopupText) : undefined, + group, + row: TRANSPORT_HOST_FIELD_KEY + }]; + if (steps.some(ws => this.usesVariable(ws, `${protocol}.port`))) { + const resolvedPort = Number(this.transportVars[`${protocol}.port`]); + formStep.extraFormFields.push({ + key: TRANSPORT_PORT_FIELD_KEY, + label: this.translate.instant(transport.portLabel), + type: FormFieldType.INTEGER, + defaultValue: isValidPort(resolvedPort) ? resolvedPort : '', + required: true, + readOnly, + // Shown on the transportPort error of transportPortValidator + errorMessage: this.translate.instant(transport.portError), + group, + row: TRANSPORT_HOST_FIELD_KEY, + width: 200 + }); + } + this.hostFieldProtocol = protocol; + } + + private usesVariable(ws: WizardStep, key: string): boolean { + const placeholder = `\${${key}}`; + return ws.rawSteps.some(step => + [step.file, step.template, step.serverAttributes, step.sharedAttributes, step.credentials, step.dockerCompose] + .some(file => file && this.zipFiles.get(file)?.includes(placeholder))); + } + private initFormStep(ws: WizardStep): void { - const formJson = this.zipFiles.get(ws.rawSteps[0].file) || '[]'; - ws.formFields = JSON.parse(formJson) as FormFieldDefinition[]; + const formJson = (ws.rawSteps[0] && this.zipFiles.get(ws.rawSteps[0].file)) || '[]'; + // These are for the fields the dialog adds; a package can't set them + const packageFields = (JSON.parse(formJson) as FormFieldDefinition[]) + .map(({ helpPopupId, helpPopupText, errorMessage, ...field }) => field); + ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; + const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -723,16 +1092,78 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 0) { - validators.push(Validators.pattern(field.validators[0].pattern)); + const pattern = Validators.pattern(field.validators[0].pattern); + validators.push((control: AbstractControl) => + pattern({ value: cleanFormFieldValue(field, control.value) } as AbstractControl)); + } + if (field.key === TRANSPORT_HOST_FIELD_KEY) { + validators.push(transportHostValidator); + } else if (field.key === TRANSPORT_PORT_FIELD_KEY) { + validators.push(transportPortValidator); } const initialValue = this.resolveInitialFieldValue(field, storedValues?.[field.key]); - controls[field.key] = new UntypedFormControl(initialValue, validators); + controls[field.key] = new UntypedFormControl({ value: initialValue, disabled: !!field.readOnly }, validators); } ws.formGroup = new UntypedFormGroup(controls); if (this.reviewMode) { ws.formGroup.disable(); ws.completed = true; + } else { + this.applyDefaultValueTemplates(ws, storedValues); + } + } + + /** + * Keeps each field with a defaultValueTemplate filled from the other fields until the user edits it. + * A template with an empty field gives an empty value, so the placeholder shows instead. + */ + private applyDefaultValueTemplates(ws: WizardStep, storedValues: Record | undefined): void { + const templated = ws.formFields.filter(field => field.defaultValueTemplate && storedValues?.[field.key] === undefined); + if (!templated.length) { + return; + } + const update = () => { + for (const field of templated) { + const control = ws.formGroup.controls[field.key]; + if (!control.dirty) { + control.setValue(this.renderFormTemplate(field.defaultValueTemplate, this.cleanedFormValues(ws)), { emitEvent: false }); + } + } + }; + update(); + this.formTemplateSubscriptions.push(ws.formGroup.valueChanges.subscribe(update)); + } + + /** Applies each field's cleanupPattern to its control, so the stored values are the cleaned ones. */ + private cleanFormStep(ws: WizardStep): void { + for (const field of ws.formFields) { + const control = ws.formGroup.controls[field.key]; + const cleaned = cleanFormFieldValue(field, control?.value); + if (control?.enabled && cleaned !== control.value) { + control.setValue(cleaned, { emitEvent: false }); + } + } + } + + private cleanedFormValues(ws: WizardStep): Record { + const values = ws.formGroup.getRawValue(); + for (const field of ws.formFields) { + values[field.key] = cleanFormFieldValue(field, values[field.key]); } + return values; + } + + private renderFormTemplate(template: string, values: Record): string { + let missing = false; + const result = template.replace(/\$\{([^}]+)}/g, (_, key: string) => { + const value = values[key]; + if (value === undefined || value === null || value === '') { + missing = true; + return ''; + } + return String(value); + }); + return missing ? '' : result; } private resolveInitialFieldValue(field: FormFieldDefinition, storedValue: any): any { @@ -1252,7 +1683,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; for (const ws of this.wizardSteps) { if (ws.type === 'form' && ws.formGroup) { - state[ws.label] = { formValues: ws.formGroup.getRawValue() }; + state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() }; } else if (ws.type === 'progress' && ws.entitySteps) { for (const ep of ws.entitySteps) { if (ep.status === 'success' && ep.entityOutput) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index cdd06ae7b2..b7d1b7a978 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -7,19 +7,78 @@ --> @if (formGroup) {
- @for (field of fields; track field.key; let i = $index) { + + @if (advancedSections.length) { +
+ + + {{ 'iot-hub.advanced-settings' | translate }} + +
+ +
+
+
+ } + + + @for (section of sections; track $index) { + @if (section.title) { +
+

{{ section.title }}

+ +
+ } @else { + + } + } +
- @if (shouldRenderGroupHeader(field, i)) { -

{{ field.group }}

+ + @for (row of rows; track row.fields[0].key) { +
+ @if (row.fields.length > 1) { +
+ @for (field of row.fields; track field.key) { +
+ +
+ } +
+ } @else { + + } + + @for (field of row.fields; track field.key) { + @if (hasHintBox(field)) { +
+
{{ helpTextOf(field) }}
+
+
+ } + } + @if (checkConnectionTemplate && hasCheckConnectionField(row.fields)) { + + } +
} +
+ @if (isSecretWidget(field)) { } @else { @@ -29,15 +88,16 @@ {{ field.label }} } @case (FormFieldType.SELECT) { - + {{ field.label }} @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -45,16 +105,19 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - + {{ field.label }} - + @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -62,13 +125,19 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @case (FormFieldType.PASSWORD) { - + {{ field.label }} + [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" + [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" + autocomplete="new-password" data-lpignore="true" data-1p-ignore data-bwignore> } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -90,14 +159,20 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @case (FormFieldType.INTEGER) { - + {{ field.label }} - - @if (field.helpText) { - {{ field.helpText }} + + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -105,12 +180,18 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @default { - + {{ field.label }} - + @if (field.randomGenerator) { } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -128,17 +209,20 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } } } - @if (field.type === FormFieldType.BOOLEAN && field.helpText) { -
{{ field.helpText }}
+ @if (field.type === FormFieldType.BOOLEAN && helpTextOf(field)) { +
{{ helpTextOf(field) }}
} @if (field.helpImage) { } - } +
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss index 960c886f7b..9acd239c18 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss @@ -5,13 +5,6 @@ display: block; } -.tb-install-form-group-header { - margin: 16px 0 8px 0; - font-size: 14px; - font-weight: 600; - color: rgba(0, 0, 0, 0.6); -} - .tb-install-form-secret-toggle { margin-left: 4px; align-self: center; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index 4e4c813ae7..fedef617df 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts @@ -1,13 +1,25 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; -import { UntypedFormGroup } from '@angular/forms'; -import { FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models'; +import { Component, Input, OnChanges, SimpleChanges, TemplateRef } from '@angular/core'; +import { AbstractControl, UntypedFormGroup } from '@angular/forms'; +import { ErrorStateMatcher } from '@angular/material/core'; +import { cleanFormFieldValue, FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models'; import { generateSecret } from '@core/utils'; const DEFAULT_RANDOM_SIZE = 20; +/** Fields shown on one line. */ +interface FormRow { + fields: FormFieldDefinition[]; +} + +/** Consecutive rows of one group, shown in a panel with the group as its title; no title for ungrouped fields. */ +interface FormSection { + title?: string; + rows: FormRow[]; +} + /** * Reusable form renderer for the device install dialog's SHOW_FORM step. Consumes * the FormFieldDefinition[] parsed from the package's form.json directly — both @@ -32,10 +44,49 @@ export class InstallFormRendererComponent implements OnChanges { @Input() resolveImagePath?: (path: string) => string; /** When true, PASSWORD inputs render unmasked by default (used by review mode). */ @Input() reviewMode = false; + /** Rendered under the field marked with checkConnection; the dialog supplies it. */ + @Input() checkConnectionTemplate?: TemplateRef | null; passwordVisible: Record = {}; + // Fields in render order: consecutive fields of a group form a section, and consecutive fields + // with the same `row` share one line + sections: FormSection[] = []; + // The same for the fields of the collapsed Advanced settings panel + advancedSections: FormSection[] = []; + private rowOf = new Map(); + private focusedControl: AbstractControl | null = null; + private keepFocusedError = false; + + /** + * A new error shows only after the user leaves the field, so a value is not called wrong while it + * is typed. An error already shown when the user enters the field stays until the value is valid. + */ + readonly errorStateMatcher: ErrorStateMatcher = { + isErrorState: (control, form) => { + if (control && control === this.focusedControl) { + this.keepFocusedError = this.keepFocusedError && control.invalid; + return this.keepFocusedError; + } + return !!control?.invalid && (control.touched || !!form?.submitted); + } + }; + + readonly FormFieldType = FormFieldType; + + /** Render this field via the Secret picker widget (tb-secret-key-input). The picker + * itself accepts both plaintext and Secret references, so secretSupport=true means + * "this field MAY hold a Secret reference and the picker UI should be shown". */ + isSecretWidget(field: FormFieldDefinition): boolean { + return field.secretSupport === true; + } ngOnChanges(changes: SimpleChanges): void { + if (changes.fields) { + this.rowOf.clear(); + const fields = this.fields ?? []; + this.sections = this.buildSections(fields.filter(field => field.section !== 'advanced')); + this.advancedSections = this.buildSections(fields.filter(field => field.section === 'advanced')); + } if (changes.fields || changes.reviewMode) { this.passwordVisible = {}; if (this.reviewMode) { @@ -48,20 +99,33 @@ export class InstallFormRendererComponent implements OnChanges { } } - readonly FormFieldType = FormFieldType; + private buildSections(fields: FormFieldDefinition[]): FormSection[] { + const sections: FormSection[] = []; + let previous: FormFieldDefinition | undefined; + for (const field of fields) { + if (!previous || field.group !== previous.group) { + sections.push({ title: field.group, rows: [] }); + } + const rows = sections[sections.length - 1].rows; + const last = rows[rows.length - 1]; + if (field.row && last?.fields[0].row === field.row) { + last.fields.push(field); + } else { + rows.push({ fields: [field] }); + } + this.rowOf.set(field.key, rows[rows.length - 1]); + previous = field; + } + return sections; + } - /** Render this field via the Secret picker widget (tb-secret-key-input). The picker - * itself accepts both plaintext and Secret references, so secretSupport=true means - * "this field MAY hold a Secret reference and the picker UI should be shown". */ - isSecretWidget(field: FormFieldDefinition): boolean { - return field.secretSupport === true; + hasCheckConnectionField(fields: FormFieldDefinition[]): boolean { + return fields.some(field => field.checkConnection); } - /** True when the previous field belonged to a different group (for header rendering). */ - shouldRenderGroupHeader(field: FormFieldDefinition, index: number): boolean { - if (!field.group) return false; - if (index === 0) return true; - return this.fields[index - 1].group !== field.group; + /** The hint of a field that a defaultValueTemplate fills describes the filled value. */ + helpTextOf(field: FormFieldDefinition): string | undefined { + return field.defaultValueTemplate && field.defaultValueTemplateHelpText ? field.defaultValueTemplateHelpText : field.helpText; } togglePasswordVisible(key: string): void { @@ -75,10 +139,44 @@ export class InstallFormRendererComponent implements OnChanges { control.markAsDirty(); } + onFocus(field: FormFieldDefinition): void { + const control = this.formGroup.controls[field.key]; + this.focusedControl = control ?? null; + this.keepFocusedError = !!control?.invalid && control.touched; + } + + onBlur(field: FormFieldDefinition): void { + this.focusedControl = null; + const control = this.formGroup.controls[field.key]; + const cleaned = cleanFormFieldValue(field, control?.value); + if (control && cleaned !== control.value) { + control.setValue(cleaned); + } + } + getPatternErrorMessage(field: FormFieldDefinition): string { return field.validators?.[0]?.message || 'Invalid format'; } + /** Fields with a help popup show their hint in a box under the row, with the popup trigger. */ + hasHintBox(field: FormFieldDefinition): boolean { + return !!field.helpPopupId && !this.reviewMode; + } + + /** + * True for the fields of a row that has a hint box. They don't reserve space for a hint or an + * error, so the box sits right under them. + */ + isInHintBoxRow(field: FormFieldDefinition): boolean { + return !!this.rowOf.get(field.key)?.fields.some(f => this.hasHintBox(f)); + } + + /** True when the field fails a validator other than required and pattern (one the dialog added). */ + hasFieldError(field: FormFieldDefinition): boolean { + const errors = this.formGroup.controls[field.key]?.errors; + return !!errors && Object.keys(errors).some(key => key !== 'required' && key !== 'pattern'); + } + imagePath(path: string): string { return this.resolveImagePath ? this.resolveImagePath(path) : path; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index a3ad857308..b04932040d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -4,12 +4,13 @@ import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of, EMPTY } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; import { DialogService } from '@core/services/dialog.service'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; -import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DeviceInstalledItemDescriptor, IotHubInstalledItem, IotHubInstalledItemKeptEntities } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { EntityId } from '@shared/models/id/entity-id'; import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemDialogResult } from './iot-hub-add-item-dialog.component'; import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component'; @@ -35,7 +36,8 @@ export class IotHubActionsService { private dialog: MatDialog, private dialogService: DialogService, private translate: TranslateService, - private builtInService: IotHubBuiltInService + private builtInService: IotHubBuiltInService, + private iotHubApiService: IotHubApiService ) {} openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, @@ -166,12 +168,18 @@ export class IotHubActionsService { if (!installedItem) { return of(false); } - return this.dialog.open(TbIotHubDeleteDialogComponent, { - panelClass: ['tb-dialog'], - disableClose: true, - autoFocus: false, - data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType } - }).afterClosed(); + // A device package keeps what other installed packages use: the dialog opens with that already known + const keptEntities$: Observable = installedItem.itemType === 'DEVICE' ? + this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) : + of(null); + return keptEntities$.pipe( + switchMap(keptEntities => this.dialog.open(TbIotHubDeleteDialogComponent, { + panelClass: ['tb-dialog'], + disableClose: true, + autoFocus: false, + data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType, keptEntities } + }).afterClosed()) + ); } // Reached only for items whose action mode is 'connect', i.e. never for built-in content: diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 3270cfd641..60eb673a23 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -1,12 +1,13 @@

{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}

-

{{ (data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc') | translate }}

+

{{ description }}

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 86ad80c197..63fa684164 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -1,5 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +:host { + display: block; + max-width: 600px; +} + .tb-iot-hub-delete-title { font-size: 20px; font-weight: 600; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 4447dc8a23..56a9c82543 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -1,18 +1,21 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { IotHubInstalledItem } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { TranslateService } from '@ngx-translate/core'; export interface IotHubDeleteDialogData { installedItemId: string; itemName: string; itemType?: string; + keptEntities?: IotHubInstalledItemKeptEntities | null; } @Component({ @@ -23,14 +26,19 @@ export interface IotHubDeleteDialogData { }) export class TbIotHubDeleteDialogComponent extends DialogComponent { + description: string; + constructor( protected store: Store, protected router: Router, protected dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: IotHubDeleteDialogData, - private iotHubApiService: IotHubApiService + private iotHubApiService: IotHubApiService, + private translate: TranslateService ) { super(store, router, dialogRef); + this.description = data.keptEntities?.entities.length ? this.describeKeptEntities(data.keptEntities) : + this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); } confirm(): void { @@ -44,4 +52,17 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent { + const key = `iot-hub.remove-kept-entity.${entity.entityId.entityType}`; + const named = this.translate.instant(key, { name: entity.name }); + return named === key ? `'${entity.name}'` : named; + }); + const entities = names.length === 1 ? names[0] : + this.translate.instant('iot-hub.remove-kept-entities', { first: names.slice(0, -1).join(', '), last: names[names.length - 1] }); + return this.translate.instant('iot-hub.remove-desc-kept', + { entities, count: kept.usedByItemsCount, kept: kept.entities.length }); + } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index f4885183cd..ab41384640 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -1,7 +1,8 @@
@@ -88,9 +89,12 @@ info_outline } - + + + + @@ -107,9 +111,9 @@ {{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }} } -