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

316 lines
11 KiB
Java
Raw Normal View History

2026-02-11 17:41:48 +07:00
package ru.soune.nocopy.service.search;
2026-02-12 12:07:41 +07:00
import com.fasterxml.jackson.databind.JsonNode;
2026-02-11 17:41:48 +07:00
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.MessageCode;
2026-02-12 12:07:41 +07:00
import ru.soune.nocopy.dto.file.YandexSearchResponse;
2026-02-11 17:41:48 +07:00
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.exception.NotValidFieldException;
import java.io.*;
import java.net.SocketTimeoutException;
2026-02-12 12:07:41 +07:00
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
2026-02-11 17:41:48 +07:00
import java.util.Map;
import java.util.concurrent.*;
@Slf4j
@Service
public class SearchImageService {
private final ObjectMapper objectMapper;
// private final OkHttpClient httpClient;
private final OkHttpClient yandexHttpClient;
private final OkHttpClient googleHttpClient;
// public SearchImageService() {
// this.httpClient = new OkHttpClient.Builder()
// .connectTimeout(18, TimeUnit.SECONDS)
// .writeTimeout(18, TimeUnit.SECONDS)
// .readTimeout(18, TimeUnit.SECONDS)
// .callTimeout(18, TimeUnit.SECONDS)
// .followRedirects(true)
// .followSslRedirects(true)
// .retryOnConnectionFailure(true)
// .connectionPool(new ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
// .build();
//
// this.objectMapper = new ObjectMapper();
// }
2026-02-11 17:41:48 +07:00
public SearchImageService() {
this.yandexHttpClient = new OkHttpClient.Builder()
.connectTimeout(35, TimeUnit.SECONDS)
.writeTimeout(35, TimeUnit.SECONDS)
.readTimeout(35, TimeUnit.SECONDS)
.callTimeout(35, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(true)
2026-03-11 12:48:54 +07:00
// .connectionPool(new ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
.build();
this.googleHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.callTimeout(15, TimeUnit.SECONDS)
2026-02-22 00:25:05 +07:00
.followRedirects(true)
.followSslRedirects(true)
2026-02-11 17:41:48 +07:00
.retryOnConnectionFailure(true)
2026-03-11 12:48:54 +07:00
// .connectionPool(new ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
2026-02-11 17:41:48 +07:00
.build();
this.objectMapper = new ObjectMapper();
}
@Value("${yandex.api-key}")
private String apiKey;
@Value("${yandex.folder-id}")
private String folderId;
@Value("${yandex.search-url}")
private String searchUrl;
@Value("${searchapi.api-key:}")
private String searchApiKey;
2026-03-07 02:18:56 +07:00
@Value("${server.baseurl}")
2026-02-11 17:41:48 +07:00
private String appBaseUrl;
@PostConstruct
public void init() {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
2026-02-11 17:53:02 +07:00
public String searchReverseByPublicUrl(FileEntity fileEntity, String engine, String searchType)
2026-02-11 17:41:48 +07:00
throws IOException, TimeoutException {
if (!isImageFile(fileEntity)) {
throw new NotValidFieldException(
"File not image",
new BaseResponse(
20007,
MessageCode.INVALID_FIELD.getCode(),
MessageCode.INVALID_FIELD.getDescription(),
Map.of("file_type", fileEntity.getMimeType())
)
);
}
2026-03-07 02:18:56 +07:00
String publicUrl = String.format("%s/api/files/public/%s", appBaseUrl, fileEntity.getId());
2026-02-11 17:41:48 +07:00
log.info("Searching reverse for image: {}", publicUrl);
try {
2026-02-11 17:53:02 +07:00
return callReverseImageApiByUrl(publicUrl, engine, searchType);
2026-02-11 17:41:48 +07:00
} catch (SocketTimeoutException e) {
log.error("Yandex search timeout after {}", fileEntity.getId());
throw new TimeoutException("Search timeout");
}
}
private boolean isImageFile(FileEntity fileEntity) {
String mimeType = fileEntity.getMimeType();
return mimeType != null && mimeType.startsWith("image");
}
2026-02-11 17:53:02 +07:00
private String callReverseImageApiByUrl(String imageUrl, String engine, String searchType) throws IOException {
2026-02-11 17:41:48 +07:00
if (searchApiKey == null || searchApiKey.isBlank()) {
throw new IllegalStateException("SearchAPI key not configured");
}
OkHttpClient client = engine.contains("yandex_reverse_image") ? yandexHttpClient : googleHttpClient;
2026-02-22 00:25:05 +07:00
HttpUrl url = HttpUrl.parse("https://www.searchapi.io/api/v1/search")
2026-02-11 17:41:48 +07:00
.newBuilder()
.addQueryParameter("engine", engine)
.addQueryParameter("api_key", searchApiKey)
.addQueryParameter("url", imageUrl)
2026-02-11 17:53:02 +07:00
.addQueryParameter("search_type", searchType)
.addQueryParameter("t_", String.valueOf(System.currentTimeMillis()))
2026-02-11 17:41:48 +07:00
.build();
2026-03-11 13:04:56 +07:00
// Request request = new Request.Builder()
// .url(url)
// .header("Accept", "application/json")
// .header("User-Agent", "Mozilla/5.0")
// .build();
2026-02-11 17:41:48 +07:00
Request request = new Request.Builder()
.url(url)
2026-03-11 13:04:56 +07:00
.header("Accept", "*/*")
.header("User-Agent", "curl/8.5.0")
.header("Host", "www.searchapi.io")
2026-02-11 17:41:48 +07:00
.build();
long start = System.currentTimeMillis();
2026-02-11 17:41:48 +07:00
try (Response response = client.newCall(request).execute()) {
long duration = System.currentTimeMillis() - start;
log.info("SearchAPI response code={}, duration={}ms, engine={}",
response.code(), duration, engine);
2026-02-11 17:41:48 +07:00
if (!response.isSuccessful()) {
String errorBody = response.body() != null ? response.body().string() : "null";
throw new IOException("API error " + response.code() + ": " + errorBody);
2026-02-11 17:41:48 +07:00
}
ResponseBody body = response.body();
if (body == null) {
throw new IOException("Empty response body");
}
return body.string();
2026-02-11 17:41:48 +07:00
}
}
2026-02-12 12:07:41 +07:00
public List<YandexSearchResponse.ImageResult> getAllImagesWithoutPagination(String searchApiJson, String findType)
throws IOException {
JsonNode root = objectMapper.readTree(searchApiJson);
JsonNode matches = root.path(findType);
2026-02-11 17:41:48 +07:00
2026-02-12 12:07:41 +07:00
List<YandexSearchResponse.ImageResult> allImages = new ArrayList<>();
2026-02-11 17:41:48 +07:00
2026-02-12 12:07:41 +07:00
if (matches.isArray()) {
for (JsonNode match : matches) {
YandexSearchResponse.ImageResult result = mapImageResult(match);
2026-02-11 17:41:48 +07:00
2026-02-12 12:07:41 +07:00
if ("exact_matches".equals(findType)) {
JsonNode thumbnail = match.path("thumbnail");
if (!thumbnail.isMissingNode() && thumbnail.asText().startsWith("data:image")) {
result.setUrl(thumbnail.asText());
}
2026-02-11 17:41:48 +07:00
2026-02-12 12:07:41 +07:00
JsonNode imageNode = match.path("image");
if (!imageNode.isMissingNode()) {
2026-02-12 15:36:45 +07:00
String directUrl = imageNode.path("link").asText();
2026-02-12 12:07:41 +07:00
if (directUrl != null && !directUrl.isBlank()) {
result.setUrl(directUrl);
}
}
}
if (result.getUrl() != null && !result.getUrl().isBlank()) {
allImages.add(result);
}
}
}
return allImages;
}
public List<YandexSearchResponse.ImageResult> removeDuplicateUrls(
List<YandexSearchResponse.ImageResult> yandexImages,
List<YandexSearchResponse.ImageResult> googleImages) {
Map<String, YandexSearchResponse.ImageResult> uniqueByUrl = new LinkedHashMap<>();
for (YandexSearchResponse.ImageResult image : googleImages) {
String normalizedUrl = normalizeUrl(image.getUrl());
uniqueByUrl.putIfAbsent(normalizedUrl, image);
}
for (YandexSearchResponse.ImageResult image : yandexImages) {
String normalizedUrl = normalizeUrl(image.getUrl());
uniqueByUrl.putIfAbsent(normalizedUrl, image);
}
return new ArrayList<>(uniqueByUrl.values());
}
public List<YandexSearchResponse.ImageResult> paginateResults(
List<YandexSearchResponse.ImageResult> allResults,
int page,
int pageSize) {
if (allResults.isEmpty()) {
return new ArrayList<>();
}
int totalPages = (int) Math.ceil((double) allResults.size() / pageSize);
if (page > totalPages) {
return new ArrayList<>();
}
int startIndex = (page - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, allResults.size());
return new ArrayList<>(allResults.subList(startIndex, endIndex));
}
private String normalizeUrl(String url) {
if (url == null) return null;
try {
if (url.startsWith("data:image")) {
return url.length() > 100 ? url.substring(0, 100) : url;
}
java.net.URI uri = new java.net.URI(url);
String host = uri.getHost();
if (host != null) {
host = host.toLowerCase().replaceFirst("^www\\.", "");
}
String path = uri.getPath();
if (path != null && path.length() > 1 && path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return (host != null ? host : "") + (path != null ? path : "");
} catch (Exception e) {
return url.toLowerCase()
.replaceFirst("^(https?://)?(www\\.)?", "")
.replaceFirst("/$", "");
}
}
private YandexSearchResponse.ImageResult mapImageResult(JsonNode match) {
YandexSearchResponse.ImageResult result =
new YandexSearchResponse.ImageResult();
JsonNode imageNode = match.path("image");
if (imageNode.isObject()) {
2026-02-12 15:36:45 +07:00
result.setUrl(imageNode.path("link").asText());
2026-02-12 12:07:41 +07:00
result.setWidth(imageNode.path("width").asInt(0));
result.setHeight(imageNode.path("height").asInt(0));
}
2026-02-12 15:36:45 +07:00
result.setPageUrl(match.path("link").asText());
result.setPageTitle(match.path("title").asText());
2026-02-12 12:07:41 +07:00
2026-02-12 15:36:45 +07:00
String source = match.path("source").asText();
2026-02-12 12:07:41 +07:00
result.setHost(extractHostFromSource(source));
return result;
}
private String extractHostFromSource(String source) {
if (source == null || source.isEmpty()) {
return "";
}
source = source.replaceFirst("^(https?://)?(www\\.)?", "");
int slashIndex = source.indexOf('/');
if (slashIndex > 0) {
return source.substring(0, slashIndex);
}
return source;
}
2026-02-11 17:41:48 +07:00
}