|
| 1 | +package com.DesktopApplicationClientJava.Api.handlers; |
| 2 | + |
| 3 | +import com.DesktopApplicationClientJava.Api.ApiException; |
| 4 | +import com.DesktopApplicationClientJava.Api.Dto.error.ErrorResponse; |
| 5 | +import com.DesktopApplicationClientJava.Api.Dto.response.FileDto; |
| 6 | +import com.DesktopApplicationClientJava.Api.HttpController; |
| 7 | +import java.io.ByteArrayOutputStream; |
| 8 | +import java.io.IOException; |
| 9 | +import java.io.InputStream; |
| 10 | +import java.net.URI; |
| 11 | +import java.net.URLDecoder; |
| 12 | +import java.net.http.HttpRequest; |
| 13 | +import java.net.http.HttpResponse; |
| 14 | +import java.nio.charset.StandardCharsets; |
| 15 | +import java.nio.file.Files; |
| 16 | +import java.nio.file.Path; |
| 17 | +import java.util.Optional; |
| 18 | +import java.util.UUID; |
| 19 | +import lombok.Setter; |
| 20 | + |
| 21 | +@Setter |
| 22 | +public class FileHandler extends Handler { |
| 23 | + public FileHandler(HttpController httpController) { |
| 24 | + super(httpController); |
| 25 | + } |
| 26 | + |
| 27 | + public FileDto uploadFile(UUID resourceUuid, Path filePath) |
| 28 | + throws IOException, InterruptedException { |
| 29 | + String boundary = "----JavaPksBoundary" + System.currentTimeMillis(); |
| 30 | + byte[] fileBytes = Files.readAllBytes(filePath); |
| 31 | + String filename = filePath.getFileName().toString(); |
| 32 | + String contentType = |
| 33 | + Optional.ofNullable(Files.probeContentType(filePath)).orElse("application/octet-stream"); |
| 34 | + |
| 35 | + ByteArrayOutputStream body = new ByteArrayOutputStream(); |
| 36 | + |
| 37 | + body.write(("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8)); |
| 38 | + body.write( |
| 39 | + ("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n") |
| 40 | + .getBytes(StandardCharsets.UTF_8)); |
| 41 | + body.write(("Content-Type: " + contentType + "\r\n\r\n").getBytes(StandardCharsets.UTF_8)); |
| 42 | + body.write(fileBytes); |
| 43 | + body.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8)); |
| 44 | + |
| 45 | + HttpRequest httpRequest = |
| 46 | + HttpRequest.newBuilder() |
| 47 | + .uri(URI.create(httpController.baseUrl + "/api/v1/resource/" + resourceUuid + "/file")) |
| 48 | + .header("Content-Type", "multipart/form-data; boundary=" + boundary) |
| 49 | + .header("Authorization", "Bearer " + httpController.accessToken) |
| 50 | + .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())) |
| 51 | + .build(); |
| 52 | + |
| 53 | + HttpResponse<String> response = httpController.send(httpRequest); |
| 54 | + httpController.checkError(response); |
| 55 | + return httpController.parseResponse(response, FileDto.class); |
| 56 | + } |
| 57 | + |
| 58 | + public Path downloadFile(UUID resourceUuid, UUID fileUuid, Path destinationDir) |
| 59 | + throws IOException, InterruptedException { |
| 60 | + |
| 61 | + HttpRequest httpRequest = |
| 62 | + HttpRequest.newBuilder() |
| 63 | + .uri( |
| 64 | + URI.create( |
| 65 | + httpController.baseUrl |
| 66 | + + "/api/v1/resource/" |
| 67 | + + resourceUuid |
| 68 | + + "/file/" |
| 69 | + + fileUuid)) |
| 70 | + .header("Authorization", "Bearer " + httpController.accessToken) |
| 71 | + .GET() |
| 72 | + .build(); |
| 73 | + |
| 74 | + HttpResponse<InputStream> response = |
| 75 | + httpController.executeWithRetry(httpRequest, HttpResponse.BodyHandlers.ofInputStream()); |
| 76 | + |
| 77 | + if (response.statusCode() >= 400) { |
| 78 | + String body = new String(response.body().readAllBytes(), StandardCharsets.UTF_8); |
| 79 | + response.body().close(); |
| 80 | + try { |
| 81 | + ErrorResponse error = httpController.objectMapper.readValue(body, ErrorResponse.class); |
| 82 | + throw new ApiException(error); |
| 83 | + } catch (ApiException e) { |
| 84 | + throw e; |
| 85 | + } catch (Exception parseFail) { |
| 86 | + throw new ApiException(new ErrorResponse("Ошибка сервера: " + body, response.statusCode())); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + String filename = |
| 91 | + parseFilename(response.headers().firstValue("Content-Disposition").orElse(null)); |
| 92 | + if (filename == null || filename.isBlank()) { |
| 93 | + filename = fileUuid.toString(); |
| 94 | + } |
| 95 | + |
| 96 | + Files.createDirectories(destinationDir); |
| 97 | + Path target = destinationDir.resolve(filename); |
| 98 | + |
| 99 | + try (InputStream in = response.body()) { |
| 100 | + Files.copy(in, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING); |
| 101 | + } |
| 102 | + return target; |
| 103 | + } |
| 104 | + |
| 105 | + public void deleteFile(UUID resourceUuid, UUID fileUuid) |
| 106 | + throws IOException, InterruptedException { |
| 107 | + HttpRequest httpRequest = |
| 108 | + HttpRequest.newBuilder() |
| 109 | + .uri( |
| 110 | + URI.create( |
| 111 | + httpController.baseUrl |
| 112 | + + "/api/v1/resource/" |
| 113 | + + resourceUuid |
| 114 | + + "/file/" |
| 115 | + + fileUuid)) |
| 116 | + .header("Authorization", "Bearer " + httpController.accessToken) |
| 117 | + .DELETE() |
| 118 | + .build(); |
| 119 | + HttpResponse<String> response = httpController.send(httpRequest); |
| 120 | + httpController.checkError(response); |
| 121 | + } |
| 122 | + |
| 123 | + private static String parseFilename(String cd) { |
| 124 | + if (cd == null) return null; |
| 125 | + |
| 126 | + int starIdx = cd.indexOf("filename*="); |
| 127 | + if (starIdx >= 0) { |
| 128 | + String val = cd.substring(starIdx + "filename*=".length()).trim(); |
| 129 | + int semi = val.indexOf(';'); |
| 130 | + if (semi >= 0) val = val.substring(0, semi).trim(); |
| 131 | + int encIdx = val.indexOf("''"); |
| 132 | + if (encIdx >= 0) { |
| 133 | + String encoded = val.substring(encIdx + 2); |
| 134 | + return URLDecoder.decode(encoded, StandardCharsets.UTF_8); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + int idx = cd.indexOf("filename="); |
| 139 | + if (idx >= 0) { |
| 140 | + String val = cd.substring(idx + "filename=".length()).trim(); |
| 141 | + if (val.startsWith("\"")) { |
| 142 | + int end = val.indexOf('"', 1); |
| 143 | + if (end > 0) return val.substring(1, end); |
| 144 | + } else { |
| 145 | + int semi = val.indexOf(';'); |
| 146 | + if (semi >= 0) val = val.substring(0, semi); |
| 147 | + return val.trim(); |
| 148 | + } |
| 149 | + } |
| 150 | + return null; |
| 151 | + } |
| 152 | +} |
0 commit comments