Compare commits

...
8 Commits
Author SHA1 Message Date
backdev 45d958e923 add work monitoring scheme 2026-06-11 17:44:03 +07:00
backdev 02f1dad83a add work monitoring scheme 2026-06-11 16:45:35 +07:00
backdev cf79647e24 add work monitoring scheme 2026-06-11 15:07:10 +07:00
backdev fb116c5ca7 add work monitoring scheme 2026-06-11 14:34:31 +07:00
backdev 76b678460a add work monitoring scheme 2026-06-11 11:07:34 +07:00
backdev d6504e4b5d add kafka listener 2026-06-04 17:58:54 +07:00
backdev 8139c1c2df Merge branch 'main' of https://code.3err0.ru/backdev/monitoring-service 2026-06-04 14:11:55 +07:00
backdev fb865e47c7 initial commit 2026-06-04 14:10:01 +07:00
19 changed files with 953 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
POSTGRES_DB: monitoring_db
POSTGRES_USER: adminMonitoring
POSTGRES_PASSWORD: monitoringDbApp
POSTGRES_PORT=5353
POSTGRES_HOST=db
REDIS_HOST=redis
REDIS_PORT=6379
SERVER_PORT=8080
MAIL_HOST_PROD=postfix-production
MAIL_PORT_PROD=25
MAIL_USERNAME_PROD=noreply@nocopy.com
SMTP_PASSWORD_PROD=nocopy!nocopy!
+3
View File
@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
+37
View File
@@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
+14
View File
@@ -0,0 +1,14 @@
FROM gradle:8.14.2-jdk21 AS build
WORKDIR /app
COPY . .
RUN gradle --no-daemon clean bootJar -x test
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/build/libs/*.jar app.jar
EXPOSE 8083
CMD ["java", "-jar", "app.jar"]
+54
View File
@@ -0,0 +1,54 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.6'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'ru.no-copy'
version = '0.0.1-SNAPSHOT'
description = 'monitoring'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.kafka:spring-kafka'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-validation'
annotationProcessor 'org.projectlombok:lombok'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test'
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-thymeleaf-test'
testImplementation 'org.springframework.boot:spring-boot-starter-validation-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.17.0'
implementation 'tools.jackson.core:jackson-core:3.0.3'
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.17.2'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.12.0'
}
tasks.named('test') {
useJUnitPlatform()
}
+81
View File
@@ -0,0 +1,81 @@
version: '3.9'
services:
db:
image: postgres:17.7
container_name: monitoring-db
environment:
POSTGRES_DB: monitoring_db
POSTGRES_USER: adminMonitoring
POSTGRES_PASSWORD: monitoringDbApp
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5353:5432"
restart: unless-stopped
monitoring:
build: .
container_name: monitoring-backend
ports:
- "${SERVER_PORT:-8083}:${SERVER_PORT:-8083}"
environment:
SPRING_PROFILES_ACTIVE: prod
POSTGRES_HOST: db
POSTGRES_PORT: 5432
POSTGRES_DB: monitoring_db
POSTGRES_USER: adminMonitoring
POSTGRES_PASSWORD: monitoringDbApp
SERVER_PORT: ${SERVER_PORT:-8083}
# SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
depends_on:
- db
restart: unless-stopped
networks:
- app-network
kafka:
image: apache/kafka:latest
container_name: kafka
ports:
- "9092:9092"
environment:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: 'broker,controller'
KAFKA_CONTROLLER_QUORUM_VOTERS: '1@kafka:9093'
KAFKA_LISTENERS: 'PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093'
KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://kafka:9092'
KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT'
KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true'
KAFKA_DELETE_TOPIC_ENABLE: 'true'
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_DEFAULT_REPLICATION_FACTOR: 1
KAFKA_MIN_INSYNC_REPLICAS: 1
volumes:
- kafka_data:/var/lib/kafka/data
networks:
- app-network
kafka-ui:
image: provectuslabs/kafka-ui:latest
container_name: kafka-ui
ports:
- "8010:8080"
environment:
DYNAMIC_CONFIG_ENABLED: 'true'
KAFKA_CLUSTERS_0_NAME: 'local-cluster'
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: 'kafka:9092'
depends_on:
- kafka
networks:
- app-network
volumes:
kafka_data:
postgres_data:
networks:
app-network:
external: true
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'monitoring'
@@ -0,0 +1,13 @@
package ru.no_copy.monitoring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MonitoringApplication {
public static void main(String[] args) {
SpringApplication.run(MonitoringApplication.class, args);
}
}
@@ -0,0 +1,17 @@
package ru.no_copy.monitoring.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController("/api/monitoring")
public class HealthCheckController {
@GetMapping
public ResponseEntity<Map<String, String>> healthCheck() {
return ResponseEntity.ok().body(Map.of("status","ok"));
}
}
@@ -0,0 +1,17 @@
package ru.no_copy.monitoring.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MonitoringDTO {
String fileId;
String baseUrl;
String engine;
String searchType;
}
@@ -0,0 +1,47 @@
package ru.no_copy.monitoring.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class SearchResponse {
@JsonProperty("images")
private List<ImageResult> images;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ImageResult {
@JsonProperty("url")
private String url;
@JsonProperty("pageUrl")
private String pageUrl;
@JsonProperty("pageTitle")
private String pageTitle;
@JsonProperty("width")
private Integer width;
@JsonProperty("height")
private Integer height;
@JsonProperty("host")
private String host;
@JsonProperty("file_id")
private String fileId;
}
private int page;
private int pageSize;
private int totalResults;
private int totalPages;
}
@@ -0,0 +1,32 @@
package ru.no_copy.monitoring.kafka;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import ru.no_copy.monitoring.service.MonitoringService;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
@Component
@Slf4j
public class MonitoringCommandListener {
private final MonitoringService monitoringService;
public MonitoringCommandListener(MonitoringService monitoringService) {
this.monitoringService = monitoringService;
}
@KafkaListener(topics = "monitoring-commands", groupId = "monitoring-service")
public void handleCommand(String commandMessage) {
log.info("message: " + commandMessage);
CompletableFuture.runAsync(() -> {
try {
monitoringService.execute(commandMessage);
} catch (IOException | TimeoutException e) {
throw new RuntimeException(e);
}
});
}
}
@@ -0,0 +1,173 @@
package ru.no_copy.monitoring.searcher;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import ru.no_copy.monitoring.dto.SearchResponse;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j
@Service
@RequiredArgsConstructor
public class SearchImageService {
private final ObjectMapper objectMapper;
@Value("${searchapi.api-key:}")
private String searchApiKey;
public String searchReverseByPublicUrl(String fileId, String baseUrl, String engine, String searchType)
throws IOException, TimeoutException {
String publicUrl = String.format("%s/api/files/public/%s", baseUrl, fileId);
try {
return callReverseImageApiByUrl(publicUrl, engine, searchType);
} catch (SocketTimeoutException e) {
log.error("Yandex search timeout after {}", fileId);
throw new TimeoutException("Search timeout");
}
}
private String callReverseImageApiByUrl(String imageUrl, String engine, String searchType) throws IOException {
if (searchApiKey == null || searchApiKey.isBlank()) {
throw new IllegalStateException("SearchAPI key not configured");
}
OkHttpClient client = createHttpClient();
HttpUrl url = HttpUrl.parse("https://www.searchapi.io/api/v1/search")
.newBuilder()
.addQueryParameter("engine", engine)
.addQueryParameter("api_key", searchApiKey)
.addQueryParameter("url", imageUrl)
.addQueryParameter("search_type", searchType)
.addQueryParameter("t_", String.valueOf(System.currentTimeMillis()))
.build();
Request request = new Request.Builder()
.url(url)
.header("Accept", "application/json")
.header("User-Agent", "Mozilla/5.0")
.build();
long start = System.currentTimeMillis();
try (Response response = client.newCall(request).execute()) {
ResponseBody body = response.body();
long duration = System.currentTimeMillis() - start;
log.info("SearchAPI response code={}, duration={}ms, engine={}",
response.code(), duration, engine);
if (!response.isSuccessful()) {
String errorBody = response.body() != null ? response.body().string() : "null";
throw new IOException("API error " + response.code() + ": " + errorBody);
}
if (body == null) {
throw new IOException("Empty response body");
}
return body.string();
}
}
public List<SearchResponse.ImageResult> getAllImagesWithoutPagination(String searchApiJson, String findType, String fileId)
throws IOException {
JsonNode root = objectMapper.readTree(searchApiJson);
JsonNode matches = root.path(findType);
List<SearchResponse.ImageResult> allImages = new ArrayList<>();
if (matches.isArray()) {
for (JsonNode match : matches) {
SearchResponse.ImageResult result = mapImageResult(match);
result.setFileId(fileId);
if ("exact_matches".equals(findType)) {
JsonNode thumbnail = match.path("thumbnail");
if (!thumbnail.isMissingNode()) {
String thumbnailUrl = thumbnail.asText();
if (thumbnailUrl.startsWith("data:image")) {
result.setUrl(thumbnailUrl);
} else if (!thumbnailUrl.isBlank()) {
result.setUrl(thumbnailUrl);
}
}
JsonNode imageNode = match.path("image");
if (!imageNode.isMissingNode()) {
String directUrl = imageNode.path("link").asText();
if (directUrl != null && !directUrl.isBlank()) {
result.setUrl(directUrl);
}
}
}
if (result.getUrl() != null && !result.getUrl().isBlank()) {
allImages.add(result);
}
}
}
return allImages;
}
private SearchResponse.ImageResult mapImageResult(JsonNode match) {
SearchResponse.ImageResult result =
new SearchResponse.ImageResult();
JsonNode imageNode = match.path("image");
if (imageNode.isObject()) {
result.setUrl(imageNode.path("link").asText());
result.setWidth(imageNode.path("width").asInt(0));
result.setHeight(imageNode.path("height").asInt(0));
}
result.setPageUrl(match.path("link").asText());
result.setPageTitle(match.path("title").asText());
String source = match.path("source").asText();
result.setHost(extractHostFromSource(source));
return result;
}
private OkHttpClient createHttpClient() {
OkHttpClient.Builder builder = 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);
return builder.build();
}
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;
}
}
@@ -0,0 +1,66 @@
package ru.no_copy.monitoring.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import ru.no_copy.monitoring.dto.MonitoringDTO;
import ru.no_copy.monitoring.dto.SearchResponse;
import ru.no_copy.monitoring.searcher.SearchImageService;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
@Service
@RequiredArgsConstructor
@Slf4j
public class MonitoringService {
private final SearchImageService imageService;
private final ObjectMapper objectMapper;
private final KafkaTemplate<String, Object> kafkaTemplate;
public void execute(String message) throws IOException, TimeoutException {
MonitoringDTO monitoring;
try {
monitoring = objectMapper.readValue(message, MonitoringDTO.class);
log.info("Monitoring object создан: fileId={}, engine={}", monitoring.getFileId(), monitoring.getEngine());
} catch (Exception e) {
log.error("Exception readValue: {}", e.getMessage(), e);
throw new RuntimeException(e);
}
String searchResponse = imageService.searchReverseByPublicUrl(monitoring.getFileId(), monitoring.getBaseUrl(),
monitoring.getEngine(), monitoring.getSearchType());
log.info("Search response: {}", searchResponse);
List<SearchResponse.ImageResult> images =
imageService.getAllImagesWithoutPagination(searchResponse,
monitoring.getSearchType(),
monitoring.getFileId());
log.info("Images count before filter: {}", images.size());
images = images.stream()
.filter(distinctByKey(SearchResponse.ImageResult::getUrl))
.toList();
log.info("Images count after filter: {}", images.size());
for (SearchResponse.ImageResult imageResult: images) {
kafkaTemplate.send("monitoring-results", imageResult);
}
}
private static <T> java.util.function.Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
+44
View File
@@ -0,0 +1,44 @@
spring:
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:kafka:9092}
consumer:
group-id: monitoring-service
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
cloud:
compatibility-verifier:
enabled: false
datasource:
url: jdbc:postgresql://${POSTGRES_HOST:db}:${POSTGRES_PORT:5432}/${POSTGRES_DB:monitoring_db}
username: ${POSTGRES_USER:adminMonitoring}
password: ${POSTGRES_PASSWORD:monitoringDbApp}
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
server:
port: ${SERVER_PORT:8083}
searchapi:
api-key: ${SEARCHAPI_API_KEY:5jyYZC8jSaxhZTwjMUhwtAXi}
reverse-image-url: "https://searchapi.io/api/v1/search"
app:
internal-api-key: "tljzkXiEYF1klSHuG2hPZKjx6EsBX8RQP6UrzMdQanSKbRYuHuOBwrXejZkn7V4FICvIahoDmYD2hjNBPw61NFbGIt4scOzwZpyCiXEa1YKLAeJSPso4S43LIZlKjO4S"
jwt:
secret: Z29nb3Bvd2VycmFuZ2VydHVtYmF5YW1iZjMyNDIyMjh3aW5lcndpbmVy
expiration: 3600000
nocopy-dashboard:
url: http://172.17.0.1:3001