Files
no-copy/src/main/java/ru/soune/nocopy/service/FileSimilarityService.java
T

267 lines
11 KiB
Java
Raw Normal View History

package ru.soune.nocopy.service;
2026-01-27 20:27:39 +07:00
import com.vrt.fileprotection.image.phash.PHash;
import com.vrt.fileprotection.image.phash.PerceptualHashHelper;
import lombok.RequiredArgsConstructor;
2026-01-25 20:45:29 +07:00
import lombok.extern.slf4j.Slf4j;
2026-01-27 20:27:39 +07:00
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.file.SimilarFileDTO;
2026-02-24 14:56:41 +07:00
import ru.soune.nocopy.entity.company.Company;
import ru.soune.nocopy.entity.file.FileEntity;
2026-03-25 15:55:16 +07:00
import ru.soune.nocopy.entity.file.FileStatus;
2026-01-25 22:05:19 +07:00
import ru.soune.nocopy.entity.file.ImageHashEntity;
2026-02-24 14:56:41 +07:00
import ru.soune.nocopy.entity.user.User;
2026-02-16 20:16:50 +07:00
import ru.soune.nocopy.exception.DuplicateImageException;
import ru.soune.nocopy.repository.*;
import ru.soune.nocopy.util.FileUtil;
2026-03-02 13:55:45 +07:00
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
2026-01-25 22:05:19 +07:00
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
2026-01-25 20:45:29 +07:00
@Slf4j
public class FileSimilarityService {
private final ImageSimilarityRepository repository;
private final ImageHashRepository hashRepository;
private final FileUtil fileUtil;
private final AuthTokenRepository authTokenRepository;
2026-02-16 20:11:06 +07:00
private final FileEntityRepository fileEntityRepository;
2026-03-07 02:18:56 +07:00
@Value("${server.baseurl}")
2026-01-27 20:27:39 +07:00
private String baseUrl;
public List<SimilarFileDTO> findDuplicateByHammingDistance(String fileId, int hammingDistance,
int duplicate, int similar) {
List<SimilarImageProjection> candidates = repository.findCandidates(fileId);
2026-01-25 22:05:19 +07:00
Optional<ImageHashEntity> hashOptional = hashRepository.findById(fileId);
if (hashOptional.isEmpty()) {
return Collections.emptyList();
}
var imageHashEntity = hashOptional.get();
Long hash64Hi = imageHashEntity.getHash64Hi();
Long hash64Lo = imageHashEntity.getHash64Lo();
return candidates.stream()
.map(c -> {
Long cHi = c.getHash64Hi();
Long cLo = c.getHash64Lo();
int hamming = fileUtil.hamming64(hash64Hi, hash64Lo, cHi, cLo);
return new AbstractMap.SimpleEntry<>(c, hamming);
})
.filter(entry -> entry.getValue() <= hammingDistance)
.sorted((a, b) -> Integer.compare(a.getValue(), b.getValue()))
.map(entry -> {
SimilarImageProjection similarImageProjection = entry.getKey();
int hamming = entry.getValue();
String level;
if (hamming <= duplicate) {
level = "DUPLICATE";
} else if (hamming <= similar) {
level = "SIMILAR";
} else {
level = "DIFFERENT";
}
return SimilarFileDTO.builder()
2026-01-25 18:59:55 +07:00
.fileId(similarImageProjection.getId())
.originalFileName(similarImageProjection.getOriginalFileName())
.fileSize(similarImageProjection.getFileSize())
.hammingDistance(hamming)
.similarityLevel(level)
.ownerId(similarImageProjection.getUserId())
.build();
})
.toList();
}
public List<SimilarImageProjection> findDuplicatedByHash(Long hash64Hi, Long hash64Lo) {
2026-01-19 15:49:27 +07:00
List<SimilarImageProjection> duplicates = repository.findExactDuplicates(hash64Hi,hash64Lo);
if (duplicates.isEmpty()) {
return new ArrayList<>();
}
return duplicates;
}
2026-02-27 01:47:50 +07:00
public void hasDuplicatesByHash(String path, String mimeType, Long userId) throws Exception {
FileEntity duplicateByHash = findDuplicateByHash(path, mimeType, userId);
if (duplicateByHash != null) {
throw new DuplicateImageException("Duplicate", duplicateByHash.getId(),
duplicateByHash.getUserId());
}
}
public FileEntity findDuplicateByHash(String path, String mimeType, Long userId) throws Exception {
2026-02-17 15:39:26 +07:00
String hash = calculateFileHash(path);
2026-03-02 13:55:45 +07:00
2026-02-27 01:47:50 +07:00
User user = userRepository.findById(userId).orElseThrow();
Company company = user.getCompany();
List<Long> userIds = new ArrayList<>();
if (company != null) {
userIds.addAll(company.getUsers().stream().map(User::getId).toList());
} else {
userIds.add(userId);
}
List<FileEntity> fileEntityList = fileEntityRepository.findByMimeTypeAndUserIds(mimeType, userIds);
2026-02-17 15:39:26 +07:00
for (FileEntity file : fileEntityList) {
2026-03-02 14:05:27 +07:00
if (file.getProtectedFilePath() == null) continue;
2026-03-02 13:55:45 +07:00
File existingFile = new File(file.getProtectedFilePath());
File newFile = new File(path);
if (existingFile.length() == newFile.length()) {
if (calculateFileHash(file.getProtectedFilePath()).equals(hash)) {
return file;
}
2026-02-17 15:39:26 +07:00
}
}
2026-02-27 01:47:50 +07:00
return null;
2026-02-17 15:39:26 +07:00
}
2026-02-24 14:56:41 +07:00
private final UserRepository userRepository;
2026-02-17 13:57:38 +07:00
public Page<SimilarFileDTO> findSimilarFiles(
String fileId,
List<String> similarityLevels,
Pageable pageable,
String authToken) {
try {
var imageHashEntity = hashRepository.findById(fileId)
2026-02-17 13:57:38 +07:00
.orElseThrow(() -> new RuntimeException("Hash not found for file: " + fileId));
2026-03-25 15:55:16 +07:00
2026-03-19 14:48:07 +07:00
List<Long> userIds;
2026-03-25 15:55:16 +07:00
List<SimilarImageProjection> candidates = repository.findCandidates(fileId);
Long userId = authTokenRepository.findUserIdByToken(authToken);
User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found"));
Company company = user.getCompany();
if (company != null) {
userIds = company.getUsers().stream().map(User::getId).collect(Collectors.toList());
} else {
userIds = List.of(userId);
}
2026-02-17 13:57:38 +07:00
List<String> levels = (similarityLevels != null && !similarityLevels.isEmpty())
? similarityLevels
: List.of("DUPLICATE", "SIMILAR", "DIFFERENT");
2026-02-17 13:57:38 +07:00
List<SimilarFileDTO> allResults = candidates.stream()
.map(c -> createSimilarFileResponse(c,
imageHashEntity.getHash64Hi(),
2026-03-19 14:48:07 +07:00
imageHashEntity.getHash64Lo(), userIds))
2026-02-17 13:57:38 +07:00
.filter(dto -> levels.contains(dto.getSimilarityLevel()))
2026-03-31 13:31:26 +07:00
.filter(dto -> !(dto.getFileStatus().equals(FileStatus.MODERATION.name()) && !dto.getOwner()))
.sorted(Comparator.comparingInt(SimilarFileDTO::getHammingDistance))
.collect(Collectors.toList());
2026-02-17 12:46:54 +07:00
2026-02-17 13:57:38 +07:00
int start = (int) pageable.getOffset();
int end = Math.min((start + pageable.getPageSize()), allResults.size());
List<SimilarFileDTO> pageContent = start < allResults.size() ?
allResults.subList(start, end) : Collections.emptyList();
2026-02-17 13:57:38 +07:00
return new PageImpl<>(pageContent, pageable, allResults.size());
2026-02-17 12:55:25 +07:00
2026-02-17 13:57:38 +07:00
} catch (Exception e) {
log.error("Error finding similar files for fileId: {}", fileId, e);
return new PageImpl<>(Collections.emptyList(), pageable, 0);
}
}
2026-02-16 20:11:06 +07:00
private String calculateFileHash(String path) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
2026-02-16 20:11:06 +07:00
try (InputStream is = new FileInputStream(path)) {
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
}
byte[] hashBytes = digest.digest();
return Base64.getEncoder().encodeToString(hashBytes);
}
private SimilarFileDTO createSimilarFileResponse(SimilarImageProjection similarImageProjection,
2026-03-19 14:48:07 +07:00
Long hash64Hi, Long hash64Lo, List<Long> userIds) {
Long imageProjectionHash64Hi = similarImageProjection.getHash64Hi();
Long similarImageProjectionHash64Lo = similarImageProjection.getHash64Lo();
2026-01-27 20:27:39 +07:00
int hamming = PerceptualHashHelper.INSTANCE.hammingDistance(new PHash(hash64Hi, hash64Lo),
new PHash(imageProjectionHash64Hi, similarImageProjectionHash64Lo));
String level;
2026-01-27 20:27:39 +07:00
if (hamming <= 6) {
level = "DUPLICATE";
} else if (hamming <= 12) {
level = "SIMILAR";
} else {
level = "DIFFERENT";
}
2026-03-31 13:06:27 +07:00
boolean owner = userIds.contains(similarImageProjection.getUserId());
return SimilarFileDTO.builder()
2026-01-24 10:59:02 +07:00
.fileId(similarImageProjection.getId())
2026-01-25 20:45:29 +07:00
.ownerId(similarImageProjection.getUserId())
2026-02-17 11:11:51 +07:00
.originalFileName(similarImageProjection.getOriginalFileName().replace("." +
similarImageProjection.getExtension(), "") + "_nocopy_protected" +
"." + similarImageProjection.getExtension())
.fileSize(similarImageProjection.getFileSize())
.hammingDistance(hamming)
.similarityLevel(level)
2026-01-27 20:27:39 +07:00
.supportId(similarImageProjection.getSupportId())
.uploadDate(similarImageProjection.getUploadDate())
.status(similarImageProjection.getProtectionStatus())
2026-03-31 13:06:27 +07:00
.owner(owner)
2026-02-26 00:27:31 +07:00
// .url(baseUrl + "/api/files/protected/" + similarImageProjection.getId())
2026-03-07 02:18:56 +07:00
.url(baseUrl + "/api/files/protected/" + similarImageProjection.getId() + "/thumbnail")
2026-03-25 15:55:16 +07:00
.fileStatus(similarImageProjection.getFileStatus())
.build();
}
2026-02-17 13:57:38 +07:00
public SimilarFileDTO buildDTO(FileEntity fileEntity) {
return SimilarFileDTO.builder()
.fileId(fileEntity.getId())
.ownerId(fileEntity.getUserId())
2026-02-17 11:11:51 +07:00
.originalFileName(fileEntity.getOriginalFileName().replace("." +
fileEntity.getFileExtension(), "") + "_nocopy_protected" +
"." + fileEntity.getFileExtension())
.fileSize(fileEntity.getFileSize())
.uploadDate(fileEntity.getCreatedAt())
2026-03-25 16:12:26 +07:00
.fileStatus(fileEntity.getStatus().name())
.status(fileEntity.getProtectionStatus())
2026-03-02 14:12:40 +07:00
.supportId(Long.valueOf(fileEntity.getSupportId()))
.build();
}
}