Browse Source

Merge pull request #16537 from ShvaykaD/feature/lts-4.4/iot-hub-converter-update-dialog

IoT Hub: a confirm dialog updates a device package's default converter
pull/16545/head
Shvaika Dmytro 1 month ago
committed by GitHub
parent
commit
08a3834cda
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 14
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  2. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java
  3. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java
  4. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java
  5. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  6. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
  7. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java
  8. 51
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  9. 3
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java
  10. 3
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  11. 3
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  12. 3
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  13. 3
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  14. 3
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  15. 36
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  16. 45
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  17. 2
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts
  18. 33
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html
  19. 65
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss
  20. 79
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts
  21. 72
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  22. 2
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  23. 3
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss
  24. 34
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  25. 45
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts
  26. 1
      ui-ngx/src/assets/locale/locale.constant-en_US.json

14
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
@ -348,6 +348,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
}
// An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps
// it changes: the other steps and the forms keep their install state
if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) {
previous.getInstallState().forEach((key, value) -> {
if (value instanceof ObjectNode state) {
installState.putIfAbsent(key, state);
}
});
}
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
// The new version may not offer the method the package was installed with
descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod());

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import lombok.AllArgsConstructor;

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.node.ObjectNode;

4
application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;

51
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
@ -531,6 +531,53 @@ class DefaultDevicePackageUpdateServiceTest {
verify(installedItemService, never()).save(tenantId, taker);
}
@Test
void updateOfTheInstalledVersion_keepsTheInstallStateOfTheStepsItLeavesOut() {
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter current = new Converter(converterId);
current.setTenantId(tenantId);
current.setName("Uplink data converter for TTN my-app");
current.setVersion(4L);
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current);
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0));
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId, converterId));
installed.setInstallState(Map.of("Integration", stateOf(integrationId, "created"), "uplink", stateOf(converterId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("profileName", "am308"))));
ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0");
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo);
// ThingsBoard's default converter changed: only the converter step is sent
DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setId("uplink");
step.setDefaultConverter(true);
DeviceUpdateRequest request = request(step);
request.setVersionId(installedVersionId.toString());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
ArgumentCaptor<Converter> saved = ArgumentCaptor.forClass(Converter.class);
verify(converterService).saveConverter(saved.capture());
assertThat(state.get("uplink").get("checksum").asText()).isEqualTo(EntityChecksum.of(saved.getValue()));
assertThat(state.get("uplink").get("defaultConverter").asBoolean()).isTrue();
assertThat(state.get("Integration")).isEqualTo(stateOf(integrationId, "created"));
assertThat(state.get("Configuration").get("formValues").get("profileName").asText()).isEqualTo("am308");
verify(integrationService, never()).saveIntegration(any());
assertThat(installedItem.getItemVersionId()).isEqualTo(installedVersionId);
}
@Test
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard");
}
@Test
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID());

3
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.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.common.data.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;

3
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.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.dao.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;

3
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.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.dao.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;

3
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.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.dao.iot_hub;
import lombok.RequiredArgsConstructor;

3
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.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.dao.sql.iot_hub;
import org.springframework.data.domain.Page;

3
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.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.dao.sql.iot_hub;
import lombok.RequiredArgsConstructor;

36
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

