Browse Source
- New /api/ai/resources endpoints (config, upload, download, delete) proxy file uploads to TB AI over the channel.
- Solution Creator messages go through a new JSON endpoint /api/ai/solution/{id}/{step}/messages carrying the attached
resource ids; the plain-text chat endpoint stays unchanged.
- The chat composer gets a + button, drag and drop onto the chat, paste of screenshots, image downscaling before
upload, previews with upload progress and remove, and a toolbar layout below the text; sent messages show image
thumbnails with a preview dialog and file chips that download the file.
pull/16551/head
29 changed files with 1471 additions and 51 deletions
@ -0,0 +1,88 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.controller; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.http.CacheControl; |
|||
import org.springframework.http.ContentDisposition; |
|||
import org.springframework.http.HttpHeaders; |
|||
import org.springframework.http.HttpStatus; |
|||
import org.springframework.http.MediaType; |
|||
import org.springframework.http.ResponseEntity; |
|||
import org.springframework.security.access.prepost.PreAuthorize; |
|||
import org.springframework.web.bind.annotation.DeleteMapping; |
|||
import org.springframework.web.bind.annotation.GetMapping; |
|||
import org.springframework.web.bind.annotation.PathVariable; |
|||
import org.springframework.web.bind.annotation.PostMapping; |
|||
import org.springframework.web.bind.annotation.RequestMapping; |
|||
import org.springframework.web.bind.annotation.RequestPart; |
|||
import org.springframework.web.bind.annotation.ResponseStatus; |
|||
import org.springframework.web.bind.annotation.RestController; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.permission.Operation; |
|||
import org.thingsboard.server.common.data.permission.Resource; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.ai.resource.AiResourceService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.time.Duration; |
|||
import java.util.UUID; |
|||
|
|||
@RequiredArgsConstructor |
|||
@RestController |
|||
@TbCoreComponent |
|||
@RequestMapping("/api/ai/resources") |
|||
class AiResourceController extends BaseController { |
|||
|
|||
private final AiResourceService aiResourceService; |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@GetMapping("/config") |
|||
public JsonNode getConfig() throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
|||
return aiResourceService.getConfig(user); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) |
|||
@ResponseStatus(HttpStatus.CREATED) |
|||
public JsonNode uploadResource(@RequestPart("file") MultipartFile file) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
|||
return aiResourceService.upload(file, user); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@GetMapping("/{resourceId}") |
|||
public ResponseEntity<byte[]> downloadResource(@PathVariable UUID resourceId) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
|||
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user); |
|||
return ResponseEntity.ok() |
|||
.contentType(MediaType.parseMediaType(content.mediaType())) |
|||
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name())) |
|||
.header("X-Content-Type-Options", "nosniff") |
|||
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate()) |
|||
.body(content.data()); |
|||
} |
|||
|
|||
private static String disposition(String name) { |
|||
ContentDisposition.Builder builder = ContentDisposition.attachment(); |
|||
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name); |
|||
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString(); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@DeleteMapping("/{resourceId}") |
|||
@ResponseStatus(HttpStatus.NO_CONTENT) |
|||
public void deleteResource(@PathVariable UUID resourceId) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
|||
aiResourceService.delete(resourceId, user); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.resource; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.UUID; |
|||
|
|||
public interface AiResourceService { |
|||
|
|||
JsonNode getConfig(SecurityUser user); |
|||
|
|||
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException; |
|||
|
|||
AiResourceContent download(UUID resourceId, SecurityUser user); |
|||
|
|||
void delete(UUID resourceId, SecurityUser user); |
|||
|
|||
record AiResourceContent(String name, String mediaType, byte[] data) {} |
|||
|
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.resource; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Service; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.ai.common.channel.ChannelProtocol; |
|||
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
|||
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.ai.TbAiService; |
|||
import org.thingsboard.server.service.ai.transport.TbAiOperation; |
|||
import org.thingsboard.server.service.ai.transport.TbAiOperations; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.io.IOException; |
|||
import java.util.Base64; |
|||
import java.util.UUID; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
class DefaultAiResourceService implements AiResourceService { |
|||
|
|||
static final long MAX_UPLOAD_BYTES = 7L * 1024 * 1024; |
|||
|
|||
private final TbAiService tbAiService; |
|||
private final TbAiOperations operations; |
|||
|
|||
@Override |
|||
public JsonNode getConfig(SecurityUser user) { |
|||
return tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
@Override |
|||
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException { |
|||
if (file == null || file.isEmpty()) { |
|||
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
} |
|||
if (file.getSize() > MAX_UPLOAD_BYTES) { |
|||
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
} |
|||
String data; |
|||
try { |
|||
data = Base64.getEncoder().encodeToString(file.getBytes()); |
|||
} catch (IOException e) { |
|||
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL); |
|||
} |
|||
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data); |
|||
return tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
@Override |
|||
public AiResourceContent download(UUID resourceId, SecurityUser user) { |
|||
JsonNode content = tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
|||
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(), |
|||
Base64.getDecoder().decode(content.path("data").asText())); |
|||
} |
|||
|
|||
@Override |
|||
public void delete(UUID resourceId, SecurityUser user) { |
|||
tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,195 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.controller; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.junit.Test; |
|||
import org.springframework.http.HttpHeaders; |
|||
import org.springframework.http.HttpMethod; |
|||
import org.springframework.http.MediaType; |
|||
import org.springframework.mock.web.MockMultipartFile; |
|||
import org.springframework.test.web.servlet.MvcResult; |
|||
import org.springframework.test.web.servlet.ResultActions; |
|||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
|||
import org.thingsboard.ai.common.channel.ChannelProtocol; |
|||
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
|||
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
|||
import org.thingsboard.ai.common.channel.SolutionChatRequest; |
|||
import org.thingsboard.ai.common.data.solution.SolutionStep; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.service.ai.transport.TbAiTurnContext; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.util.Base64; |
|||
import java.util.List; |
|||
import java.util.UUID; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.hamcrest.Matchers.equalTo; |
|||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; |
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
|||
|
|||
@DaoSqlTest |
|||
public class AiResourceControllerTest extends AbstractAiControllerTest { |
|||
|
|||
private static final byte[] PNG = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="); |
|||
|
|||
@Test |
|||
public void shouldForwardTheFileBase64Encoded_whenUploadingAResource() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
UUID resourceId = UUID.randomUUID(); |
|||
ObjectNode info = resourceInfo(resourceId, "chart.png", "image/png", PNG.length); |
|||
var request = new ResourceUploadRequest("chart.png", "image/png", Base64.getEncoder().encodeToString(PNG)); |
|||
givenOperation(ChannelProtocol.RESOURCE_UPLOAD, request, success(info)); |
|||
|
|||
// WHEN
|
|||
JsonNode result = readResponse(upload("chart.png", "image/png", PNG).andExpect(status().isCreated()), JsonNode.class); |
|||
|
|||
// THEN
|
|||
assertThat(result).isEqualTo(info); |
|||
TbAiTurnContext context = verifyOperation(ChannelProtocol.RESOURCE_UPLOAD, request); |
|||
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider()); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldRejectAFileOverTheUploadLimit_withoutCallingTheAiService() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
|
|||
// WHEN
|
|||
upload("huge.png", "image/png", new byte[7 * 1024 * 1024 + 1]) |
|||
.andExpect(status().isBadRequest()) |
|||
.andExpect(statusReason(equalTo("The file is too large: huge.png"))); |
|||
|
|||
// THEN
|
|||
verifyNoAiCalls(); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldServeTheFileWithItsTypeAndName_whenDownloadingAResource() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
UUID resourceId = UUID.randomUUID(); |
|||
ObjectNode content = JacksonUtil.newObjectNode() |
|||
.put("name", "chart.png") |
|||
.put("mediaType", "image/png") |
|||
.put("data", Base64.getEncoder().encodeToString(PNG)); |
|||
givenOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId), success(content)); |
|||
|
|||
// WHEN
|
|||
MvcResult result = doGet("/api/ai/resources/" + resourceId).andExpect(status().isOk()).andReturn(); |
|||
|
|||
// THEN
|
|||
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(PNG); |
|||
assertThat(result.getResponse().getContentType()).isEqualTo("image/png"); |
|||
assertThat(result.getResponse().getHeader(HttpHeaders.CONTENT_DISPOSITION)).isEqualTo("attachment; filename=\"chart.png\""); |
|||
assertThat(result.getResponse().getHeader("X-Content-Type-Options")).isEqualTo("nosniff"); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldDeleteAnUnsentResource() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
UUID resourceId = UUID.randomUUID(); |
|||
givenOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId), success()); |
|||
|
|||
// WHEN
|
|||
doDelete("/api/ai/resources/" + resourceId).andExpect(status().isNoContent()); |
|||
|
|||
// THEN
|
|||
verifyOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldReturnTheAcceptedFiles_whenGettingTheConfig() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
JsonNode limits = JacksonUtil.toJsonNode(""" |
|||
{"maxSize": 5242880, "maxPerMessage": 5, "mediaTypes": ["image/png"], "extensions": [".png"]} |
|||
"""); |
|||
givenOperation(ChannelProtocol.RESOURCE_CONFIG, null, success(limits)); |
|||
|
|||
// WHEN
|
|||
JsonNode result = doGet("/api/ai/resources/config", JsonNode.class); |
|||
|
|||
// THEN
|
|||
assertThat(result).isEqualTo(limits); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldSendTheAttachedResources_whenSendingASolutionMessage() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
UUID solutionId = UUID.randomUUID(); |
|||
UUID resourceId = UUID.randomUUID(); |
|||
var request = new SolutionChatRequest(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, "Like this", List.of(resourceId)); |
|||
ObjectNode solution = JacksonUtil.newObjectNode().put("id", solutionId.toString()); |
|||
givenOperation(ChannelProtocol.SOLUTION_CHAT, request, success(solution)); |
|||
|
|||
// WHEN
|
|||
JsonNode result = readResponse(solutionMessage(solutionId, SolutionStep.DASHBOARDS_CONFIGURATION, """ |
|||
{"message": "Like this", "resources": ["%s"]} |
|||
""".formatted(resourceId)).andExpect(status().isOk()), JsonNode.class); |
|||
|
|||
// THEN
|
|||
assertThat(result).isEqualTo(solution); |
|||
verifyOperation(ChannelProtocol.SOLUTION_CHAT, request); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldRejectASolutionMessage_whenItHasNeitherTextNorFiles() throws Exception { |
|||
// GIVEN
|
|||
loginTenantAdmin(); |
|||
|
|||
// WHEN
|
|||
solutionMessage(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, """ |
|||
{"message": " ", "resources": []} |
|||
""") |
|||
.andExpect(status().isBadRequest()) |
|||
.andExpect(statusReason(equalTo("Message cannot be blank"))); |
|||
|
|||
// THEN
|
|||
verifyNoAiCalls(); |
|||
} |
|||
|
|||
@Test |
|||
public void shouldReturnForbiddenAndNotCallClient_whenCustomerUserUploads() throws Exception { |
|||
// GIVEN
|
|||
loginCustomerUser(); |
|||
|
|||
// WHEN
|
|||
upload("chart.png", "image/png", PNG) |
|||
.andExpect(status().isForbidden()) |
|||
.andExpect(statusReason(equalTo(msgErrorPermission))); |
|||
|
|||
// THEN
|
|||
verifyNoAiCalls(); |
|||
} |
|||
|
|||
private ResultActions upload(String name, String mediaType, byte[] content) throws Exception { |
|||
var request = MockMvcRequestBuilders.multipart(HttpMethod.POST, "/api/ai/resources") |
|||
.file(new MockMultipartFile("file", name, mediaType, content)); |
|||
setJwtToken(request); |
|||
return mockMvc.perform(request); |
|||
} |
|||
|
|||
private ResultActions solutionMessage(UUID solutionId, SolutionStep step, String body) throws Exception { |
|||
var request = post("/api/ai/solution/" + solutionId + "/" + step + "/messages") |
|||
.contentType(MediaType.APPLICATION_JSON) |
|||
.content(body.getBytes(StandardCharsets.UTF_8)); |
|||
setJwtToken(request); |
|||
return mockMvc.perform(request); |
|||
} |
|||
|
|||
private static ObjectNode resourceInfo(UUID id, String name, String mediaType, int size) { |
|||
return JacksonUtil.newObjectNode() |
|||
.put("id", id.toString()) |
|||
.put("name", name) |
|||
.put("mediaType", mediaType) |
|||
.put("size", size); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,96 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { Injectable } from '@angular/core'; |
|||
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http'; |
|||
import { defaultHttpOptions, defaultHttpUploadOptions } from '@core/http/http-utils'; |
|||
import { Observable, of } from 'rxjs'; |
|||
import { catchError, filter, map, shareReplay, tap } from 'rxjs/operators'; |
|||
import { AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; |
|||
|
|||
export type AiResourceUploadEvent = |
|||
{ type: 'progress'; progress: number } | |
|||
{ type: 'done'; resource: AiResourceInfo }; |
|||
|
|||
@Injectable({ |
|||
providedIn: 'root' |
|||
}) |
|||
export class AiResourceService { |
|||
|
|||
private config$: Observable<AiResourceConfig | null>; |
|||
|
|||
private readonly urls = new Map<string, Observable<string>>(); |
|||
|
|||
constructor(private http: HttpClient) { |
|||
} |
|||
|
|||
getConfig(): Observable<AiResourceConfig | null> { |
|||
if (!this.config$) { |
|||
this.config$ = this.http.get<AiResourceConfig>('/api/ai/resources/config', defaultHttpOptions(true, true)).pipe( |
|||
catchError(() => { |
|||
this.config$ = null; |
|||
return of(null); |
|||
}), |
|||
shareReplay(1) |
|||
); |
|||
} |
|||
return this.config$; |
|||
} |
|||
|
|||
upload(file: File): Observable<AiResourceUploadEvent> { |
|||
const formData = new FormData(); |
|||
formData.append('file', file, file.name); |
|||
return this.http.post<AiResourceInfo>('/api/ai/resources', formData, { |
|||
...defaultHttpUploadOptions(true, true), |
|||
observe: 'events', |
|||
reportProgress: true |
|||
}).pipe( |
|||
filter((event: HttpEvent<AiResourceInfo>) => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response), |
|||
map((event: HttpEvent<AiResourceInfo>): AiResourceUploadEvent => { |
|||
if (event.type === HttpEventType.UploadProgress) { |
|||
return {type: 'progress', progress: event.total ? Math.round(100 * event.loaded / event.total) : 0}; |
|||
} |
|||
return {type: 'done', resource: (event as any).body as AiResourceInfo}; |
|||
}) |
|||
); |
|||
} |
|||
|
|||
delete(resourceId: string): Observable<void> { |
|||
this.urls.delete(resourceId); |
|||
return this.http.delete<void>(`/api/ai/resources/${resourceId}`, defaultHttpOptions(true, true)); |
|||
} |
|||
|
|||
rememberUrl(resourceId: string, url: string): void { |
|||
this.urls.set(resourceId, of(url)); |
|||
} |
|||
|
|||
getUrl(resourceId: string): Observable<string> { |
|||
let url$ = this.urls.get(resourceId); |
|||
if (!url$) { |
|||
url$ = this.http.get(`/api/ai/resources/${resourceId}`, {...defaultHttpOptions(true, true), responseType: 'blob'}).pipe( |
|||
map(blob => URL.createObjectURL(blob)), |
|||
catchError(error => { |
|||
this.urls.delete(resourceId); |
|||
throw error; |
|||
}), |
|||
shareReplay(1) |
|||
); |
|||
this.urls.set(resourceId, url$); |
|||
} |
|||
return url$; |
|||
} |
|||
|
|||
download(resource: AiResourceInfo): Observable<void> { |
|||
return this.getUrl(resource.id).pipe( |
|||
tap(url => { |
|||
const link = document.createElement('a'); |
|||
link.href = url; |
|||
link.download = resource.name; |
|||
document.body.appendChild(link); |
|||
link.click(); |
|||
link.remove(); |
|||
}), |
|||
map(() => undefined) |
|||
); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<mat-toolbar class="flex items-center gap-2"> |
|||
<h2 class="preview-title">{{ data.item.name }}</h2> |
|||
<span class="flex-1"></span> |
|||
@if (data.item.resource) { |
|||
<button mat-icon-button type="button" (click)="download()" |
|||
[matTooltip]="'action.download' | translate" matTooltipPosition="above"> |
|||
<mat-icon>download</mat-icon> |
|||
</button> |
|||
} |
|||
<button mat-icon-button type="button" (click)="close()" |
|||
[matTooltip]="'action.close' | translate" matTooltipPosition="above"> |
|||
<mat-icon>close</mat-icon> |
|||
</button> |
|||
</mat-toolbar> |
|||
<div mat-dialog-content class="preview-content"> |
|||
@if (data.item.url$ | async; as url) { |
|||
<img [src]="url" [alt]="data.item.name"> |
|||
} @else { |
|||
<mat-progress-spinner diameter="40" mode="indeterminate"></mat-progress-spinner> |
|||
} |
|||
</div> |
|||
@ -0,0 +1,32 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
:host { |
|||
display: flex; |
|||
flex-direction: column; |
|||
min-width: min(360px, 90vw); |
|||
max-height: 90vh; |
|||
|
|||
.preview-title { |
|||
margin: 0; |
|||
font-size: 16px; |
|||
overflow: hidden; |
|||
white-space: nowrap; |
|||
text-overflow: ellipsis; |
|||
} |
|||
|
|||
.preview-content { |
|||
display: flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
padding: 0 16px 16px; |
|||
max-height: calc(90vh - 64px); |
|||
overflow: auto; |
|||
|
|||
img { |
|||
max-width: 100%; |
|||
max-height: calc(90vh - 96px); |
|||
object-fit: contain; |
|||
border-radius: 8px; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,35 @@ |
|||
// 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 { AiResourceService } from '@core/http/ai-resource.service'; |
|||
import { AiAttachmentItem } from '@home/components/ai/ai-attachment.models'; |
|||
|
|||
export interface AiAttachmentPreviewDialogData { |
|||
item: AiAttachmentItem; |
|||
} |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-attachment-preview-dialog', |
|||
templateUrl: './ai-attachment-preview-dialog.component.html', |
|||
styleUrls: ['./ai-attachment-preview-dialog.component.scss'], |
|||
standalone: false |
|||
}) |
|||
export class AiAttachmentPreviewDialogComponent { |
|||
|
|||
constructor(@Inject(MAT_DIALOG_DATA) public data: AiAttachmentPreviewDialogData, |
|||
private dialogRef: MatDialogRef<AiAttachmentPreviewDialogComponent>, |
|||
private aiResourceService: AiResourceService) { |
|||
} |
|||
|
|||
download(): void { |
|||
if (this.data.item.resource) { |
|||
this.aiResourceService.download(this.data.item.resource).subscribe({error: () => {}}); |
|||
} |
|||
} |
|||
|
|||
close(): void { |
|||
this.dialogRef.close(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,112 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { Observable } from 'rxjs'; |
|||
import { AiResourceInfo } from '@shared/models/ai-chat.models'; |
|||
|
|||
export interface AiAttachmentItem { |
|||
key: string; |
|||
name: string; |
|||
mediaType: string; |
|||
size: number; |
|||
image: boolean; |
|||
url$?: Observable<string>; |
|||
resource?: AiResourceInfo; |
|||
status?: 'uploading' | 'ready' | 'error'; |
|||
progress?: number; |
|||
} |
|||
|
|||
const MAX_IMAGE_SIDE = 2560; |
|||
const RESIZABLE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']; |
|||
|
|||
export const aiAttachmentIcon = (mediaType: string, name: string): string => { |
|||
const extension = name.split('.').pop()?.toLowerCase(); |
|||
if (mediaType === 'application/pdf' || extension === 'pdf') { |
|||
return 'picture_as_pdf'; |
|||
} |
|||
if (extension === 'xlsx' || extension === 'csv') { |
|||
return 'table_chart'; |
|||
} |
|||
if (extension === 'pptx') { |
|||
return 'slideshow'; |
|||
} |
|||
if (['json', 'xml', 'yaml', 'yml', 'html', 'htm'].includes(extension)) { |
|||
return 'code'; |
|||
} |
|||
return 'description'; |
|||
}; |
|||
|
|||
export const aiAttachmentExtension = (name: string): string => { |
|||
const dot = name.lastIndexOf('.'); |
|||
return dot > 0 ? name.substring(dot + 1).toUpperCase() : ''; |
|||
}; |
|||
|
|||
export const isAiAttachmentAccepted = (file: File, extensions: string[]): boolean => { |
|||
const name = file.name.toLowerCase(); |
|||
return extensions.some(extension => name.endsWith(extension.toLowerCase())); |
|||
}; |
|||
|
|||
export const namePastedImage = (file: File): File => { |
|||
if (!RESIZABLE_IMAGE_TYPES.includes(file.type) || (file.name && file.name !== 'image.png')) { |
|||
return file; |
|||
} |
|||
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').substring(0, 15); |
|||
const extension = file.type === 'image/jpeg' ? 'jpg' : file.type.split('/')[1]; |
|||
return new File([file], `screenshot-${stamp}.${extension}`, {type: file.type, lastModified: file.lastModified}); |
|||
}; |
|||
|
|||
const loadImage = (file: File): Promise<HTMLImageElement> => new Promise((resolve, reject) => { |
|||
const url = URL.createObjectURL(file); |
|||
const image = new Image(); |
|||
image.onload = () => { |
|||
URL.revokeObjectURL(url); |
|||
resolve(image); |
|||
}; |
|||
image.onerror = () => { |
|||
URL.revokeObjectURL(url); |
|||
reject(new Error('Image could not be decoded')); |
|||
}; |
|||
image.src = url; |
|||
}); |
|||
|
|||
const encode = (canvas: HTMLCanvasElement, type: string, quality?: number): Promise<Blob> => new Promise((resolve, reject) => |
|||
canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Image could not be encoded')), type, quality)); |
|||
|
|||
export const fitAiImage = async (file: File, maxSize: number): Promise<File> => { |
|||
if (!RESIZABLE_IMAGE_TYPES.includes(file.type)) { |
|||
return file; |
|||
} |
|||
let image: HTMLImageElement; |
|||
try { |
|||
image = await loadImage(file); |
|||
} catch { |
|||
return file; |
|||
} |
|||
const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(image.naturalWidth, image.naturalHeight)); |
|||
if (scale === 1 && file.size <= maxSize) { |
|||
return file; |
|||
} |
|||
const canvas = document.createElement('canvas'); |
|||
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale)); |
|||
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale)); |
|||
const context = canvas.getContext('2d'); |
|||
if (file.type === 'image/jpeg') { |
|||
context.fillStyle = '#fff'; |
|||
context.fillRect(0, 0, canvas.width, canvas.height); |
|||
} |
|||
context.drawImage(image, 0, 0, canvas.width, canvas.height); |
|||
let blob = await encode(canvas, file.type, 0.92); |
|||
let type = file.type; |
|||
if (blob.size > maxSize) { |
|||
context.globalCompositeOperation = 'destination-over'; |
|||
context.fillStyle = '#fff'; |
|||
context.fillRect(0, 0, canvas.width, canvas.height); |
|||
blob = await encode(canvas, 'image/jpeg', 0.85); |
|||
type = 'image/jpeg'; |
|||
} |
|||
if (blob.size >= file.size && scale === 1) { |
|||
return file; |
|||
} |
|||
const base = file.name.replace(/\.[^.]+$/, ''); |
|||
const name = type === file.type ? file.name : `${base}.jpg`; |
|||
return new File([blob], name, {type, lastModified: file.lastModified}); |
|||
}; |
|||
@ -0,0 +1,48 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<div class="attachments"> |
|||
@for (item of shown; track item.key) { |
|||
<div class="attachment" |
|||
[class.image]="item.image" |
|||
[class.file]="!item.image" |
|||
[class.uploading]="item.status === 'uploading'" |
|||
[class.failed]="item.status === 'error'" |
|||
[class.clickable]="item.status !== 'uploading' && item.status !== 'error'" |
|||
[matTooltip]="item.status === 'error' ? ('ai-assistant.attachment-failed' | translate) : item.name" |
|||
matTooltipPosition="above" |
|||
(click)="open(item)"> |
|||
@if (item.image) { |
|||
@if (item.url$ | async; as url) { |
|||
<img [src]="url" [alt]="item.name"> |
|||
} @else { |
|||
<mat-icon class="placeholder">image</mat-icon> |
|||
} |
|||
} @else { |
|||
<div class="file-icon"><mat-icon>{{ icon(item.mediaType, item.name) }}</mat-icon></div> |
|||
<div class="file-meta"> |
|||
<span class="file-name">{{ item.name }}</span> |
|||
<span class="file-info">{{ extension(item.name) }}@if (extension(item.name)) { · }{{ item.size | fileSize }}</span> |
|||
</div> |
|||
} |
|||
@if (item.status === 'uploading') { |
|||
<div class="state"> |
|||
<mat-progress-spinner diameter="24" strokeWidth="3" |
|||
[mode]="item.progress ? 'determinate' : 'indeterminate'" |
|||
[value]="item.progress"></mat-progress-spinner> |
|||
</div> |
|||
} @else if (item.status === 'error') { |
|||
<div class="state"><mat-icon class="error-icon">error_outline</mat-icon></div> |
|||
} |
|||
@if (removable) { |
|||
<button type="button" class="remove" [attr.aria-label]="'ai-assistant.remove-attachment' | translate" |
|||
(click)="remove($event, item)"> |
|||
<mat-icon>close</mat-icon> |
|||
</button> |
|||
} |
|||
</div> |
|||
} |
|||
</div> |
|||
@ -0,0 +1,155 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
:host { |
|||
display: block; |
|||
max-width: 100%; |
|||
|
|||
.attachments { |
|||
display: flex; |
|||
flex-wrap: wrap; |
|||
gap: 8px; |
|||
justify-content: inherit; |
|||
} |
|||
|
|||
.attachment { |
|||
position: relative; |
|||
display: flex; |
|||
align-items: center; |
|||
border-radius: 10px; |
|||
border: 1px solid rgba(0, 0, 0, 0.12); |
|||
background: #fff; |
|||
overflow: hidden; |
|||
flex: none; |
|||
|
|||
&.clickable { |
|||
cursor: pointer; |
|||
|
|||
&:hover { |
|||
border-color: var(--tb-primary-500); |
|||
} |
|||
} |
|||
|
|||
&.image { |
|||
width: 64px; |
|||
height: 64px; |
|||
justify-content: center; |
|||
background: rgba(0, 0, 0, 0.04); |
|||
|
|||
img { |
|||
width: 100%; |
|||
height: 100%; |
|||
object-fit: cover; |
|||
} |
|||
|
|||
.placeholder { |
|||
color: rgba(0, 0, 0, 0.38); |
|||
} |
|||
} |
|||
|
|||
&.file { |
|||
gap: 8px; |
|||
height: 48px; |
|||
max-width: 220px; |
|||
padding: 0 28px 0 8px; |
|||
|
|||
.file-icon { |
|||
display: flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
flex: none; |
|||
width: 32px; |
|||
height: 32px; |
|||
border-radius: 8px; |
|||
color: var(--tb-primary-500); |
|||
position: relative; |
|||
|
|||
&:before { |
|||
content: ""; |
|||
position: absolute; |
|||
inset: 0; |
|||
border-radius: inherit; |
|||
background: var(--tb-primary-500); |
|||
opacity: 0.1; |
|||
} |
|||
|
|||
mat-icon { |
|||
font-size: 20px; |
|||
width: 20px; |
|||
height: 20px; |
|||
} |
|||
} |
|||
|
|||
.file-meta { |
|||
display: flex; |
|||
flex-direction: column; |
|||
min-width: 0; |
|||
line-height: 16px; |
|||
|
|||
.file-name { |
|||
font-size: 13px; |
|||
color: rgba(0, 0, 0, 0.87); |
|||
white-space: nowrap; |
|||
overflow: hidden; |
|||
text-overflow: ellipsis; |
|||
} |
|||
|
|||
.file-info { |
|||
font-size: 11px; |
|||
color: rgba(0, 0, 0, 0.54); |
|||
white-space: nowrap; |
|||
} |
|||
} |
|||
} |
|||
|
|||
&.failed { |
|||
border-color: rgba(209, 39, 48, 0.6); |
|||
} |
|||
|
|||
.state { |
|||
position: absolute; |
|||
inset: 0; |
|||
display: flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
background: rgba(255, 255, 255, 0.7); |
|||
|
|||
.error-icon { |
|||
color: rgb(209, 39, 48); |
|||
} |
|||
} |
|||
|
|||
.remove { |
|||
position: absolute; |
|||
top: 4px; |
|||
right: 4px; |
|||
width: 20px; |
|||
height: 20px; |
|||
padding: 0; |
|||
border: none; |
|||
border-radius: 50%; |
|||
display: flex; |
|||
align-items: center; |
|||
justify-content: center; |
|||
cursor: pointer; |
|||
color: #fff; |
|||
background: rgba(0, 0, 0, 0.6); |
|||
opacity: 0.9; |
|||
|
|||
&:hover { |
|||
opacity: 1; |
|||
background: rgba(0, 0, 0, 0.8); |
|||
} |
|||
|
|||
mat-icon { |
|||
font-size: 14px; |
|||
width: 14px; |
|||
height: 14px; |
|||
} |
|||
} |
|||
|
|||
&.file .remove { |
|||
top: 50%; |
|||
transform: translateY(-50%); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,78 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; |
|||
import { MatDialog } from '@angular/material/dialog'; |
|||
import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models'; |
|||
import { AiResourceService } from '@core/http/ai-resource.service'; |
|||
import { |
|||
aiAttachmentExtension, |
|||
aiAttachmentIcon, |
|||
AiAttachmentItem |
|||
} from '@home/components/ai/ai-attachment.models'; |
|||
import { |
|||
AiAttachmentPreviewDialogComponent, |
|||
AiAttachmentPreviewDialogData |
|||
} from '@home/components/ai/ai-attachment-preview-dialog.component'; |
|||
|
|||
@Component({ |
|||
selector: 'tb-ai-attachments', |
|||
templateUrl: './ai-attachments.component.html', |
|||
styleUrls: ['./ai-attachments.component.scss'], |
|||
standalone: false |
|||
}) |
|||
export class AiAttachmentsComponent implements OnChanges { |
|||
|
|||
@Input() resources: AiResourceInfo[]; |
|||
|
|||
@Input() items: AiAttachmentItem[]; |
|||
|
|||
@Input() removable = false; |
|||
|
|||
@Output() removed = new EventEmitter<AiAttachmentItem>(); |
|||
|
|||
shown: AiAttachmentItem[] = []; |
|||
|
|||
readonly icon = aiAttachmentIcon; |
|||
|
|||
readonly extension = aiAttachmentExtension; |
|||
|
|||
constructor(private aiResourceService: AiResourceService, |
|||
private dialog: MatDialog) { |
|||
} |
|||
|
|||
ngOnChanges(changes: SimpleChanges): void { |
|||
if (changes.items || changes.resources) { |
|||
this.shown = this.items ?? (this.resources ?? []).map(resource => ({ |
|||
key: resource.id, |
|||
name: resource.name, |
|||
mediaType: resource.mediaType, |
|||
size: resource.size, |
|||
image: isAiImageResource(resource), |
|||
url$: isAiImageResource(resource) ? this.aiResourceService.getUrl(resource.id) : undefined, |
|||
resource, |
|||
status: 'ready' |
|||
})); |
|||
} |
|||
} |
|||
|
|||
open(item: AiAttachmentItem): void { |
|||
if (item.status === 'uploading' || item.status === 'error') { |
|||
return; |
|||
} |
|||
if (item.image && item.url$) { |
|||
this.dialog.open<AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData>(AiAttachmentPreviewDialogComponent, { |
|||
panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], |
|||
maxWidth: '92vw', |
|||
data: {item} |
|||
}); |
|||
} else if (item.resource) { |
|||
this.aiResourceService.download(item.resource).subscribe({error: () => {}}); |
|||
} |
|||
} |
|||
|
|||
remove(event: Event, item: AiAttachmentItem): void { |
|||
event.stopPropagation(); |
|||
this.removed.emit(item); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue