2025-12-10 19:12:54 +07:00
|
|
|
package ru.soune.nocopy.controller;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
import com.vrt.NoCopyFileService;
|
|
|
|
|
import com.vrt.fileprotection.FileProtector;
|
|
|
|
|
import com.vrt.fileprotection.NoCopyCheckResult;
|
|
|
|
|
import com.vrt.fileprotection.audio.AudioCheckResult;
|
|
|
|
|
import com.vrt.fileprotection.documents.DocumentCheckResult;
|
2025-12-10 02:37:31 +07:00
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
2026-01-30 17:51:59 +07:00
|
|
|
import org.springframework.core.io.FileSystemResource;
|
2026-01-16 14:30:45 +07:00
|
|
|
import org.springframework.data.domain.Page;
|
|
|
|
|
import org.springframework.data.domain.Pageable;
|
|
|
|
|
import org.springframework.data.web.PageableDefault;
|
2025-12-18 14:40:27 +07:00
|
|
|
import org.springframework.http.HttpHeaders;
|
|
|
|
|
import org.springframework.http.MediaType;
|
2025-12-10 02:37:31 +07:00
|
|
|
import org.springframework.http.ResponseEntity;
|
|
|
|
|
import org.springframework.validation.BindingResult;
|
|
|
|
|
import org.springframework.validation.FieldError;
|
|
|
|
|
import org.springframework.web.bind.annotation.*;
|
2025-12-17 22:31:30 +07:00
|
|
|
import org.springframework.web.multipart.MultipartFile;
|
2025-12-10 19:12:54 +07:00
|
|
|
import ru.soune.nocopy.dto.BaseRequest;
|
|
|
|
|
import ru.soune.nocopy.dto.BaseResponse;
|
|
|
|
|
import ru.soune.nocopy.dto.MessageCode;
|
2026-01-24 11:32:02 +07:00
|
|
|
import ru.soune.nocopy.dto.file.*;
|
2026-01-20 03:47:51 +07:00
|
|
|
import ru.soune.nocopy.dto.register.RegAnswer;
|
2026-02-24 14:19:15 +07:00
|
|
|
import ru.soune.nocopy.entity.company.Company;
|
2026-01-24 11:32:02 +07:00
|
|
|
import ru.soune.nocopy.entity.file.FileEntity;
|
2025-12-30 02:19:07 +07:00
|
|
|
import ru.soune.nocopy.entity.file.FileStatus;
|
2025-12-17 22:31:30 +07:00
|
|
|
import ru.soune.nocopy.entity.file.UploadStatus;
|
2026-02-05 19:02:17 +07:00
|
|
|
import ru.soune.nocopy.entity.user.AuthToken;
|
2026-02-24 14:19:15 +07:00
|
|
|
import ru.soune.nocopy.entity.user.User;
|
2025-12-30 02:19:07 +07:00
|
|
|
import ru.soune.nocopy.exception.*;
|
2025-12-18 01:13:19 +07:00
|
|
|
import ru.soune.nocopy.handler.*;
|
2026-02-05 19:02:17 +07:00
|
|
|
import ru.soune.nocopy.repository.AuthTokenRepository;
|
2026-01-15 20:41:35 +07:00
|
|
|
import ru.soune.nocopy.repository.FileEntityRepository;
|
2026-02-24 14:19:15 +07:00
|
|
|
import ru.soune.nocopy.repository.UserRepository;
|
2026-01-24 11:32:02 +07:00
|
|
|
import ru.soune.nocopy.service.FileSimilarityService;
|
2026-02-05 18:55:54 +07:00
|
|
|
import ru.soune.nocopy.service.file.ProtectionsLimitService;
|
2026-01-21 12:21:14 +07:00
|
|
|
import ru.soune.nocopy.service.register.AuthService;
|
2025-12-18 14:40:27 +07:00
|
|
|
import ru.soune.nocopy.service.file.FileEntityService;
|
2025-12-17 22:31:30 +07:00
|
|
|
import ru.soune.nocopy.service.file.FileUploadService;
|
2026-01-22 19:55:09 +07:00
|
|
|
import ru.soune.nocopy.util.FileUtil;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
import java.io.File;
|
2025-12-18 14:40:27 +07:00
|
|
|
import java.io.IOException;
|
|
|
|
|
import java.nio.file.Files;
|
|
|
|
|
import java.nio.file.Path;
|
|
|
|
|
import java.nio.file.Paths;
|
2026-02-17 13:57:38 +07:00
|
|
|
import java.util.*;
|
2025-12-10 02:37:31 +07:00
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
|
|
@Slf4j
|
|
|
|
|
@RestController
|
|
|
|
|
@RequestMapping("/api")
|
|
|
|
|
@RequiredArgsConstructor
|
|
|
|
|
public class ApiController {
|
2025-12-17 22:31:30 +07:00
|
|
|
private final FileUploadService fileUploadService;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-18 01:13:19 +07:00
|
|
|
private final Map<Integer, RequestHandler> handlers;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-18 14:40:27 +07:00
|
|
|
private final FileEntityService fileEntityService;
|
|
|
|
|
|
2026-01-05 16:26:46 +07:00
|
|
|
private final AuthService authService;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2026-01-13 22:40:52 +07:00
|
|
|
private final FileSimilarityService fileSimilarityService;
|
|
|
|
|
|
2026-01-15 20:41:35 +07:00
|
|
|
private final FileEntityRepository fileEntityRepository;
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
private final FileUtil fileUtil;
|
|
|
|
|
|
2026-02-05 18:55:54 +07:00
|
|
|
private final ProtectionsLimitService protectionsLimitService;
|
|
|
|
|
|
2026-02-05 19:02:17 +07:00
|
|
|
private final AuthTokenRepository authTokenRepository;
|
|
|
|
|
|
2026-02-24 14:19:15 +07:00
|
|
|
private final UserRepository userRepository;
|
|
|
|
|
|
2025-12-10 02:37:31 +07:00
|
|
|
@PostMapping("/v{version}/data")
|
2025-12-10 12:17:08 +07:00
|
|
|
public ResponseEntity<?> handlePostRequest(@RequestBody BaseRequest request,
|
|
|
|
|
@PathVariable("version") int version) {
|
2025-12-10 02:37:31 +07:00
|
|
|
Integer msgId = request.getMsgId();
|
2025-12-10 17:17:48 +07:00
|
|
|
BaseResponse response;
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-10 12:17:08 +07:00
|
|
|
try {
|
|
|
|
|
RequestHandler handler = handlers.get(msgId);
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-10 12:17:08 +07:00
|
|
|
if (handler == null) {
|
2025-12-10 17:17:48 +07:00
|
|
|
response = new BaseResponse(msgId,
|
2025-12-10 12:17:08 +07:00
|
|
|
MessageCode.MSG_ID_NOT_FOUND.getCode(),
|
2025-12-10 15:27:14 +07:00
|
|
|
MessageCode.MSG_ID_NOT_FOUND.getDescription(),
|
|
|
|
|
new HashMap<>());
|
2025-12-10 17:17:48 +07:00
|
|
|
} else {
|
|
|
|
|
response = handler.handle(request);
|
2025-12-10 12:17:08 +07:00
|
|
|
}
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-10 12:17:08 +07:00
|
|
|
return ResponseEntity.ok().body(response);
|
|
|
|
|
} catch (ValidationException e) {
|
|
|
|
|
return createValidationErrorResponse(e.getBindingResult(), e.getMsgId());
|
2026-01-21 12:34:40 +07:00
|
|
|
} catch (UserNotFoundException e) {
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(msgId, MessageCode.USER_NOT_FOUND.getCode(),
|
|
|
|
|
MessageCode.USER_NOT_FOUND.getDescription(), new HashMap<>()));
|
2026-01-05 16:26:46 +07:00
|
|
|
} catch (NotFoundAuthToken e) {
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(msgId, MessageCode.AUTH_TOKEN_NOT_FOUND.getCode(),
|
|
|
|
|
MessageCode.AUTH_TOKEN_NOT_FOUND.getDescription(), new HashMap<>()));
|
2025-12-10 12:17:08 +07:00
|
|
|
} catch (NotValidFieldException e) {
|
|
|
|
|
throw e;
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
log.error("Handler execution failed for msgId: {}", msgId, e);
|
2025-12-10 19:25:45 +07:00
|
|
|
|
|
|
|
|
BaseResponse errorResponse = new BaseResponse(msgId,
|
|
|
|
|
MessageCode.INVALID_JSON_BODY.getCode(),
|
|
|
|
|
MessageCode.INVALID_JSON_BODY.getDescription(),
|
|
|
|
|
new HashMap<>());
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(errorResponse);
|
2025-12-10 12:17:08 +07:00
|
|
|
}
|
2025-12-10 02:37:31 +07:00
|
|
|
}
|
|
|
|
|
|
2025-12-17 22:31:30 +07:00
|
|
|
@PostMapping("/v{version}/files/chunk")
|
|
|
|
|
public ResponseEntity<BaseResponse> uploadChunk(
|
|
|
|
|
@PathVariable("version") int version,
|
2025-12-25 13:04:49 +07:00
|
|
|
@RequestParam(value = "upload_id", required = false) String uploadId,
|
|
|
|
|
@RequestParam(value = "chunk_number", required = false) Integer chunkNumber,
|
2026-01-26 21:03:45 +07:00
|
|
|
@RequestParam(value = "chunk", required = false) MultipartFile chunk,
|
2026-01-27 08:09:54 +07:00
|
|
|
@RequestParam(value = "findSimilar", required = false, defaultValue = "0") Integer findSimilar) {
|
2025-12-17 22:31:30 +07:00
|
|
|
try {
|
2025-12-25 13:04:49 +07:00
|
|
|
if (chunk == null || chunk.isEmpty()) {
|
2026-01-15 20:41:35 +07:00
|
|
|
return buildErrorResponse(uploadId, chunkNumber, "Chunk file null or empty");
|
2025-12-25 13:04:49 +07:00
|
|
|
}
|
|
|
|
|
if (uploadId == null || uploadId.isBlank()) {
|
2026-01-15 20:41:35 +07:00
|
|
|
return buildErrorResponse(uploadId, chunkNumber, "Upload ID is required");
|
2025-12-25 13:04:49 +07:00
|
|
|
}
|
|
|
|
|
if (chunkNumber == null || chunkNumber < 0) {
|
2026-01-15 20:41:35 +07:00
|
|
|
return buildErrorResponse(uploadId, chunkNumber, "Valid chunk number is required");
|
2025-12-25 13:04:49 +07:00
|
|
|
}
|
|
|
|
|
|
2026-01-26 21:03:45 +07:00
|
|
|
UploadProgressResponse uploadProgressResponse = fileUploadService.uploadChunk(uploadId, chunkNumber,
|
|
|
|
|
chunk, findSimilar);
|
2025-12-17 22:31:30 +07:00
|
|
|
|
2026-01-26 21:03:45 +07:00
|
|
|
return buildSuccessResponse(uploadId, chunkNumber, chunk,
|
|
|
|
|
fileEntityService.findFileIdByPath(uploadProgressResponse.getFilePath()));
|
2026-01-19 15:49:27 +07:00
|
|
|
} catch (DuplicateImageException e) {
|
2026-01-25 19:59:16 +07:00
|
|
|
Map<String, Object> duplicateData = new HashMap<>();
|
|
|
|
|
duplicateData.put("duplicateFileId", e.duplicateFileId());
|
|
|
|
|
duplicateData.put("userId", e.userId());
|
|
|
|
|
duplicateData.put("message", e.getMessage());
|
|
|
|
|
|
|
|
|
|
if (uploadId != null) {
|
|
|
|
|
duplicateData.put("uploadId", uploadId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20004,
|
|
|
|
|
MessageCode.DUPLICATE_FILE_UPLOAD.getCode(),
|
2026-01-19 15:49:27 +07:00
|
|
|
MessageCode.DUPLICATE_FILE_UPLOAD.getDescription(),
|
2026-01-25 19:59:16 +07:00
|
|
|
duplicateData
|
|
|
|
|
));
|
2026-02-21 21:41:05 +07:00
|
|
|
}catch (FileFormatException e){
|
|
|
|
|
return buildErrorResponse(uploadId, chunkNumber, e.getMessage());
|
2025-12-17 22:31:30 +07:00
|
|
|
} catch (Exception e) {
|
|
|
|
|
log.error("Error uploading chunk", e);
|
2026-01-15 20:41:35 +07:00
|
|
|
return buildErrorResponse(uploadId, chunkNumber, "Failed to upload chunk: " + e.getMessage());
|
2025-12-17 22:31:30 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
private final NoCopyFileService noCopyFileService;
|
|
|
|
|
|
2026-01-27 08:09:54 +07:00
|
|
|
@GetMapping("/v{version}/files/{fileId}/similar")
|
2026-01-16 14:30:45 +07:00
|
|
|
public ResponseEntity<BaseResponse> findSimilarFiles(
|
|
|
|
|
@PathVariable("version") int version,
|
|
|
|
|
@PathVariable String fileId,
|
2026-02-17 13:57:38 +07:00
|
|
|
@RequestParam(value = "auth_token", required = false) String authToken,
|
2026-01-16 14:30:45 +07:00
|
|
|
@RequestParam(required = false) List<String> similarityLevels,
|
2026-02-17 13:57:38 +07:00
|
|
|
@PageableDefault(size = 20, sort = "hammingDistance") Pageable pageable) {
|
2026-01-15 20:41:35 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
try {
|
|
|
|
|
FileEntity fileEntity = fileEntityRepository.findByFileId(fileId);
|
|
|
|
|
if (fileEntity == null) {
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(0, MessageCode.INVALID_FIELD.getCode(),
|
|
|
|
|
MessageCode.INVALID_FIELD.getDescription(), null));
|
|
|
|
|
}
|
2026-01-16 14:30:45 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
BaseResponse response;
|
|
|
|
|
if ("image".equals(fileEntity.getMimeType())) {
|
|
|
|
|
Page<SimilarFileDTO> similarFilesPage = fileSimilarityService.findSimilarFiles(
|
|
|
|
|
fileId, similarityLevels, pageable, authToken);
|
|
|
|
|
response = buildSuccessResponse(similarFilesPage, MessageCode.SIMILAR_FILES_FOUND);
|
|
|
|
|
} else {
|
|
|
|
|
List<SimilarFileDTO> results = processNonImageFile(fileEntity, authToken);
|
|
|
|
|
response = buildSuccessResponse(results, MessageCode.SIMILAR_FILES_FOUND);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok(response);
|
|
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
log.error("Error finding similar files: {}", e.getMessage(), e);
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(0, MessageCode.INVALID_FIELD.getCode(),
|
|
|
|
|
MessageCode.INVALID_FIELD.getDescription(), null));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-27 01:47:50 +07:00
|
|
|
private List<SimilarFileDTO> processNonImageFile(FileEntity fileEntity, String authToken) throws Exception {
|
2026-02-17 13:57:38 +07:00
|
|
|
List<SimilarFileDTO> results = new ArrayList<>();
|
|
|
|
|
|
2026-02-27 01:52:56 +07:00
|
|
|
FileEntity duplicateByHash = fileSimilarityService.findDuplicateByHash(fileEntity.getFilePath(),
|
2026-02-27 01:47:50 +07:00
|
|
|
fileEntity.getMimeType(), fileEntity.getUserId());
|
|
|
|
|
|
|
|
|
|
if (duplicateByHash != null) {
|
|
|
|
|
results.add(fileSimilarityService.buildDTO(duplicateByHash));
|
|
|
|
|
|
|
|
|
|
return results;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-02 13:40:07 +07:00
|
|
|
File file = new File(fileEntity.getProtectedFilePath());
|
2026-02-17 13:57:38 +07:00
|
|
|
FileProtector.Type type = "document".equals(fileEntity.getMimeType()) ?
|
|
|
|
|
FileProtector.Type.DOC : FileProtector.Type.AUDIO;
|
|
|
|
|
|
|
|
|
|
NoCopyCheckResult checkResult = noCopyFileService.checkFile(file, type);
|
|
|
|
|
|
|
|
|
|
switch (checkResult) {
|
|
|
|
|
case DocumentCheckResult.Success success -> {
|
|
|
|
|
FileProtector.FileInfo info = success.getInfo();
|
|
|
|
|
FileEntity entity = fileEntityRepository.findByFileId(info.getId());
|
|
|
|
|
if (entity != null) {
|
|
|
|
|
results.add(fileSimilarityService.buildDTO(entity));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
case AudioCheckResult.Success success -> {
|
|
|
|
|
FileProtector.FileInfo info = success.getInfo();
|
|
|
|
|
FileEntity entity = fileEntityRepository.findByFileId(info.getId());
|
|
|
|
|
if (entity != null) {
|
|
|
|
|
results.add(fileSimilarityService.buildDTO(entity));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
case DocumentCheckResult.Failed failed ->
|
|
|
|
|
log.warn("Document check failed: {}", failed.getMessage());
|
|
|
|
|
case AudioCheckResult.Failed failed ->
|
|
|
|
|
log.warn("Audio check failed: {}", failed.getMessage());
|
|
|
|
|
default -> log.warn("Unexpected result type: {}", checkResult.getClass().getSimpleName());
|
2026-01-15 20:41:35 +07:00
|
|
|
}
|
|
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
return results;
|
|
|
|
|
}
|
2026-01-15 20:41:35 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
private BaseResponse buildSuccessResponse(Page<SimilarFileDTO> page, MessageCode messageCode) {
|
|
|
|
|
Map<String, Object> responseData = new HashMap<>();
|
|
|
|
|
responseData.put("content", page.getContent());
|
|
|
|
|
responseData.put("page", page.getNumber());
|
|
|
|
|
responseData.put("size", page.getSize());
|
|
|
|
|
responseData.put("totalElements", page.getTotalElements());
|
|
|
|
|
responseData.put("totalPages", page.getTotalPages());
|
|
|
|
|
responseData.put("hasNext", page.hasNext());
|
|
|
|
|
responseData.put("hasPrevious", page.hasPrevious());
|
|
|
|
|
|
|
|
|
|
return new BaseResponse(20004, messageCode.getCode(),
|
|
|
|
|
messageCode.getDescription(), responseData);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private BaseResponse buildSuccessResponse(List<SimilarFileDTO> list, MessageCode messageCode) {
|
|
|
|
|
Map<String, Object> responseData = new HashMap<>();
|
|
|
|
|
responseData.put("content", list);
|
|
|
|
|
responseData.put("totalElements", list.size());
|
|
|
|
|
|
|
|
|
|
return new BaseResponse(20004, messageCode.getCode(),
|
|
|
|
|
messageCode.getDescription(), responseData);
|
2026-01-13 22:40:52 +07:00
|
|
|
}
|
|
|
|
|
|
2025-12-17 22:31:30 +07:00
|
|
|
@GetMapping("/v{version}/files/progress/{uploadId}")
|
|
|
|
|
public ResponseEntity<BaseResponse> getUploadProgress(
|
|
|
|
|
@PathVariable("version") int version,
|
|
|
|
|
@PathVariable String uploadId) {
|
|
|
|
|
|
|
|
|
|
log.info("Getting progress for upload session: {}, version: {}", uploadId, version);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
var progress = fileUploadService.getUploadProgress(uploadId);
|
|
|
|
|
|
|
|
|
|
UploadProgress responseBody = UploadProgress.builder()
|
|
|
|
|
.uploadId(progress.getUploadId())
|
|
|
|
|
.fileName(progress.getFileName())
|
|
|
|
|
.totalChunks(progress.getTotalChunks())
|
|
|
|
|
.uploadedChunks(progress.getUploadedChunks())
|
|
|
|
|
.status(progress.getStatus().toString())
|
|
|
|
|
.progressPercentage(progress.getProgressPercentage())
|
|
|
|
|
.filePath(progress.getFilePath())
|
|
|
|
|
.remainingChunks(progress.getTotalChunks() - progress.getUploadedChunks())
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20004, MessageCode.SUCCESS.getCode(), MessageCode.SUCCESS.getDescription(), responseBody));
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
log.error("Error getting progress for upload: {}", uploadId, e);
|
|
|
|
|
|
|
|
|
|
UploadProgress responseBody = UploadProgress.builder()
|
|
|
|
|
.uploadId(uploadId)
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20004, MessageCode.FILE_UPLOAD_ERROR.getCode(),
|
|
|
|
|
"Failed to get upload progress: " + e.getMessage(), responseBody));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@PostMapping("/v{version}/files/{uploadId}/complete")
|
|
|
|
|
public ResponseEntity<BaseResponse> completeUpload(
|
|
|
|
|
@PathVariable("version") int version,
|
|
|
|
|
@PathVariable String uploadId) {
|
|
|
|
|
|
|
|
|
|
log.info("Completing upload session: {}, version: {}", uploadId, version);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
var progress = fileUploadService.getUploadProgress(uploadId);
|
|
|
|
|
|
|
|
|
|
if (progress.getStatus() == UploadStatus.COMPLETED) {
|
|
|
|
|
CompleteUploadResponse responseBody = CompleteUploadResponse.builder()
|
|
|
|
|
.uploadId(progress.getUploadId())
|
|
|
|
|
.status(progress.getStatus().toString())
|
|
|
|
|
.uploadedChunks(progress.getUploadedChunks())
|
|
|
|
|
.totalChunks(progress.getTotalChunks())
|
|
|
|
|
.message("Upload already completed")
|
|
|
|
|
.filePath(progress.getFilePath())
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004, MessageCode.SUCCESS.getCode(),
|
|
|
|
|
"Upload already completed", responseBody));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (progress.getUploadedChunks() < progress.getTotalChunks()) {
|
|
|
|
|
CompleteUploadResponse responseBody = CompleteUploadResponse.builder()
|
|
|
|
|
.uploadId(progress.getUploadId())
|
|
|
|
|
.status(progress.getStatus().toString())
|
|
|
|
|
.uploadedChunks(progress.getUploadedChunks())
|
|
|
|
|
.totalChunks(progress.getTotalChunks())
|
|
|
|
|
.message("Not all chunks uploaded")
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004, MessageCode.INCOMPLETE_UPLOAD.getCode(),
|
|
|
|
|
"Not all chunks uploaded", responseBody));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
CompleteUploadResponse responseBody = CompleteUploadResponse.builder()
|
|
|
|
|
.uploadId(progress.getUploadId())
|
|
|
|
|
.status(progress.getStatus().toString())
|
|
|
|
|
.uploadedChunks(progress.getUploadedChunks())
|
|
|
|
|
.totalChunks(progress.getTotalChunks())
|
|
|
|
|
.message("File assembly in progress")
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004, MessageCode.SUCCESS.getCode(),
|
|
|
|
|
"File assembly in progress", responseBody));
|
|
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
log.error("Error completing upload: {}", uploadId, e);
|
|
|
|
|
|
|
|
|
|
CompleteUploadResponse responseBody = CompleteUploadResponse.builder()
|
|
|
|
|
.uploadId(uploadId)
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004, MessageCode.FILE_UPLOAD_ERROR.getCode(),
|
|
|
|
|
"Failed to complete upload: " + e.getMessage(), responseBody));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-18 14:40:27 +07:00
|
|
|
@GetMapping("/v{version}/files/download/{fileId}")
|
2025-12-26 12:22:40 +07:00
|
|
|
public ResponseEntity<?> downloadFile(
|
|
|
|
|
@PathVariable(required = false) String fileId,
|
|
|
|
|
@PathVariable(required = false) Integer version,
|
|
|
|
|
@RequestHeader(value = "Authorization", required = false) String tokenHeader) {
|
2025-12-18 14:40:27 +07:00
|
|
|
try {
|
2026-02-18 11:30:15 +07:00
|
|
|
if (tokenHeader == null || tokenHeader.isBlank()) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("token", tokenHeader);
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
2026-02-16 10:43:20 +07:00
|
|
|
MessageCode.TOKEN_IS_NULL.getCode(),
|
|
|
|
|
MessageCode.TOKEN_IS_NULL.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-05 16:26:46 +07:00
|
|
|
Long userId = authService.useUserAuthToken(tokenHeader);
|
2025-12-26 12:22:40 +07:00
|
|
|
FileEntityResponse entityResponse = fileEntityService.getById(fileId, version);
|
2025-12-18 14:40:27 +07:00
|
|
|
|
2026-02-24 14:19:15 +07:00
|
|
|
User fileUser = userRepository.findById(entityResponse.getUserId()).orElseThrow();
|
|
|
|
|
User user = userRepository.findById(userId).orElseThrow();
|
|
|
|
|
Company companyUser = user.getCompany();
|
|
|
|
|
|
|
|
|
|
if (companyUser != null && !fileUser.getCompany().getId().equals(companyUser.getId())) {
|
|
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("token", tokenHeader);
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
|
|
|
|
MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
|
|
|
|
|
MessageCode.USER_NOT_HAD_PERMISSION.getDescription(),
|
|
|
|
|
errorData));
|
2026-02-24 14:24:42 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (companyUser == null && !entityResponse.getUserId().equals(userId)) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("token", tokenHeader);
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
2026-02-16 10:43:20 +07:00
|
|
|
MessageCode.USER_NOT_HAD_PERMISSION.getCode(),
|
|
|
|
|
MessageCode.USER_NOT_HAD_PERMISSION.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (entityResponse.getStatus().equals(FileStatus.DELETED)) {
|
|
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("file_status", entityResponse.getStatus());
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
2026-02-18 11:30:15 +07:00
|
|
|
MessageCode.FILE_DELETE.getCode(),
|
|
|
|
|
MessageCode.FILE_DELETE.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
2025-12-18 14:40:27 +07:00
|
|
|
}
|
|
|
|
|
|
2025-12-26 12:22:40 +07:00
|
|
|
if (!entityResponse.isExistsOnDisk()) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("onDisk", entityResponse.isExistsOnDisk());
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
2026-02-18 11:30:15 +07:00
|
|
|
MessageCode.FILE_NOT_EXIST.getCode(),
|
|
|
|
|
MessageCode.FILE_NOT_EXIST.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
2025-12-18 14:40:27 +07:00
|
|
|
}
|
|
|
|
|
|
2026-01-30 17:39:19 +07:00
|
|
|
|
2026-01-30 18:02:34 +07:00
|
|
|
Path filePath = Paths.get(entityResponse.getProtectedFilePath());
|
|
|
|
|
FileSystemResource resource = new FileSystemResource(filePath);
|
|
|
|
|
long fileSize = Files.size(filePath);
|
2025-12-18 14:40:27 +07:00
|
|
|
|
|
|
|
|
if (!resource.exists()) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("resource", resource.exists());
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
|
|
|
|
MessageCode.FILE_DOWNLOAD_ERROR.getCode(),
|
2025-12-26 12:22:40 +07:00
|
|
|
MessageCode.FILE_DOWNLOAD_ERROR.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
2025-12-18 14:40:27 +07:00
|
|
|
}
|
2026-02-18 11:30:15 +07:00
|
|
|
String contentType = determineContentType(filePath);
|
2025-12-18 14:40:27 +07:00
|
|
|
|
|
|
|
|
return ResponseEntity.ok()
|
2026-01-30 18:02:34 +07:00
|
|
|
.contentLength(fileSize)
|
2025-12-18 14:40:27 +07:00
|
|
|
.contentType(MediaType.parseMediaType(contentType))
|
|
|
|
|
.header(HttpHeaders.CONTENT_DISPOSITION,
|
2026-02-12 16:03:39 +07:00
|
|
|
"attachment; filename=\"" + entityResponse.getFileName() + "\"")
|
2025-12-18 14:40:27 +07:00
|
|
|
.body(resource);
|
2025-12-26 12:22:40 +07:00
|
|
|
} catch (FileEntityNotFoundException e) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("fileId", fileId);
|
|
|
|
|
|
2025-12-26 12:22:40 +07:00
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
|
|
|
|
MessageCode.FILE_NOT_FOUND.getCode(),
|
|
|
|
|
MessageCode.FILE_NOT_FOUND.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
2026-02-18 11:30:15 +07:00
|
|
|
} catch (NotFoundAuthToken e) {
|
|
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("token", tokenHeader);
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
|
|
|
|
MessageCode.AUTH_TOKEN_NOT_FOUND.getCode(),
|
|
|
|
|
MessageCode.AUTH_TOKEN_NOT_FOUND.getDescription(),
|
|
|
|
|
errorData));
|
|
|
|
|
} catch (IOException e) {
|
2025-12-30 02:19:07 +07:00
|
|
|
Map<String, Object> errorData = new HashMap<>();
|
|
|
|
|
errorData.put("token", tokenHeader);
|
|
|
|
|
errorData.put("fileId", fileId);
|
|
|
|
|
errorData.put("version", version);
|
|
|
|
|
|
2025-12-26 12:22:40 +07:00
|
|
|
return ResponseEntity.ok().body(new BaseResponse(20004,
|
|
|
|
|
MessageCode.FILE_DOWNLOAD_ERROR_NOT_CORRECT_FIELD.getCode(),
|
|
|
|
|
MessageCode.FILE_DOWNLOAD_ERROR_NOT_CORRECT_FIELD.getDescription(),
|
2025-12-30 02:19:07 +07:00
|
|
|
errorData));
|
2025-12-18 14:40:27 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-05 19:02:17 +07:00
|
|
|
@GetMapping("/check/file_stats")
|
|
|
|
|
public ResponseEntity<?> checkFileProtectStats(@RequestHeader("Authorization") String tokenHeader) {
|
|
|
|
|
String token = tokenHeader.replace("Bearer ", "");
|
|
|
|
|
|
|
|
|
|
Optional<AuthToken> tokenOptional = authTokenRepository.findByToken(token);
|
|
|
|
|
|
|
|
|
|
AuthToken authToken = tokenOptional.orElseThrow(() -> new NotFoundAuthToken("Token: " + token + "not found"));
|
|
|
|
|
|
|
|
|
|
Map<String, Object> fileTypeStats = protectionsLimitService.getFileTypeStats(authToken.getUser().getId());
|
2026-02-05 18:55:54 +07:00
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(fileTypeStats);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
private boolean hasDuplicate(List<SimilarFileDTO> similarFiles) {
|
2026-01-16 14:30:45 +07:00
|
|
|
return similarFiles.stream().anyMatch(f -> f.getHammingDistance() <= 5);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
private ResponseEntity<BaseResponse> handleDuplicate(FileEntity fileEntity, List<SimilarFileDTO> similarFiles)
|
2026-01-16 14:30:45 +07:00
|
|
|
throws IOException {
|
|
|
|
|
fileEntityService.deleteFromDisk(fileEntity);
|
|
|
|
|
|
2026-01-27 08:09:54 +07:00
|
|
|
fileEntityService.softDeleteFileWithHash(fileEntity);
|
2026-01-16 14:30:45 +07:00
|
|
|
|
|
|
|
|
Optional<FileEntity> originalFile = fileEntityRepository.findById(similarFiles.get(0).getFileId());
|
|
|
|
|
|
|
|
|
|
if (originalFile.isPresent()) {
|
|
|
|
|
Map<String, String> duplicateInfo = Map.of(
|
|
|
|
|
"duplicate_file_id", originalFile.get().getId(),
|
|
|
|
|
"owner_user_id", String.valueOf(originalFile.get().getUserId()));
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20004,
|
|
|
|
|
MessageCode.DUPLICATE_FILE_UPLOAD.getCode(),
|
|
|
|
|
"Failed to upload chunk, duplicate",
|
|
|
|
|
duplicateInfo));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-26 21:03:45 +07:00
|
|
|
private ResponseEntity<BaseResponse> buildSuccessResponse(String uploadId, Integer chunkNumber, MultipartFile chunk,
|
|
|
|
|
String fileId) {
|
2026-01-15 20:41:35 +07:00
|
|
|
ChunkUploadResponse responseBody = ChunkUploadResponse.builder()
|
|
|
|
|
.uploadId(uploadId)
|
|
|
|
|
.chunkNumber(chunkNumber)
|
|
|
|
|
.chunkSize(chunk.getSize())
|
2026-01-26 21:03:45 +07:00
|
|
|
.fileId(fileId)
|
2026-01-15 20:41:35 +07:00
|
|
|
.message("Chunk uploaded successfully")
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20000,
|
|
|
|
|
MessageCode.SUCCESS.getCode(),
|
|
|
|
|
"Chunk uploaded successfully",
|
|
|
|
|
responseBody));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private ResponseEntity<BaseResponse> buildErrorResponse(String uploadId, Integer chunkNumber, String errorMessage) {
|
|
|
|
|
ChunkUploadResponse responseBody = ChunkUploadResponse.builder()
|
|
|
|
|
.uploadId(uploadId)
|
|
|
|
|
.chunkNumber(chunkNumber)
|
|
|
|
|
.build();
|
|
|
|
|
|
|
|
|
|
return ResponseEntity.ok().body(new BaseResponse(
|
|
|
|
|
20004,
|
|
|
|
|
MessageCode.FILE_UPLOAD_ERROR.getCode(),
|
|
|
|
|
errorMessage,
|
|
|
|
|
responseBody));
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 15:27:14 +07:00
|
|
|
private ResponseEntity<BaseResponse> createValidationErrorResponse(BindingResult bindingResult, Integer msgId) {
|
2025-12-10 02:37:31 +07:00
|
|
|
List<Map<String, String>> fieldErrors = bindingResult.getFieldErrors()
|
|
|
|
|
.stream()
|
|
|
|
|
.map(this::createErrorDetail)
|
|
|
|
|
.collect(Collectors.toList());
|
|
|
|
|
|
2025-12-10 15:27:14 +07:00
|
|
|
RegAnswer regAnswer = new RegAnswer();
|
|
|
|
|
regAnswer.setFieldErrors(fieldErrors);
|
2025-12-10 02:37:31 +07:00
|
|
|
|
2025-12-10 15:27:14 +07:00
|
|
|
return ResponseEntity.ok().body(new BaseResponse(msgId, MessageCode.INVALID_FIELD.getCode(),
|
|
|
|
|
MessageCode.INVALID_FIELD.getDescription(), regAnswer));
|
2025-12-10 02:37:31 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Map<String, String> createErrorDetail(FieldError fieldError) {
|
|
|
|
|
Map<String, String> errorDetail = new HashMap<>();
|
|
|
|
|
errorDetail.put("field", fieldError.getField());
|
|
|
|
|
errorDetail.put("code", fieldError.getCode() != null ? fieldError.getCode() : "VALIDATION_ERROR");
|
|
|
|
|
errorDetail.put("message", fieldError.getDefaultMessage());
|
|
|
|
|
|
|
|
|
|
if (fieldError.getRejectedValue() != null &&
|
|
|
|
|
!fieldError.getField().toLowerCase().contains("password")) {
|
|
|
|
|
errorDetail.put("rejected_value", fieldError.getRejectedValue().toString());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return errorDetail;
|
|
|
|
|
}
|
2025-12-18 14:40:27 +07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
private String determineContentType(Path filePath) throws IOException {
|
|
|
|
|
String contentType = Files.probeContentType(filePath);
|
|
|
|
|
if (contentType == null) {
|
|
|
|
|
contentType = "application/octet-stream";
|
|
|
|
|
}
|
|
|
|
|
return contentType;
|
|
|
|
|
}
|
2025-12-10 02:37:31 +07:00
|
|
|
}
|