@ -40,6 +40,7 @@ import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { IntegrationType } from '@shared/models/integration.models';
import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter';
import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils';
import {
cleanFormFieldValue,
DeviceInstallStep,
@ -119,15 +120,6 @@ export interface DeviceInstallUpdate {
fromVersion: string;
}
// ThingsBoard error codes whose message is written for the user: validation, permission, not found, limits
const SHOWN_ERROR_CODES = new Set([20, 30, 31, 32, 33, 34, 35, 40, 41]);
const MAX_SHOWN_ERROR_LENGTH = 200;
/** The message as it is when it reads like one written for the user, null for an internal one (a stack trace, a URL, too long). */
const readableMessage = (message: unknown): string | null =>
typeof message === 'string' && message.trim() && message.length <= MAX_SHOWN_ERROR_LENGTH &&
!/exception|java\.|https?:\/\/|\bat [\w.$]+\(/i.test(message) ? message : null;
// Fields the server sets, or that the update keeps as they are: they don't count as changes the user made.
// Nor do the debug settings, which change nothing the entity does, and whether a profile is the default one.
const SERVER_SET_KEYS = new Set(['id', 'name', 'title', 'routingKey', 'version', 'createdTime', 'tenantId', 'customerId',
@ -2014,18 +2006,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
}
/**
* What the user sees for a failed request: ThingsBoard's validation and limit messages as they are,
* anything else (a server error, the network, a bug) as a common message, with the details in the console.
*/
private failureMessage(error: any): string {
const body = error?.error;
const message = SHOWN_ERROR_CODES.has(body?.errorCode) ? readableMessage(body.message) : null;
if (message) {
return message;
}
console.error('Device package step failed', error);
return this.translate.instant('iot-hub.device-install-unexpected-error');
return requestFailureMessage(error, this.translate);
}
// --- Update ---
@ -2054,7 +2036,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
}
/** A translated text with a link written as <a>…</a>, which the translation may put anywhere in it, split around the link. */
/** Update: what the update did with the entity of a row, once it succeeded. */
updateOutcomeOf(plan: EntityStepPlan | undefined): string {
if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') {
@ -2064,9 +2045,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
textWithLink(key: string): { before: string; link: string; after: string } {
const text: string = this.translate.instant(key);
const match = /^([\s\S]*)<a>([\s\S]*)<\/a>([\s\S]*)$/.exec(text);
return match ? { before: match[1], link: match[2], after: match[3] } : { before: text, link: '', after: '' };
return splitTextWithLink(this.translate.instant(key));
}
/** Update: saves the entity the user changed, as it is before the update overwrites it, to a JSON file. */
@ -2075,14 +2054,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!current) {
return;
}
const blob = new Blob([JSON.stringify(current, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${(ep.resolvedName || ep.step.name).replace(/[^\w\- ]+/g, '_')}.json`;
link.click();
// Revoked right away, the URL may be gone before the download starts
setTimeout(() => URL.revokeObjectURL(url), 0);
downloadEntityJson(current, ep.resolvedName || ep.step.name);
}
/**

45
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable, of, EMPTY } from 'rxjs';
import { Observable, of, EMPTY, firstValueFrom, from } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { DialogService } from '@core/services/dialog.service';
@ -11,6 +11,9 @@ 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, IotHubInstalledItemKeptEntities } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { ConverterService } from '@core/http/converter.service';
import { Converter } from '@shared/models/converter.models';
import { HasVersion } from '@shared/models/entity.models';
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';
@ -21,6 +24,8 @@ import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallU
import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component';
import { IotHubBuiltInService } from './iot-hub-built-in.service';
import { isBuiltInItem } from './iot-hub-utils';
import { TbIotHubConverterUpdateDialogComponent, IotHubConverterUpdateDialogData } from './iot-hub-converter-update-dialog.component';
import { DefaultConverterUpdate, loadInstalledDevicePackages } from './iot-hub-default-converter';
/**
* What `openBuiltInOrConfirmInstall` did with a built-in item: 'handled' means nothing is left to do
@ -37,7 +42,8 @@ export class IotHubActionsService {
private dialogService: DialogService,
private translate: TranslateService,
private builtInService: IotHubBuiltInService,
private iotHubApiService: IotHubApiService
private iotHubApiService: IotHubApiService,
private converterService: ConverterService
) {}
openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number,
@ -167,6 +173,41 @@ export class IotHubActionsService {
}).afterClosed();
}
/**
* Brings a device package's default converter to ThingsBoard's default converter now, after the user confirms it.
* The dialog opens with what the update check found: whether someone changed the converter, and which other packages use it.
*/
updateDefaultConverter(update: DefaultConverterUpdate): Observable<boolean> {
return from(this.converterUpdateDialogData(update)).pipe(
switchMap(data => this.dialog.open<TbIotHubConverterUpdateDialogComponent, IotHubConverterUpdateDialogData, boolean>(
TbIotHubConverterUpdateDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data
}).afterClosed()),
catchError(() => of(false))
);
}
private async converterUpdateDialogData(update: DefaultConverterUpdate): Promise<IotHubConverterUpdateDialogData> {
const installedItemId = update.installedItem.id.id;
const converterId = update.converter.id.id;
// The converter as it is now, not the table's copy: the dialog downloads it, and the update overwrites only this version
const [states, packages, converter] = await Promise.all([
firstValueFrom(this.iotHubApiService.checkDeviceUpdate(installedItemId)),
loadInstalledDevicePackages(this.iotHubApiService),
firstValueFrom(this.converterService.getConverter(converterId)) as Promise<Converter & HasVersion>
]);
const state = states.find(s => s.stepName === update.stateKey);
// As the server decides what is shared: the converter is one of the entities another package tracks
const usedBy = packages
.filter(item => item.id.id !== installedItemId &&
(item.descriptor as DeviceInstalledItemDescriptor)?.createdEntityIds?.some(id => id.id === converterId))
.map(item => item.itemName);
return { update: { ...update, converter }, version: converter.version ?? state?.version, modified: state?.modified === true, usedBy };
}
deleteItem(installedItem: IotHubInstalledItem): Observable<boolean> {
if (!installedItem) {
return of(false);

2
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts

@ -11,6 +11,7 @@ import { TbIotHubAddItemDialogComponent } from './iot-hub-add-item-dialog.compon
import { TbIotHubInstallDialogComponent } from './iot-hub-install-dialog.component';
import { TbIotHubUpdateDialogComponent } from './iot-hub-update-dialog.component';
import { TbIotHubDeleteDialogComponent } from './iot-hub-delete-dialog.component';
import { TbIotHubConverterUpdateDialogComponent } from './iot-hub-converter-update-dialog.component';
import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished-warning-dialog.component';
import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component';
import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component';
@ -27,6 +28,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
@NgModule({
declarations: [
TbIotHubConverterUpdateDialogComponent,
TbIotHubItemDetailDialogComponent,
TbIotHubBrowseComponent,
TbIotHubItemCardComponent,

33
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html

@ -0,0 +1,33 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="flex flex-col gap-4 p-6">
<h2 class="tb-converter-update-title">{{ 'iot-hub.converter-update-title' | translate }}</h2>
<p class="tb-converter-update-text">{{ 'iot-hub.device-update-new-default-converter' | translate }}</p>
<div class="tb-converter-update-box flex flex-col gap-2">
<div class="tb-converter-update-name">{{ data.update.converter.name }}</div>
@if (data.usedBy.length) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span>
<ul class="tb-converter-update-packages">
@for (name of data.usedBy; track $index) {
<li>{{ name }}</li>
}
</ul>
}
@if (data.modified) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ modifiedHint.before }}<a class="tb-converter-update-link" href="#" (click)="$event.preventDefault(); downloadCurrent()">{{ modifiedHint.link }}</a>{{ modifiedHint.after }}
</span>
}
</div>
@if (errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ errorMessage }}</span>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">
<button mat-button (click)="cancel()" [disabled]="updating">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary" (click)="update()" [disabled]="updating">{{ 'iot-hub.update' | translate }}</button>
</div>

65
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss

@ -0,0 +1,65 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
:host {
display: block;
max-width: 600px;
}
.tb-converter-update-title {
font-size: 20px;
font-weight: 600;
line-height: 24px;
letter-spacing: 0.1px;
color: rgba(0, 0, 0, 0.87);
margin: 0;
}
.tb-converter-update-text {
font-size: 14px;
line-height: 20px;
letter-spacing: 0.2px;
color: rgba(0, 0, 0, 0.54);
margin: 0;
}
.tb-converter-update-box {
padding: 12px 16px;
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 8px;
}
.tb-converter-update-name {
font-size: 14px;
font-weight: 500;
line-height: 20px;
color: rgba(0, 0, 0, 0.87);
}
.tb-converter-update-packages {
margin: 0;
padding-left: 20px;
font-size: 12px;
line-height: 16px;
color: rgba(0, 0, 0, 0.54);
}
.tb-converter-update-link {
color: #305680;
text-decoration: underline;
cursor: pointer;
}
.tb-progress-alert-msg {
font-size: 12px;
font-weight: 400;
line-height: 16px;
letter-spacing: 0.4px;
&.tb-progress-alert-msg-warning {
color: #f66716;
}
&.tb-progress-alert-msg-error {
color: #dd2c00;
}
}

79
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts

@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: 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 { TranslateService } from '@ngx-translate/core';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DefaultConverterUpdate, defaultConverterUpdateRequest } from '@home/components/iot-hub/iot-hub-default-converter';
import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils';
export interface IotHubConverterUpdateDialogData {
update: DefaultConverterUpdate;
// The version of the converter the dialog downloads: the server refuses the update if someone saved the converter since
version?: number;
// Someone changed the converter since a package installed or last updated it
modified: boolean;
// The names of the other installed packages that use the converter
usedBy: string[];
}
/**
* Brings an installed device package's default converter to ThingsBoard's default converter now, without a new version of
* the package. Closes with true once it is updated.
*/
@Component({
selector: 'tb-iot-hub-converter-update-dialog',
standalone: false,
templateUrl: './iot-hub-converter-update-dialog.component.html',
styleUrls: ['./iot-hub-converter-update-dialog.component.scss']
})
export class TbIotHubConverterUpdateDialogComponent extends DialogComponent<TbIotHubConverterUpdateDialogComponent, boolean> {
readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified'));
updating = false;
errorMessage: string | null = null;
constructor(
protected store: Store<AppState>,
protected router: Router,
protected dialogRef: MatDialogRef<TbIotHubConverterUpdateDialogComponent, boolean>,
@Inject(MAT_DIALOG_DATA) public data: IotHubConverterUpdateDialogData,
private iotHubApiService: IotHubApiService,
private translate: TranslateService
) {
super(store, router, dialogRef);
}
downloadCurrent(): void {
downloadEntityJson(this.data.update.converter, this.data.update.converter.name);
}
update(): void {
this.updating = true;
this.errorMessage = null;
this.iotHubApiService.updateDevicePackage(this.data.update.installedItem.id.id,
defaultConverterUpdateRequest(this.data.update, this.data.version), { ignoreErrors: true }).subscribe({
next: result => {
if (result.success) {
this.dialogRef.close(true);
return;
}
// Nothing was changed: the server rolled it back
this.updating = false;
this.errorMessage = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error');
},
error: error => {
this.updating = false;
this.errorMessage = requestFailureMessage(error, this.translate);
}
});
}
cancel(): void {
this.dialogRef.close(false);
}
}

72
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -1,16 +1,25 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { firstValueFrom } from 'rxjs';
import { ResourcesService } from '@core/services/resources.service';
import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models';
import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data';
/** An installed device package's default converter that differs from ThingsBoard's default converter now. */
export interface DefaultConverterUpdate {
installedItem: IotHubInstalledItem;
// The key of the converter's step in the package's install state
stateKey: string;
converter: Converter;
defaultConverter: Partial<Converter>;
}
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json';
// The settings of a default converter that decide what it does: the script is compared on its own
@ -60,6 +69,19 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null));
};
/** All installed device packages of the tenant. */
export const loadInstalledDevicePackages = async (iotHubApiService: IotHubApiService): Promise<IotHubInstalledItem[]> => {
const items: IotHubInstalledItem[] = [];
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
items.push(...page.data);
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
return items;
};
/**
* The converters device packages installed themselves as their default converter, not ones they took as they were, of
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version
@ -67,18 +89,40 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert
*/
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => {
const ids = new Set<string>();
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
for (const item of page.data) {
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) {
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') {
ids.add(state.entityOutput.id);
}
for (const item of await loadInstalledDevicePackages(iotHubApiService)) {
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) {
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') {
ids.add(state.entityOutput.id);
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
}
return ids;
};
/**
* The update of the installed version itself that brings its default converter to ThingsBoard's default one. It sends only
* the converter step: the server keeps the other steps, the forms and the integration's metadata as they are.
* expectedVersion is the converter's version the user reviewed.
*/
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => {
const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor;
return {
versionId: update.installedItem.itemVersionId,
fromVersionId: update.installedItem.itemVersionId,
selectedInstallMethod: descriptor.selectedInstallMethod,
installState: {},
steps: [{
name: update.converter.name,
id: update.stateKey,
type: 'UPLINK_CONVERTER',
action: 'OVERWRITE',
entityId: update.converter.id.id,
expectedVersion,
// The user confirmed it in the dialog, which names the other packages it affects
confirmed: true,
resolution: descriptor.installState?.[update.stateKey]?.resolution ?? 'created',
defaultConverter: true,
entity: update.defaultConverter
}]
};
};

2
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html

@ -57,7 +57,7 @@
}
</div>
} @else if (hasConverterUpdate(item)) {
<!-- The update of the same version: only ThingsBoard's default converter changed -->
<!-- Only ThingsBoard's default converter changed: the package has no new version for it -->
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateConverter(item)">
<mat-icon>arrow_upward</mat-icon>
{{ 'iot-hub.new-converter-available' | translate }}

3
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss

@ -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
@import "../../../../../scss/constants";
:host {

34
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts

@ -38,7 +38,12 @@ import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { ConverterService } from '@core/http/converter.service';
import { ResourcesService } from '@core/services/resources.service';
import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter';
import {
DefaultConverterUpdate,
differsFromDefaultConverter,
loadDefaultUplinkConverter,
loadOwnDefaultConverterIds
} from '@home/components/iot-hub/iot-hub-default-converter';
import { firstValueFrom } from 'rxjs';
@Component({
@ -73,7 +78,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
publishedVersionMap = new Map<string, ItemPublishedVersionInfo>();
// Installed device packages whose default converter differs from ThingsBoard's default converter now
converterUpdates = new Set<string>();
converterUpdates = new Map<string, DefaultConverterUpdate>();
private converterCheckRun = 0;
updatesChecked = false;
isCheckingUpdates = false;
@ -264,10 +269,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
return this.converterUpdates.has(item.id.id);
}
/** The update to the installed version itself brings the converter to ThingsBoard's default one. */
/** Brings the package's default converter to ThingsBoard's default one. Other packages on the converter take it too. */
updateConverter(item: IotHubInstalledItem): void {
this.iotHubActions.updateItem(item, item.version, item.itemVersionId).subscribe(result => {
if (result === 'updated') {
const update = this.converterUpdates.get(item.id.id);
if (!update) {
return;
}
this.iotHubActions.updateDefaultConverter(update).subscribe(updated => {
if (updated) {
this.loadData();
}
});
@ -281,12 +290,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
// A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win
const run = ++this.converterCheckRun;
// The package's default converter of each DEVICE package on the page
const checks: { itemId: string; converterId: string }[] = [];
const checks: { item: IotHubInstalledItem; stateKey: string; converterId: string }[] = [];
// Over all installed packages, not only this page's, as the update dialog decides
let ownDefaultConverterIds: Set<string> | undefined;
for (const item of this.dataSource) {
const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : [];
for (const state of states) {
const states = item.itemType === 'DEVICE' ? Object.entries((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : [];
for (const [stateKey, state] of states) {
const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined;
if (!id) {
continue;
@ -298,10 +307,10 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
continue;
}
}
checks.push({ itemId: item.id.id, converterId: id });
checks.push({ item, stateKey, converterId: id });
}
}
const changed = await Promise.all(checks.map(async ({ itemId, converterId }) => {
const changed = await Promise.all(checks.map(async ({ item, stateKey, converterId }): Promise<DefaultConverterUpdate | null> => {
const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true}))
.catch(() => null);
if (!converter) {
@ -309,12 +318,13 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
}
const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType,
converter.configuration.scriptLang, converter.name);
return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ? itemId : null;
return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ?
{ installedItem: item, stateKey, converter, defaultConverter } : null;
}));
if (run !== this.converterCheckRun) {
return;
}
this.converterUpdates = new Set(changed.filter(itemId => !!itemId));
this.converterUpdates = new Map(changed.filter(update => !!update).map(update => [update.installedItem.id.id, update]));
this.cd.markForCheck();
}

45
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts

@ -1,8 +1,10 @@
// 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 { FilterParamInfo, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
export const IOT_HUB_FILTER_GROUPING_THRESHOLD = 11;
export const IOT_HUB_FILTER_POPULAR_LIMIT = 10;
@ -123,3 +125,44 @@ export function resolveIotHubItemImageUrl(item: MpItemVersionView, api: IotHubAp
}
return null;
}
// ThingsBoard error codes whose message is written for the user: validation, permission, not found, limits
const SHOWN_ERROR_CODES = new Set([20, 30, 31, 32, 33, 34, 35, 40, 41]);
const MAX_SHOWN_ERROR_LENGTH = 200;
/** The message as it is when it reads like one written for the user, null for an internal one (a stack trace, a URL, too long). */
export const readableMessage = (message: unknown): string | null =>
typeof message === 'string' && message.trim() && message.length <= MAX_SHOWN_ERROR_LENGTH &&
!/exception|java\.|https?:\/\/|\bat [\w.$]+\(/i.test(message) ? message : null;
/**
* What the user sees for a failed request: ThingsBoard's validation and limit messages as they are,
* anything else (a server error, the network, a bug) as a common message, with the details in the console.
*/
export const requestFailureMessage = (error: any, translate: TranslateService): string => {
const body = error?.error;
const message = SHOWN_ERROR_CODES.has(body?.errorCode) ? readableMessage(body.message) : null;
if (message) {
return message;
}
console.error('Device package request failed', error);
return translate.instant('iot-hub.device-install-unexpected-error');
};
/** A translated text with a link written as <a>…</a>, which the translation may put anywhere in it, split around the link. */
export const splitTextWithLink = (text: string): { before: string; link: string; after: string } => {
const match = /^([\s\S]*)<a>([\s\S]*)<\/a>([\s\S]*)$/.exec(text);
return match ? { before: match[1], link: match[2], after: match[3] } : { before: text, link: '', after: '' };
};
/** Saves an entity as a JSON file named after it. */
export const downloadEntityJson = (entity: any, name: string): void => {
const blob = new Blob([JSON.stringify(entity, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${name.replace(/[^\w\- ]+/g, '_')}.json`;
link.click();
// Revoked right away, the URL may be gone before the download starts
setTimeout(() => URL.revokeObjectURL(url), 0);
};

1
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -6455,6 +6455,7 @@
"updates": "Updates",
"up-to-date": "Up to date",
"new-converter-available": "New converter available",
"converter-update-title": "Update the converter?",
"update": "Update",
"update-to-version": "Update to v {{ version }}",
"update-item-title": "Update Item",

Loading…
Cancel
Save