2026-01-13 22:40:52 +07:00
|
|
|
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;
|
2026-01-13 22:40:52 +07:00
|
|
|
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;
|
2026-01-16 14:30:45 +07:00
|
|
|
import org.springframework.data.domain.Page;
|
|
|
|
|
import org.springframework.data.domain.PageImpl;
|
|
|
|
|
import org.springframework.data.domain.Pageable;
|
2026-01-13 22:40:52 +07:00
|
|
|
import org.springframework.stereotype.Service;
|
2026-01-22 19:55:09 +07:00
|
|
|
import ru.soune.nocopy.dto.file.SimilarFileDTO;
|
2026-02-24 14:56:41 +07:00
|
|
|
import ru.soune.nocopy.entity.company.Company;
|
2026-02-16 16:41:29 +07:00
|
|
|
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;
|
2026-02-16 16:41:29 +07:00
|
|
|
import ru.soune.nocopy.repository.*;
|
2026-01-22 19:55:09 +07:00
|
|
|
import ru.soune.nocopy.util.FileUtil;
|
2026-01-13 22:40:52 +07:00
|
|
|
|
2026-03-02 13:55:45 +07:00
|
|
|
import java.io.File;
|
2026-02-16 16:41:29 +07:00
|
|
|
import java.io.FileInputStream;
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
import java.security.MessageDigest;
|
2026-01-25 22:05:19 +07:00
|
|
|
import java.util.*;
|
2026-01-16 14:30:45 +07:00
|
|
|
import java.util.stream.Collectors;
|
2026-01-13 22:40:52 +07:00
|
|
|
|
|
|
|
|
@Service
|
|
|
|
|
@RequiredArgsConstructor
|
2026-01-25 20:45:29 +07:00
|
|
|
@Slf4j
|
2026-01-13 22:40:52 +07:00
|
|
|
public class FileSimilarityService {
|
2026-01-22 19:55:09 +07:00
|
|
|
|
2026-01-13 22:40:52 +07:00
|
|
|
private final ImageSimilarityRepository repository;
|
2026-01-16 14:30:45 +07:00
|
|
|
|
2026-01-13 22:40:52 +07:00
|
|
|
private final ImageHashRepository hashRepository;
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
private final FileUtil fileUtil;
|
|
|
|
|
|
2026-01-26 21:03:45 +07:00
|
|
|
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;
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
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();
|
2026-01-22 19:55:09 +07:00
|
|
|
|
2026-01-23 13:22:02 +07:00
|
|
|
Long hash64Hi = imageHashEntity.getHash64Hi();
|
|
|
|
|
Long hash64Lo = imageHashEntity.getHash64Lo();
|
2026-01-22 19:55:09 +07:00
|
|
|
|
|
|
|
|
return candidates.stream()
|
|
|
|
|
.map(c -> {
|
2026-01-23 13:22:02 +07:00
|
|
|
Long cHi = c.getHash64Hi();
|
|
|
|
|
Long cLo = c.getHash64Lo();
|
2026-01-22 19:55:09 +07:00
|
|
|
|
|
|
|
|
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())
|
2026-01-22 19:55:09 +07:00
|
|
|
.originalFileName(similarImageProjection.getOriginalFileName())
|
|
|
|
|
.fileSize(similarImageProjection.getFileSize())
|
|
|
|
|
.hammingDistance(hamming)
|
|
|
|
|
.similarityLevel(level)
|
|
|
|
|
.ownerId(similarImageProjection.getUserId())
|
|
|
|
|
.build();
|
|
|
|
|
})
|
|
|
|
|
.toList();
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-23 13:22:02 +07:00
|
|
|
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-01-16 14:30:45 +07:00
|
|
|
|
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-01-16 14:30:45 +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 {
|
2026-02-16 16:41:29 +07:00
|
|
|
var imageHashEntity = hashRepository.findById(fileId)
|
2026-02-17 13:57:38 +07:00
|
|
|
.orElseThrow(() -> new RuntimeException("Hash not found for file: " + fileId));
|
2026-01-16 14:30:45 +07:00
|
|
|
|
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-01-16 14:30:45 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
List<String> levels = (similarityLevels != null && !similarityLevels.isEmpty())
|
|
|
|
|
? similarityLevels
|
2026-02-16 16:41:29 +07:00
|
|
|
: 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-25 15:55:16 +07:00
|
|
|
.filter(dto -> dto.getFileStatus().equals(FileStatus.ACTIVE.name()))
|
2026-02-16 16:41:29 +07:00
|
|
|
.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-16 16:41:29 +07:00
|
|
|
|
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 16:41:29 +07:00
|
|
|
}
|
2026-01-16 14:30:45 +07:00
|
|
|
}
|
|
|
|
|
|
2026-02-16 16:41:29 +07:00
|
|
|
|
2026-02-16 20:11:06 +07:00
|
|
|
private String calculateFileHash(String path) throws Exception {
|
2026-02-16 16:41:29 +07:00
|
|
|
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);
|
|
|
|
|
}
|
2026-02-16 16:41:29 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
byte[] hashBytes = digest.digest();
|
|
|
|
|
return Base64.getEncoder().encodeToString(hashBytes);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
private SimilarFileDTO createSimilarFileResponse(SimilarImageProjection similarImageProjection,
|
2026-03-19 14:48:07 +07:00
|
|
|
Long hash64Hi, Long hash64Lo, List<Long> userIds) {
|
2026-01-23 13:22:02 +07:00
|
|
|
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));
|
2026-01-16 14:30:45 +07:00
|
|
|
|
|
|
|
|
String level;
|
2026-01-27 20:27:39 +07:00
|
|
|
if (hamming <= 6) {
|
2026-01-16 14:30:45 +07:00
|
|
|
level = "DUPLICATE";
|
|
|
|
|
} else if (hamming <= 12) {
|
|
|
|
|
level = "SIMILAR";
|
|
|
|
|
} else {
|
|
|
|
|
level = "DIFFERENT";
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-22 19:55:09 +07:00
|
|
|
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())
|
2026-01-16 14:30:45 +07:00
|
|
|
.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-19 14:48:07 +07:00
|
|
|
.owner(userIds.contains(similarImageProjection.getUserId()))
|
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())
|
2026-01-16 14:30:45 +07:00
|
|
|
.build();
|
|
|
|
|
}
|
2026-02-16 16:41:29 +07:00
|
|
|
|
2026-02-17 13:57:38 +07:00
|
|
|
public SimilarFileDTO buildDTO(FileEntity fileEntity) {
|
2026-02-16 16:41:29 +07:00
|
|
|
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())
|
2026-02-16 16:41:29 +07:00
|
|
|
.fileSize(fileEntity.getFileSize())
|
|
|
|
|
.uploadDate(fileEntity.getCreatedAt())
|
|
|
|
|
.status(fileEntity.getProtectionStatus())
|
2026-03-02 14:12:40 +07:00
|
|
|
.supportId(Long.valueOf(fileEntity.getSupportId()))
|
2026-02-16 16:41:29 +07:00
|
|
|
.build();
|
|
|
|
|
}
|
2026-01-13 22:40:52 +07:00
|
|
|
}
|