Compare commits

...

29 Commits

Author SHA1 Message Date
SlimusMinus
71e69c4af8 Merge pull request #55 from SlimusMinus/fix/ai-moderation-mapping
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s
fix AI moderation response mapping and long post text
2026-10-20 00:35:17 +03:00
SlimusMinus
a68b89981c fix AI moderation response mapping and long post text
The AI service returns snake_case JSON, so detectedLabels was always null
and blocked posts carried no labels. Map it with @JsonProperty("detected_labels").

Post text longer than the service limit (5000 chars) got 422, which became
AiBadRequestException and the post was rejected. Text is now sent in
overlapping chunks within ai.text-max-length; blank text is skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:33:31 +03:00
SlimusMinus
d63a3309fa Merge pull request #54 from SlimusMinus/image-optimization
All checks were successful
deploy-backend / deploy (push) Successful in 1m30s
compress uploaded images and cache proxied files
2026-10-19 23:45:03 +03:00
SlimusMinus
a564e6f97d compress uploaded images and cache proxied files
Photos from iPhone (3-10 MB, 12-24 MP) were stored and served as-is, so the
feed loaded slowly on first open. Images are now downscaled to 1600px,
rotated by EXIF and re-encoded as progressive JPEG on upload. The
/api/v1/files proxy now sends Cache-Control instead of Spring Security's
no-store, so images are not re-downloaded on every app open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:43:07 +03:00
SlimusMinus
91ceafe75b Merge pull request #53 from SlimusMinus/fix-empty_advert
All checks were successful
deploy-backend / deploy (push) Successful in 1m17s
fixed empty advertising
2026-10-19 01:22:52 +03:00
SlimusMinus
057cdddff6 fixed empty advertising 2026-10-19 01:22:08 +03:00
SlimusMinus
72486a54f7 Merge pull request #52 from SlimusMinus/full-text-search
All checks were successful
deploy-backend / deploy (push) Successful in 2m18s
fixed search and add hints
2026-10-18 23:48:33 +03:00
SlimusMinus
96b4be5e6f fixed search and add hints 2026-10-18 23:46:13 +03:00
SlimusMinus
c1b14da7b9 Merge pull request #51 from SlimusMinus/image-caching
All checks were successful
deploy-backend / deploy (push) Successful in 1m28s
fixed image caching
2026-10-15 01:32:56 +03:00
SlimusMinus
307c4ae432 fixed image caching 2026-10-15 01:32:17 +03:00
SlimusMinus
4d9cb9946d Merge pull request #50 from SlimusMinus/fix-ai_timeout
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s
fixed ai image timeout
2026-10-15 00:49:40 +03:00
SlimusMinus
c83d41a036 fixed ai image timeout 2026-10-15 00:48:58 +03:00
SlimusMinus
13bb0c8503 Merge pull request #49 from SlimusMinus/add-adr_post
All checks were successful
deploy-backend / deploy (push) Successful in 2m9s
fixed address for map
2026-10-15 00:14:02 +03:00
SlimusMinus
03e2b36c8d fixed address for map 2026-10-15 00:13:19 +03:00
SlimusMinus
f8ccb15185 Merge pull request #48 from SlimusMinus/fix-address
All checks were successful
deploy-backend / deploy (push) Successful in 1m57s
fixed address for map
2026-10-15 00:02:58 +03:00
SlimusMinus
01ac227bdb fixed address for map 2026-10-15 00:02:10 +03:00
SlimusMinus
9eae82f6df Merge pull request #47 from SlimusMinus/chat-on-first-message
All checks were successful
deploy-backend / deploy (push) Successful in 1m23s
create chats only together with the first message
2026-10-13 01:50:06 +03:00
SlimusMinus
cd0d2a4081 create chats only together with the first message
- GET /api/v1/chats/with/{otherUserId}?postId= finds an existing chat
  (404 if there is none) and never creates one
- POST /api/v1/chats/with/{otherUserId}/messages?postId= with {content}
  finds or creates the chat and saves the first message in one
  transaction; same participant/post checks as before, WebSocket events
  still sent after commit
- the old POST /with/{otherUserId} that created empty chats is removed
- chat list hides chats without messages (existing empty rows stay in DB)
- empty messages are rejected with 400

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:45:18 +03:00
SlimusMinus
73463f6c5b Merge pull request #46 from SlimusMinus/fix-chat-per-post
All checks were successful
deploy-backend / deploy (push) Successful in 1m21s
Fix chat per post
2026-10-13 01:34:17 +03:00
SlimusMinus
da7d68c31a add ChatService tests for creating a chat about an ad
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:31:33 +03:00
SlimusMinus
45c4273ea8 fix chats: one chat per ad, ordering, delivery after commit, errors
A chat was unique per user pair, so contacting the same author about a
second ad returned the old chat with the old post_id, and the chat list
showed the other ad's title and image.

- chats are unique per (user_one_id, user_two_id, post_id); migration 015
  drops the old pair constraint whatever its name and adds the new one
- getOrCreateChat looks the chat up by users and post, and checks that the
  other user exists and the post belongs to one of the participants
- chat list is sorted by last message time (chat creation as fallback)
- WebSocket message and unread events are sent only after commit
- chat errors are ApiException: 404 not found, 403 not a participant,
  400 validation; messages are limited to 4000 characters
- Post.images ordered by id so the cover image is stable everywhere

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:23:09 +03:00
SlimusMinus
008852c781 Merge pull request #45 from SlimusMinus/fix-feed-pagination
All checks were successful
deploy-backend / deploy (push) Successful in 1m23s
fix feed pagination order, moderation reject and cache invalidation
2026-10-13 01:10:47 +03:00
SlimusMinus
d19f03d412 fix feed pagination order, moderation reject and cache invalidation
- getFeed: add id DESC as tie-breaker so posts with equal createdAt
  are not duplicated or lost between pages
- moderation: AI verdict false now sets REJECTED instead of ACTIVE
- nightly cleanup: invalidate feed and map caches after deleting posts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:07:26 +03:00
SlimusMinus
5ea7b438f5 Merge pull request #44 from SlimusMinus/fix-get_image
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
fixed getting image from minio
2026-10-13 00:43:45 +03:00
SlimusMinus
9dbf2dd043 fixed getting image from minio 2026-10-13 00:43:06 +03:00
SlimusMinus
e321fa4c60 Merge pull request #43 from SlimusMinus/add-timezone
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
added timezone for all create date
2026-10-11 23:26:58 +03:00
SlimusMinus
4119b767c3 added timezone for all create date 2026-10-11 23:26:11 +03:00
SlimusMinus
68d53fadf3 Merge pull request #42 from SlimusMinus/go-to_test
Add Docker build and deploy pipeline
2026-10-08 01:23:01 +03:00
SlimusMinus
818c8f6a11 Add Docker build and deploy pipeline
All checks were successful
deploy-backend / deploy (push) Successful in 8m24s
2026-10-07 22:56:56 +03:00
68 changed files with 2902 additions and 110 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
.git
.gradle
build
target
.idea

39
.env.example Normal file
View File

@@ -0,0 +1,39 @@
# Шаблон переменных окружения. Скопируй в .env и заполни значениями.
# Сам .env добавлен в .gitignore и не должен попадать в репозиторий.
#
# Как приложение их получает:
# docker compose читает .env автоматически;
# Spring Boot — нет. Нужно экспортировать переменные в терминал
# или прописать их в Environment variables в настройках запуска IDE.
# --- Обязательные: без них приложение не стартует ---
# Ключи доступа к MinIO (S3-совместимое хранилище).
# ВНИМАНИЕ: они должны совпадать с MINIO_ACCESS_KEY / MINIO_SECRET_KEY
# в docker-compose.yaml, иначе приложение не подключится к MinIO.
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
# Пароль Redis. Тот же, что в docker-compose.yaml.
# docker-compose падает с понятной ошибкой, если переменная пустая.
REDIS_PASSWORD=
# --- Рекомендуется задать ---
# Секрет подписи JWT. Без переменной берётся захардкоженное значение
# из application.yaml — подделать такой токен может кто угодно.
# Сгенерировать, например, так:
# openssl rand -base64 48
JWT_SECRET=
# --- Необязательно: есть значения по умолчанию ---
# REDIS_HOST=localhost
# MINIO_ENDPOINT=http://localhost:9010
# MINIO_BUCKET=refound-images
# MINIO_ADS_BUCKET=ads-media
# MINIO_REGION=us-east-1
# AI_SERVICE_URL=http://localhost:8000
# JWT_ACCESS_EXPIRATION=900000
# JWT_REFRESH_EXPIRATION=604800000
# JPA_DDL_AUTO=validate

View File

@@ -0,0 +1,16 @@
name: deploy-backend
on:
push:
branches: [main]
jobs:
deploy:
runs-on: host
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t nakhodka-backend:latest -t nakhodka-backend:${{ github.sha }} .
- name: Restart backend
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
- name: Cleanup
run: docker image prune -f

18
Dockerfile Normal file
View File

@@ -0,0 +1,18 @@
FROM eclipse-temurin:25-jdk AS build
WORKDIR /app
COPY . .
RUN sed -i 's/\r$//' gradlew \
&& chmod +x gradlew \
&& ./gradlew bootJar --no-daemon -x test \
&& cp "$(ls build/libs/*.jar | grep -v plain | head -n1)" /app/app.jar
FROM eclipse-temurin:25-jre
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -r -u 1001 app
WORKDIR /app
COPY --from=build /app/app.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-Xmx768m", "-jar", "app.jar"]

View File

@@ -52,6 +52,11 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.minio:minio:8.6.0' implementation 'io.minio:minio:8.6.0'
// Сжатие картинок при загрузке: ресайз + поворот по EXIF, чтение WebP/CMYK-JPEG
implementation 'net.coobird:thumbnailator:0.4.20'
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.12.0'
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.12.0'
// JWT // JWT
implementation 'io.jsonwebtoken:jjwt-api:0.12.5' implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5'
@@ -70,6 +75,10 @@ dependencies {
runtimeOnly 'org.postgresql:postgresql' runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
// Поиск опирается на возможности PostgreSQL (стемминг, tsvector, pg_trgm) — тестируем на настоящей БД
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
} }

View File

@@ -3,6 +3,7 @@ package com.krylov.refound;
import com.krylov.refound.ai.config.AiProperties; import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.AiRetryProperties; import com.krylov.refound.ai.config.AiRetryProperties;
import com.krylov.refound.config.MinioProperties; import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.search.SearchProperties;
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration; import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -15,7 +16,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
scanBasePackages = "com.krylov.refound", scanBasePackages = "com.krylov.refound",
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class } exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
)@EnableScheduling )@EnableScheduling
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class}) @EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
SearchProperties.class})
@EnableRetry @EnableRetry
public class ReFoundApplication { public class ReFoundApplication {

View File

@@ -0,0 +1,38 @@
package com.krylov.refound.ai.client;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import java.util.concurrent.TimeoutException;
/**
* Перевод ошибок WebClient в исключения AI-клиента.
*/
final class AiClientErrors {
private AiClientErrors() {
}
/**
* Ошибки статуса (onStatus) уже пришли как AiException — их не трогаем.
* Таймаут ответа → AiTimeoutException, прочие сетевые ошибки → AiUnavailableException.
*/
static AiException translate(Exception ex) {
if (ex instanceof AiException aiException) {
return aiException;
}
if (isTimeout(ex)) {
return new AiTimeoutException(ex);
}
return new AiUnavailableException(ex);
}
static boolean isTimeout(Throwable ex) {
for (Throwable t = ex; t != null; t = t.getCause()) {
if (t instanceof io.netty.handler.timeout.TimeoutException || t instanceof TimeoutException) {
return true;
}
}
return false;
}
}

View File

@@ -1,14 +1,15 @@
package com.krylov.refound.ai.client; package com.krylov.refound.ai.client;
import com.krylov.refound.ai.exception.AiBadRequestException; import com.krylov.refound.ai.exception.AiBadRequestException;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiServerException; import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException; import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatusCode; import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
@Slf4j @Slf4j
@Component @Component
@@ -39,13 +40,16 @@ public class AiHttpClient {
log.info("AI response received"); log.info("AI response received");
return response; return response;
} catch (WebClientRequestException ex) {
log.error("AI connection failed", ex);
throw new AiUnavailableException(ex);
} catch (Exception ex) { } catch (Exception ex) {
log.error("AI request failed", ex); AiException error = AiClientErrors.translate(ex);
throw new AiUnavailableException(ex); if (error instanceof AiTimeoutException) {
log.warn("AI text moderation did not respond in time");
} else if (error instanceof AiUnavailableException) {
log.warn("AI text moderation is unavailable: {}", ex.getMessage());
} else {
log.warn("AI text moderation returned an error: {}", error.getMessage());
}
throw error;
} }
} }
} }

View File

@@ -1,8 +1,13 @@
package com.krylov.refound.ai.client; package com.krylov.refound.ai.client;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.exception.AiBadRequestException; import com.krylov.refound.ai.exception.AiBadRequestException;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiServerException; import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException; import com.krylov.refound.ai.exception.AiUnavailableException;
import java.io.IOException;
import java.time.Duration;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
@@ -12,19 +17,28 @@ import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException; import reactor.netty.http.client.HttpClientRequest;
@Slf4j @Slf4j
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class AiMultipartHttpClient { public class AiMultipartHttpClient {
private final WebClient aiWebClient; private final WebClient aiWebClient;
private final AiProperties properties;
public <R> R post(String uri, MultipartFile file, Class<R> responseType) { public <R> R post(String uri, MultipartFile file, Class<R> responseType) {
log.info("AI IMAGE POST {}", uri); log.info("AI IMAGE POST {}", uri);
byte[] bytes;
try {
bytes = file.getBytes();
} catch (IOException ex) {
throw new IllegalStateException("Cannot read image for AI moderation", ex);
}
Duration timeout = Duration.ofSeconds(properties.getImageTimeout());
try { try {
MultipartBodyBuilder builder = new MultipartBodyBuilder(); MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("file", new ByteArrayResource(file.getBytes()) { builder.part("file", new ByteArrayResource(bytes) {
@Override @Override
public String getFilename() { public String getFilename() {
return file.getOriginalFilename(); return file.getOriginalFilename();
@@ -36,6 +50,8 @@ public class AiMultipartHttpClient {
.uri(uri) .uri(uri)
.contentType(MediaType.MULTIPART_FORM_DATA) .contentType(MediaType.MULTIPART_FORM_DATA)
.bodyValue(builder.build()) .bodyValue(builder.build())
// Картинки обрабатываются дольше текста — свой таймаут ответа
.httpRequest(req -> ((HttpClientRequest) req.getNativeRequest()).responseTimeout(timeout))
.retrieve() .retrieve()
.onStatus( .onStatus(
HttpStatusCode::is4xxClientError, HttpStatusCode::is4xxClientError,
@@ -51,12 +67,16 @@ public class AiMultipartHttpClient {
.block(); .block();
log.info("AI image response received"); log.info("AI image response received");
return response; return response;
} catch (WebClientRequestException ex) {
log.error("WebClientRequestException in AiMultipartHttpClient {}", ex.getMessage(), ex);
throw new AiUnavailableException(ex);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Exception in AiMultipartHttpClient {}", ex.getMessage(), ex); AiException error = AiClientErrors.translate(ex);
throw new RuntimeException("Cannot send image to AI", ex); if (error instanceof AiTimeoutException) {
log.warn("AI image moderation did not respond within {}s", timeout.toSeconds());
} else if (error instanceof AiUnavailableException) {
log.warn("AI image moderation is unavailable: {}", ex.getMessage());
} else {
log.warn("AI image moderation returned an error: {}", error.getMessage());
}
throw error;
} }
} }
} }

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.ai.client;
import com.krylov.refound.ai.dto.ImageModerationResponse; import com.krylov.refound.ai.dto.ImageModerationResponse;
import com.krylov.refound.ai.exception.AiServerException; import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException; import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -18,7 +19,7 @@ public class ImageModerationClient {
private final AiMultipartHttpClient client; private final AiMultipartHttpClient client;
@Retryable( @Retryable(
retryFor = {AiUnavailableException.class, AiServerException.class}, retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
maxAttempts = 3, maxAttempts = 3,
backoff = @Backoff(delay = 500, multiplier = 2) backoff = @Backoff(delay = 500, multiplier = 2)
) )
@@ -27,16 +28,25 @@ public class ImageModerationClient {
return client.post("/api/v1/moderation/image", file, ImageModerationResponse.class); return client.post("/api/v1/moderation/image", file, ImageModerationResponse.class);
} }
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
// проверяется снова при следующем запуске планировщика.
@Recover @Recover
public ImageModerationResponse recover(AiUnavailableException e, MultipartFile file) { public ImageModerationResponse recover(AiUnavailableException e, MultipartFile file) {
log.error("AI ImageModeration unavailable after retries", e); log.error("AI ImageModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
return null;
}
@Recover
public ImageModerationResponse recover(AiTimeoutException e, MultipartFile file) {
log.error("AI ImageModeration timed out after retries");
return null; return null;
} }
@Recover @Recover
public ImageModerationResponse recover(AiServerException e, MultipartFile file) { public ImageModerationResponse recover(AiServerException e, MultipartFile file) {
log.error("AI ImageModeration server error after retries", e); log.error("AI ImageModeration server error after retries: {}", e.getMessage());
return null; return null;
} }

View File

@@ -3,6 +3,7 @@ package com.krylov.refound.ai.client;
import com.krylov.refound.ai.dto.ModerationResponse; import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.dto.TextModerationRequest; import com.krylov.refound.ai.dto.TextModerationRequest;
import com.krylov.refound.ai.exception.AiServerException; import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException; import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -19,7 +20,7 @@ public class TextModerationClient {
private final AiHttpClient client; private final AiHttpClient client;
@Retryable( @Retryable(
retryFor = {AiUnavailableException.class, AiServerException.class}, retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
maxAttempts = 3, maxAttempts = 3,
backoff = @Backoff(delay = 500, multiplier = 2) backoff = @Backoff(delay = 500, multiplier = 2)
) )
@@ -28,16 +29,25 @@ public class TextModerationClient {
return client.post("/api/v1/moderation/text", new TextModerationRequest(text), ModerationResponse.class); return client.post("/api/v1/moderation/text", new TextModerationRequest(text), ModerationResponse.class);
} }
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
// проверяется снова при следующем запуске планировщика.
@Recover @Recover
public ModerationResponse recover(AiUnavailableException e, String text) { public ModerationResponse recover(AiUnavailableException e, String text) {
log.error("AI TextModeration unavailable after retries", e); log.error("AI TextModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
return null;
}
@Recover
public ModerationResponse recover(AiTimeoutException e, String text) {
log.error("AI TextModeration timed out after retries");
return null; return null;
} }
@Recover @Recover
public ModerationResponse recover(AiServerException e, String text) { public ModerationResponse recover(AiServerException e, String text) {
log.error("AI TextModeration server error after retries", e); log.error("AI TextModeration server error after retries: {}", e.getMessage());
return null; return null;
} }

View File

@@ -19,4 +19,17 @@ public class AiProperties {
* 10 seconds * 10 seconds
*/ */
private int timeout; private int timeout;
/**
* Таймаут ответа для модерации изображений, секунды. Картинки AI-сервис
* обрабатывает заметно дольше текста, особенно первую после простоя.
*/
private int imageTimeout = 30;
/**
* Максимальная длина текста в одном запросе к AI-сервису (TEXT_MAX_LENGTH
* на его стороне). Более длинный текст отправляется частями — иначе сервис
* отвечает 422, и пост ошибочно отклоняется.
*/
private int textMaxLength = 5000;
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto; package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List; import java.util.List;
import lombok.Data; import lombok.Data;
@@ -11,5 +12,7 @@ public class ImageModerationResponse {
private String reason; private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels; private List<String> detectedLabels;
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto; package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List; import java.util.List;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
@@ -14,6 +15,8 @@ public class ModerationResponse {
private String reason; private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels; private List<String> detectedLabels;
} }

View File

@@ -1,8 +1,11 @@
package com.krylov.refound.ai.pipeline; package com.krylov.refound.ai.pipeline;
import com.krylov.refound.ai.client.TextModerationClient; import com.krylov.refound.ai.client.TextModerationClient;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.dto.ModerationResponse; import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.exception.ContentBlockedException; import com.krylov.refound.ai.exception.ContentBlockedException;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@@ -14,7 +17,13 @@ import org.springframework.stereotype.Component;
@Order(10) @Order(10)
public class TextModerationProcessor implements ModerationProcessor { public class TextModerationProcessor implements ModerationProcessor {
/**
* Перекрытие соседних частей: фраза на стыке целиком попадает хотя бы в одну.
*/
static final int CHUNK_OVERLAP = 200;
private final TextModerationClient client; private final TextModerationClient client;
private final AiProperties properties;
@Override @Override
public Boolean process(ModerationContext context) { public Boolean process(ModerationContext context) {
@@ -24,7 +33,23 @@ public class TextModerationProcessor implements ModerationProcessor {
context.getDescription() context.getDescription()
); );
ModerationResponse response = client.moderate(text); // Пустой текст AI-сервис отклоняет как невалидный запрос (400/422) —
// проверять нечего, это не повод отклонять пост
if (text.isBlank()) {
log.info("Текст поста пустой, пропускаем модерацию текста");
return Boolean.TRUE;
}
List<String> chunks = splitText(text, properties.getTextMaxLength(), CHUNK_OVERLAP);
if (chunks.size() > 1) {
log.info("Текст длиной {} отправляется на модерацию частями: {}", text.length(), chunks.size());
}
for (String chunk : chunks) {
if (chunk.isBlank()) {
continue;
}
ModerationResponse response = client.moderate(chunk);
if (response == null) { if (response == null) {
log.warn("AI TextModeration вернул null, пропускаем модерацию текста"); log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
return null; return null;
@@ -35,10 +60,49 @@ public class TextModerationProcessor implements ModerationProcessor {
if (!Boolean.TRUE.equals(response.getApproved())) { if (!Boolean.TRUE.equals(response.getApproved())) {
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels()); throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
} }
}
return Boolean.TRUE; return Boolean.TRUE;
} }
/**
* Режет текст на части не длиннее maxLength с перекрытием overlap.
* Граница по возможности ставится на пробел, чтобы не разрезать слово.
*/
static List<String> splitText(String text, int maxLength, int overlap) {
if (text.length() <= maxLength) {
return List.of(text);
}
int safeOverlap = Math.min(overlap, maxLength / 4);
List<String> chunks = new ArrayList<>();
int start = 0;
while (start < text.length()) {
int end = Math.min(start + maxLength, text.length());
if (end < text.length()) {
int space = lastWhitespace(text, start + maxLength / 2, end);
if (space > 0) {
end = space;
}
}
chunks.add(text.substring(start, end));
if (end == text.length()) {
break;
}
start = Math.max(end - safeOverlap, start + 1);
}
return chunks;
}
private static int lastWhitespace(String text, int from, int to) {
for (int i = to - 1; i >= from; i--) {
if (Character.isWhitespace(text.charAt(i))) {
return i;
}
}
return -1;
}
private String buildText(String title, String description) { private String buildText(String title, String description) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();

View File

@@ -0,0 +1,32 @@
package com.krylov.refound.config;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Кладёт таймзону из заголовка {@code X-Timezone} в {@link TimeZoneContext} на
* время обработки запроса. Благодаря этому время создания сущностей
* (createdAt и т.п.) ставится по зоне клиента, а не по зоне сервера.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TimeZoneFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
TimeZoneContext.set(request.getHeader(TimeZoneContext.HEADER));
filterChain.doFilter(request, response);
} finally {
TimeZoneContext.clear();
}
}
}

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.MessageDto; import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.dto.StartChatRequest;
import com.krylov.refound.service.ChatService; import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService; import com.krylov.refound.service.UserService;
import java.util.List; import java.util.List;
@@ -11,11 +12,13 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -29,12 +32,21 @@ public class ChatController {
private final UserService userService; private final UserService userService;
private final ChatService chatService; private final ChatService chatService;
// Создать чат с пользователем или получить существующий // Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
@PostMapping("/with/{otherUserId}") @GetMapping("/with/{otherUserId}")
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) { public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth); Long currentUserId = extractUserId(auth);
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId); log.info("findChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.getOrCreateChat(currentUserId, otherUserId, postId); return ResponseEntity.of(chatService.findChat(currentUserId, otherUserId, postId));
}
// Первое сообщение: чат создаётся (или находится) вместе с сообщением — пустых чатов не бывает
@PostMapping("/with/{otherUserId}/messages")
public ChatDto startChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId,
@RequestBody StartChatRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("startChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
} }
// Список всех чатов текущего пользователя // Список всех чатов текущего пользователя

View File

@@ -1,7 +1,9 @@
package com.krylov.refound.controller; package com.krylov.refound.controller;
import com.krylov.refound.dto.SendMessageRequest; import com.krylov.refound.dto.SendMessageRequest;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.service.ChatService; import com.krylov.refound.service.ChatService;
import com.krylov.refound.util.TimeZoneContext;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -43,10 +45,14 @@ public class ChatWebSocketController {
} }
try { try {
Object timezone = sessionAttributes.get(TimeZoneContext.SESSION_ATTRIBUTE);
TimeZoneContext.set(timezone instanceof String tz ? tz : null);
chatService.sendMessage(senderId, request.getChatId(), request.getContent()); chatService.sendMessage(senderId, request.getChatId(), request.getContent());
} catch (SecurityException | IllegalArgumentException e) { } catch (ApiException | IllegalArgumentException e) {
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage() messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
); );
} finally {
TimeZoneContext.clear();
} }
} }
} }

View File

@@ -1,8 +1,12 @@
package com.krylov.refound.controller; package com.krylov.refound.controller;
import com.krylov.refound.service.FileStorageService; import com.krylov.refound.service.FileStorageService;
import java.time.Duration;
import java.util.Map;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -18,6 +22,12 @@ import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/api/v1/files") @RequestMapping("/api/v1/files")
@RequiredArgsConstructor @RequiredArgsConstructor
public class FileStorageController { public class FileStorageController {
/**
* Сколько браузер помнит редирект на presigned URL и не ходит за ним на бэк.
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
*/
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
private final FileStorageService fileStorageService; private final FileStorageService fileStorageService;
@PostMapping @PostMapping
@@ -34,6 +44,35 @@ public class FileStorageController {
return fileStorageService.downloadFile(key); return fileStorageService.downloadFile(key);
} }
/**
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
* Ссылка стабильна (кэшируется) и сам редирект кэшируется браузером — повторный
* показ картинки не требует ни запроса на бэк, ни повторной загрузки.
*/
@GetMapping(value = "/{*objectName}", params = "presigned=true")
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
return ResponseEntity.status(302)
.header(HttpHeaders.LOCATION, url)
.cacheControl(CacheControl.maxAge(REDIRECT_CACHE_MAX_AGE).cachePrivate())
.build();
}
/**
* Возвращает presigned URL в JSON.
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
*/
@GetMapping("/url/{*objectName}")
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
Duration ttl = ttlHours > 0 ? Duration.ofHours(ttlHours) : Duration.ofHours(24);
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
return ResponseEntity.ok(Map.of("url", url));
}
@DeleteMapping("/{*objectName}") @DeleteMapping("/{*objectName}")
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) { public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
log.info("deleteFile {}", objectName); log.info("deleteFile {}", objectName);

View File

@@ -3,6 +3,10 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.PostRequest; import com.krylov.refound.dto.PostRequest;
import com.krylov.refound.dto.PostResponse; import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.dto.StatusUpdateRequest; import com.krylov.refound.dto.StatusUpdateRequest;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.PostService; import com.krylov.refound.service.PostService;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -11,6 +15,7 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -32,6 +37,7 @@ import org.springframework.web.multipart.MultipartFile;
public class PostController { public class PostController {
private final PostService service; private final PostService service;
private final SearchSuggestService searchSuggestService;
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) { public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
@@ -40,9 +46,26 @@ public class PostController {
} }
@GetMapping @GetMapping
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) { public Page<PostResponse> getFeed(@RequestParam(required = false) String search,
log.info("get all feed"); @RequestParam(required = false) String type,
return service.getFeed(search, pageable); @RequestParam(name = "category", required = false) List<String> categories,
@RequestParam(name = "city", required = false) List<String> cities,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get feed: search='{}', type={}, categories={}, cities={}", search, type, categories, cities);
PostFeedFilter filter;
try {
filter = PostFeedFilter.of(type, categories, cities);
} catch (IllegalArgumentException e) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Некорректный фильтр ленты: " + e.getMessage(),
HttpStatus.BAD_REQUEST);
}
return service.getFeed(search, filter, pageable);
}
/** Подсказки для последнего слова строки поиска: «потерян барс» → [барсетка, барсик]. */
@GetMapping("/search/suggest")
public List<String> suggest(@RequestParam(name = "q", defaultValue = "") String query) {
return searchSuggestService.suggest(query);
} }
@GetMapping("/{id:\\d+}") @GetMapping("/{id:\\d+}")

View File

@@ -39,7 +39,8 @@ public class AdvertisingController {
log.info("getNextAdvertising"); log.info("getNextAdvertising");
Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request); Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request);
if (selected.isEmpty()) { if (selected.isEmpty()) {
log.warn("failed get advertising"); // Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
log.debug("No advertising to show, returning 204");
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }

View File

@@ -16,6 +16,7 @@ public class PostResponse {
private String category; private String category;
private String city; private String city;
private String district; private String district;
private String address;
// Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку // Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку
// объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал // объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал
// null, и MapView падал на дефолтный центр. // null, и MapView падал на дефолтный центр.

View File

@@ -0,0 +1,9 @@
package com.krylov.refound.dto;
import lombok.Data;
/** Первое сообщение, с которым создаётся чат. */
@Data
public class StartChatRequest {
private String content;
}

View File

@@ -27,6 +27,7 @@ public class AdminPostResponse {
private String category; private String category;
private String city; private String city;
private String district; private String district;
private String address;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
private String phone; private String phone;

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity; package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
@@ -18,7 +19,7 @@ import lombok.ToString;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
@Entity @Entity
@Table(name = "chats", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_one_id", "user_two_id"})}) @Table(name = "chats", uniqueConstraints = {@UniqueConstraint(name = "uq_chat_users_post", columnNames = {"user_one_id", "user_two_id", "post_id"})})
@Getter @Getter
@Setter @Setter
@ToString @ToString
@@ -42,7 +43,7 @@ public class Chat {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
@Override @Override

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity; package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
@@ -38,6 +39,6 @@ public class Message {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }

View File

@@ -14,6 +14,7 @@ import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
@@ -37,6 +38,9 @@ public class Post {
private PostCategory category; private PostCategory category;
private String city; private String city;
private String district; private String district;
// Полный адрес из формы; city/district — нормализованные данные геокодера
@Column(length = 500)
private String address;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
private LocalDateTime createdAt; private LocalDateTime createdAt;
@@ -58,7 +62,9 @@ public class Post {
@JsonIgnore @JsonIgnore
private User user; private User user;
// Порядок загрузки: первая картинка (обложка в ленте, чатах, на карте) должна быть стабильной
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private List<Image> images = new ArrayList<>(); private List<Image> images = new ArrayList<>();
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity; package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue; import jakarta.persistence.GeneratedValue;
@@ -34,6 +35,6 @@ public class Review {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.entity; package com.krylov.refound.entity;
import com.krylov.refound.enums.Role; import com.krylov.refound.enums.Role;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EnumType; import jakarta.persistence.EnumType;
@@ -36,6 +37,6 @@ public class User {
@PrePersist @PrePersist
public void prePersist() { public void prePersist() {
this.createdAt = LocalDateTime.now(); this.createdAt = TimeZoneContext.now();
} }
} }

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.AdvertisingType; import com.krylov.refound.enums.advertising.AdvertisingType;
import com.krylov.refound.enums.advertising.TranscodingStatus; import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -60,7 +61,7 @@ public class Advertising {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (createdAt == null) { if (createdAt == null) {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.entity.advertising; package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.CampaignStatus; import com.krylov.refound.enums.advertising.CampaignStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -48,7 +49,7 @@ public class Campaign {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (createdAt == null) { if (createdAt == null) {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity.advertising; package com.krylov.refound.entity.advertising;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -32,7 +33,7 @@ public class Click {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (clickedAt == null) { if (clickedAt == null) {
clickedAt = LocalDateTime.now(); clickedAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.FullscreenAdStatus; import com.krylov.refound.enums.advertising.FullscreenAdStatus;
import com.krylov.refound.enums.advertising.TranscodingStatus; import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -38,7 +39,7 @@ public class FullscreenAdvertising {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (createdAt == null) { if (createdAt == null) {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity.advertising; package com.krylov.refound.entity.advertising;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -32,7 +33,7 @@ public class Impression {
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (shownAt == null) { if (shownAt == null) {
shownAt = LocalDateTime.now(); shownAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -10,16 +10,20 @@ import org.springframework.data.repository.query.Param;
public interface ChatRepository extends JpaRepository<Chat, Long> { public interface ChatRepository extends JpaRepository<Chat, Long> {
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2") /** Чат пары пользователей по конкретному объявлению (postId == null — чат без объявления). */
Optional<Chat> findByUsers(Long u1, Long u2); @Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2 "
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */ /** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c " @Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)") + "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
boolean isParticipantOfChat(Long chatId, Long userId); boolean isParticipantOfChat(Long chatId, Long userId);
@Query("SELECT c FROM Chat c WHERE c.userOneId = :userId OR c.userTwoId = :userId ORDER BY c.createdAt DESC") /** Чаты пользователя, в которых есть хотя бы одно сообщение (пустые в списке не показываем). */
List<Chat> findAllByUserId(Long userId); // Changed from Optional to List @Query("SELECT c FROM Chat c WHERE (c.userOneId = :userId OR c.userTwoId = :userId) "
+ "AND EXISTS (SELECT 1 FROM Message m WHERE m.chatId = c.id) ORDER BY c.createdAt DESC")
List<Chat> findAllByUserId(Long userId);
/** /**
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась. * Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.

View File

@@ -0,0 +1,77 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostCategory;
import com.krylov.refound.enums.PostType;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;
/**
* Фильтры публичной ленты: тип объявления, категории, города.
* Пустые значения означают «без ограничения».
*
* @param cities названия городов/районов в нижнем регистре
*/
public record PostFeedFilter(PostType type, Set<PostCategory> categories, Set<String> cities) {
public static final PostFeedFilter NONE = new PostFeedFilter(null, Set.of(), Set.of());
public PostFeedFilter {
categories = categories == null ? Set.of() : Set.copyOf(categories);
cities = cities == null ? Set.of() : Set.copyOf(cities);
}
/**
* Собирает фильтр из параметров запроса. Тип принимается в любом регистре
* ("loss"/"LOSS"), категории — именем enum (ANIMAL) или как на фронте («Питомец»).
* Неизвестные значения — 400 через IllegalArgumentException.
*/
public static PostFeedFilter of(String type, Collection<String> categories, Collection<String> cities) {
PostType postType = StringUtils.hasText(type) ? PostType.from(type.trim()) : null;
Set<PostCategory> postCategories = categories == null ? Set.of() : categories.stream()
.filter(StringUtils::hasText)
.flatMap(value -> Arrays.stream(value.split(",")))
.map(String::trim)
.filter(StringUtils::hasText)
.map(PostFeedFilter::parseCategory)
.collect(Collectors.toCollection(LinkedHashSet::new));
Set<String> cityNames = cities == null ? Set.of() : cities.stream()
.filter(StringUtils::hasText)
.map(city -> city.trim().toLowerCase(Locale.ROOT))
.collect(Collectors.toCollection(LinkedHashSet::new));
return new PostFeedFilter(postType, postCategories, cityNames);
}
public boolean isEmpty() {
return type == null && categories.isEmpty() && cities.isEmpty();
}
/** Стабильное представление для ключа кэша. */
public String cacheKeyPart() {
return "type=" + Objects.toString(type, "")
+ ":cat=" + categories.stream().map(Enum::name).sorted().collect(Collectors.joining(","))
+ ":city=" + cities.stream().sorted().collect(Collectors.joining(","));
}
private static PostCategory parseCategory(String value) {
for (PostCategory category : PostCategory.values()) {
if (category.name().equalsIgnoreCase(value)) {
return category;
}
}
return PostCategory.fromDisplayName(value);
}
public List<String> categoryNames() {
return categories.stream().map(Enum::name).toList();
}
}

View File

@@ -0,0 +1,129 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* Нативные запросы полнотекстового поиска по объявлениям (PostgreSQL).
* Возвращает только id в нужном порядке — сами посты грузит JPA.
*/
@Repository
@RequiredArgsConstructor
public class PostSearchRepository {
/** Должно совпадать с выражением индекса idx_posts_title_trgm (changelog 019). */
private static final String TITLE_TRGM = "translate(lower(p.title), 'ё', 'е')";
private final NamedParameterJdbcTemplate jdbc;
/** Разобранный пользовательский ввод в виде текста tsquery ("" — нет значимых слов). */
public record ParsedQuery(String full, String rest, String prefix, String titlePrefix) {
}
/**
* websearch_to_tsquery не падает на спецсимволах и понимает "кавычки", -минус и or.
* rest — запрос без последнего слова, prefix — последнее слово как префикс ('кош':*),
* titlePrefix — тот же префикс, но только среди слов заголовка ('кош':*A, вес A — заголовок).
*/
public ParsedQuery parse(String text, String rest, String prefixWord) {
MapSqlParameterSource params = new MapSqlParameterSource()
.addValue("text", text)
.addValue("rest", rest == null ? "" : rest)
// prefixWord заранее очищен до букв и цифр — to_tsquery на нём не упадёт
.addValue("prefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*")
.addValue("titlePrefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*A");
return jdbc.queryForObject("""
select websearch_to_tsquery('russian', :text)::text as full_q,
websearch_to_tsquery('russian', :rest)::text as rest_q,
case when :prefix = '' then '' else to_tsquery('russian', :prefix)::text end as prefix_q,
case when :titlePrefix = '' then '' else to_tsquery('russian', :titlePrefix)::text end as title_prefix_q
""", params, (rs, i) -> new ParsedQuery(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4)));
}
/** Слово → его лексемы по русскому стеммеру (для синонимов). */
public List<String> lexemes(String word) {
return jdbc.queryForList(
"select lexeme from unnest(to_tsvector('russian', :word)) order by lexeme",
new MapSqlParameterSource("word", word), String.class);
}
public long countFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter) {
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", tsquery);
return jdbc.queryForObject("select count(*) from posts p where p.search_vector @@ cast(:q as tsquery)"
+ filters(filter), params, Long.class);
}
/** Совпадения в заголовке (вес A) ранжируются выше, чем в описании (вес B). */
public List<Long> findFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter,
long offset, int limit) {
MapSqlParameterSource params = baseParams(statuses, filter)
.addValue("q", tsquery)
.addValue("offset", offset)
.addValue("limit", limit);
return jdbc.queryForList("select p.id from posts p where p.search_vector @@ cast(:q as tsquery)"
+ filters(filter)
+ " order by ts_rank_cd(p.search_vector, cast(:q as tsquery)) desc, p.created_at desc, p.id desc"
+ " limit :limit offset :offset", params, Long.class);
}
/**
* Поиск с опечатками по заголовку. Порог задаётся на транзакцию, поэтому
* методы *Typo вызываются внутри @Transactional — иначе set_config не
* действует на следующий запрос. Оператор &lt;% использует GIN-индекс.
*/
public void setTypoThreshold(double threshold) {
jdbc.queryForObject("select set_config('pg_trgm.word_similarity_threshold', :t, true)",
new MapSqlParameterSource("t", Double.toString(threshold)), String.class);
}
public long countTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter) {
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", normalizeForTrgm(text));
return jdbc.queryForObject("select count(*) from posts p where :q <% " + TITLE_TRGM
+ filters(filter), params, Long.class);
}
public List<Long> findTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter,
long offset, int limit) {
MapSqlParameterSource params = baseParams(statuses, filter)
.addValue("q", normalizeForTrgm(text))
.addValue("offset", offset)
.addValue("limit", limit);
return jdbc.queryForList("select p.id from posts p where :q <% " + TITLE_TRGM
+ filters(filter)
+ " order by word_similarity(:q, " + TITLE_TRGM + ") desc, p.created_at desc, p.id desc"
+ " limit :limit offset :offset", params, Long.class);
}
static String normalizeForTrgm(String text) {
return text.toLowerCase(Locale.ROOT).replace('ё', 'е').trim();
}
private static MapSqlParameterSource baseParams(Collection<PostStatus> statuses, PostFeedFilter filter) {
return new MapSqlParameterSource()
.addValue("statuses", statuses.stream().map(Enum::name).toList())
.addValue("type", filter.type() == null ? null : filter.type().name())
.addValue("categories", filter.categoryNames())
.addValue("cities", List.copyOf(filter.cities()));
}
private static String filters(PostFeedFilter filter) {
StringBuilder sql = new StringBuilder(" and p.status in (:statuses)");
if (filter.type() != null) {
sql.append(" and p.type = :type");
}
if (!filter.categories().isEmpty()) {
sql.append(" and p.category in (:categories)");
}
if (!filter.cities().isEmpty()) {
sql.append(" and (lower(p.city) in (:cities) or lower(p.district) in (:cities))");
}
return sql.toString();
}
}

View File

@@ -0,0 +1,158 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Поиск объявлений по тексту. Этапы идут по очереди, пока какой-то не найдёт
* хоть что-то:
* <ol>
* <li>полнотекстовый поиск (стемминг + синонимы): «кот» → коты, кошка, но не «который»;</li>
* <li>последнее слово как префикс — поиск по мере ввода: «кош» → «кошка».
* Только если первый этап пуст: иначе «кот:*» подтянул бы «который».
* Сначала префикс ищется только в заголовках: заголовок говорит, что
* потеряли, а в описании полно случайных слов — «барс» должен найти
* «Потеряна барсетка», а не кота, который «откликается на Барсик».
* Описания подключаются, только если в заголовках ничего нет;</li>
* <li>опечатки: похожесть триграмм по заголовку («кошька» → «кошка»).</li>
* </ol>
* Этап выбирается по наличию результатов вообще, а не на странице, поэтому
* все страницы одного запроса берутся из одного этапа — пагинация не скачет.
*/
@Slf4j
@Service
public class PostSearchService {
/** Длиннее этого ввод обрезаем — защищает БД от гигантских запросов. */
static final int MAX_QUERY_LENGTH = 200;
private static final Pattern HAS_WORD = Pattern.compile("[\\p{L}\\p{N}]");
private static final Pattern PLAIN_WORD = Pattern.compile("[\\p{L}\\p{N}]+");
enum Stage { FULL_TEXT, TITLE_PREFIX, PREFIX, TYPO, NONE }
private final PostSearchRepository repository;
private final SearchProperties properties;
private volatile SynonymExpander synonyms;
public PostSearchService(PostSearchRepository repository, SearchProperties properties) {
this.repository = repository;
this.properties = properties;
}
/** Есть ли в строке, что искать (хоть одна буква или цифра). */
public static boolean hasSearchText(String text) {
return text != null && HAS_WORD.matcher(text).find();
}
/** Страница id объявлений в порядке релевантности. */
@Transactional(readOnly = true)
public Page<Long> search(String rawText, PostFeedFilter filter, Collection<PostStatus> statuses,
Pageable pageable) {
String text = normalize(rawText);
long offset = pageable.getOffset();
int limit = pageable.getPageSize();
String lastWord = lastPlainWord(text);
String rest = lastWord == null ? "" : text.substring(0, text.length() - lastWord.length()).trim();
PostSearchRepository.ParsedQuery parsed = repository.parse(text, rest, lastWord);
// 1. Полнотекстовый поиск с синонимами
String fullQuery = expander().expand(parsed.full());
if (!fullQuery.isBlank()) {
long total = repository.countFullText(fullQuery, statuses, filter);
if (total > 0) {
return page(Stage.FULL_TEXT, text, repository.findFullText(fullQuery, statuses, filter, offset, limit),
pageable, total);
}
}
// 2. Последнее слово как начало слова — поиск по мере ввода: сначала в заголовках, потом везде
if (!parsed.prefix().isBlank()) {
String restQuery = expander().expand(parsed.rest());
Page<Long> byTitle = prefixStage(Stage.TITLE_PREFIX, text, restQuery, parsed.titlePrefix(), statuses,
filter, pageable);
if (byTitle != null) {
return byTitle;
}
Page<Long> anywhere = prefixStage(Stage.PREFIX, text, restQuery, parsed.prefix(), statuses, filter,
pageable);
if (anywhere != null) {
return anywhere;
}
}
// 3. Опечатки — похожесть по заголовку
repository.setTypoThreshold(properties.getTypoThreshold());
long total = repository.countTypo(text, statuses, filter);
if (total > 0) {
return page(Stage.TYPO, text, repository.findTypo(text, statuses, filter, offset, limit), pageable, total);
}
return page(Stage.NONE, text, List.of(), pageable, 0);
}
/** Страница этапа с префиксом или null, если этап ничего не нашёл. */
private Page<Long> prefixStage(Stage stage, String text, String restQuery, String prefix,
Collection<PostStatus> statuses, PostFeedFilter filter, Pageable pageable) {
String query = restQuery.isBlank() ? prefix : "( " + restQuery + " ) & " + prefix;
long total = repository.countFullText(query, statuses, filter);
if (total == 0) {
return null;
}
return page(stage, text, repository.findFullText(query, statuses, filter, pageable.getOffset(),
pageable.getPageSize()), pageable, total);
}
static String normalize(String text) {
String collapsed = text.strip().replaceAll("\\s+", " ");
return collapsed.length() > MAX_QUERY_LENGTH ? collapsed.substring(0, MAX_QUERY_LENGTH) : collapsed;
}
/**
* Последнее слово, если его можно искать как префикс: обычное слово
* (не в кавычках, не минус-слово, не «or») не короче minPrefixLength.
*/
String lastPlainWord(String text) {
// Нечётное число кавычек — пользователь ещё печатает фразу в кавычках
if (text.chars().filter(c -> c == '"').count() % 2 != 0) {
return null;
}
int space = text.lastIndexOf(' ');
String last = text.substring(space + 1);
if (!PLAIN_WORD.matcher(last).matches()
|| last.length() < properties.getMinPrefixLength()
|| last.equalsIgnoreCase("or")) {
return null;
}
return last;
}
private Page<Long> page(Stage stage, String text, List<Long> ids, Pageable pageable, long total) {
log.debug("Post search '{}': stage={}, total={}", text, stage, total);
return new PageImpl<>(ids, pageable, total);
}
/** Синонимы приводятся к лексемам через стеммер Postgres — один раз, при первом поиске. */
private SynonymExpander expander() {
SynonymExpander current = synonyms;
if (current == null) {
synchronized (this) {
current = synonyms;
if (current == null) {
current = new SynonymExpander(properties.getSynonyms(), repository::lexemes);
synonyms = current;
}
}
}
return current;
}
}

View File

@@ -0,0 +1,59 @@
package com.krylov.refound.search;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Настройки поиска по объявлениям (prefix "search" в application.yaml).
*/
@Getter
@Setter
@ToString
@ConfigurationProperties(prefix = "search")
public class SearchProperties {
/**
* Группы синонимов: слово из любой группы ищется вместе со всеми словами
* этой группы («кот» → кот | кошка | котёнок). Слова можно писать в любой
* форме — к основе их приводит тот же русский стеммер Postgres, что и при
* индексации. Добавить синоним = дописать слово сюда и перезапустить сервис.
*/
private List<List<String>> synonyms = new ArrayList<>();
/**
* Порог pg_trgm word_similarity для поиска с опечатками (0..1). Ниже —
* больше «похожих» результатов, но и больше мусора.
*/
private double typoThreshold = 0.3;
/**
* Минимальная длина последнего слова, чтобы искать его как начало слова
* («кош» → «кошка»). Совсем короткие префиксы находят почти всё подряд.
*/
private int minPrefixLength = 3;
/** Подсказки при вводе (SearchSuggestService). */
private Suggest suggest = new Suggest();
@Getter
@Setter
@ToString
public static class Suggest {
/** Сколько подсказок отдавать. */
private int limit = 8;
/** С какой длины слова начинать подсказывать. */
private int minLength = 2;
/** С какой длины слова искать похожие, если по началу ничего нет. */
private int typoMinLength = 4;
/** Порог pg_trgm word_similarity для подсказок с опечаткой (0..1). */
private double typoThreshold = 0.5;
}
}

View File

@@ -0,0 +1,123 @@
package com.krylov.refound.search;
import com.krylov.refound.util.PostVisibility;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Подсказки при вводе поиска: дописывает последнее слово по словарю
* search_words («барс» → «барсетка», «барсик»). В словаре только слова из
* заголовков текущих объявлений, поэтому любая подсказка что-то находит.
*
* <p>Порядок подсказок — по популярности: в скольких объявлениях есть слово
* и как часто его ищут. Поиски копятся в памяти и пишутся в БД раз в
* flush-interval, чтобы не делать запись на каждое нажатие клавиши.
*/
@Slf4j
@Service
public class SearchSuggestService {
private static final Pattern WORD = Pattern.compile("[\\p{L}\\p{N}]+");
/** Предел буфера счётчиков: мусорный ввод не должен съесть память между сбросами. */
static final int MAX_PENDING_WORDS = 10_000;
private final SearchWordRepository repository;
private final SearchProperties.Suggest properties;
private volatile ConcurrentHashMap<String, LongAdder> pending = new ConcurrentHashMap<>();
public SearchSuggestService(SearchWordRepository repository, SearchProperties properties) {
this.repository = repository;
this.properties = properties.getSuggest();
}
/** Подсказки для последнего слова ввода. Пустой список, если слово слишком короткое. */
@Transactional(readOnly = true)
public List<String> suggest(String text) {
String last = lastWord(text);
if (last == null || last.length() < properties.getMinLength()) {
return List.of();
}
// +1: само введённое слово тоже может прийти, но его не подсказываем
Map<String, String> completions = repository.findByPrefix(last, properties.getLimit() + 1);
boolean exactWord = completions.remove(last) != null;
if (completions.isEmpty() && !exactWord && last.length() >= properties.getTypoMinLength()) {
return repository.findSimilar(last, properties.getTypoThreshold(), properties.getLimit());
}
return completions.values().stream().limit(properties.getLimit()).toList();
}
/**
* Учитывает поиск, который что-то нашёл. Считаются все слова запроса, но в
* БД попадут только те, что есть в словаре, — опечатки и обрывки слов отсеются.
*/
public void recordSearch(String text) {
if (text == null) {
return;
}
Map<String, LongAdder> buffer = pending;
Matcher m = WORD.matcher(text);
while (m.find()) {
String word = normalize(m.group());
if (word.length() < 3) {
continue;
}
LongAdder counter = buffer.get(word);
if (counter == null) {
if (buffer.size() >= MAX_PENDING_WORDS) {
continue;
}
counter = buffer.computeIfAbsent(word, w -> new LongAdder());
}
counter.increment();
}
}
@Scheduled(fixedDelayString = "${search.suggest.flush-interval:PT1M}")
public void flushSearchCounts() {
ConcurrentHashMap<String, LongAdder> buffer = pending;
if (buffer.isEmpty()) {
return;
}
pending = new ConcurrentHashMap<>();
Map<String, Long> counts = new HashMap<>();
buffer.forEach((word, counter) -> counts.put(word, counter.sum()));
repository.addSearchCounts(counts);
log.debug("Search suggest: flushed {} searched words", counts.size());
}
@Scheduled(initialDelayString = "${search.suggest.initial-delay:PT10S}",
fixedDelayString = "${search.suggest.refresh-interval:PT10M}")
@Transactional
public void rebuildDictionary() {
long start = System.currentTimeMillis();
repository.rebuild(PostVisibility.FEED_VISIBLE_STATUSES);
log.debug("Search suggest: dictionary rebuilt in {} ms", System.currentTimeMillis() - start);
}
/** Последнее слово, если ввод им заканчивается (после пробела подсказывать нечего). */
static String lastWord(String text) {
if (text == null || text.isEmpty() || !Character.isLetterOrDigit(text.charAt(text.length() - 1))) {
return null;
}
Matcher m = WORD.matcher(text);
String last = null;
while (m.find()) {
last = m.group();
}
return last == null ? null : normalize(last);
}
static String normalize(String word) {
return word.toLowerCase(Locale.ROOT).replace('ё', 'е');
}
}

View File

@@ -0,0 +1,93 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
/**
* Словарь подсказок search_words (changelog 020).
*/
@Repository
@RequiredArgsConstructor
public class SearchWordRepository {
private final NamedParameterJdbcTemplate jdbc;
/**
* Пересобирает doc_count по заголовкам видимых объявлений. Строки с
* неизменившимися значениями не трогаем, исчезнувшие слова обнуляем,
* а слова без объявлений и без поисков удаляем. search_count не меняется.
* Стоп-слова («для», «без») отсекает русский словарь Postgres.
*/
public void rebuild(Collection<PostStatus> statuses) {
MapSqlParameterSource params = new MapSqlParameterSource("statuses",
statuses.stream().map(Enum::name).toList());
jdbc.update("""
with fresh as (
select translate(w, 'ё', 'е') as norm, max(w) as word, count(distinct p.id) as cnt
from posts p, regexp_split_to_table(lower(p.title), '[^а-яёa-z0-9]+') w
where p.status in (:statuses)
and length(w) >= 3
and w !~ '^[0-9]+$'
and length(to_tsvector('russian', w)) > 0
group by 1
), upserted as (
insert into search_words (norm, word, doc_count)
select norm, word, cnt from fresh
on conflict (norm) do update set word = excluded.word, doc_count = excluded.doc_count
where (search_words.word, search_words.doc_count) is distinct from (excluded.word, excluded.doc_count)
)
update search_words set doc_count = 0
where doc_count > 0 and norm not in (select norm from fresh)
""", params);
jdbc.update("delete from search_words where doc_count = 0 and search_count = 0", Map.of());
}
/** Прибавляет счётчики поисков. Слова, которых нет в словаре, игнорируются. */
public void addSearchCounts(Map<String, Long> counts) {
SqlParameterSource[] batch = counts.entrySet().stream()
.map(e -> new MapSqlParameterSource().addValue("norm", e.getKey()).addValue("count", e.getValue()))
.toArray(SqlParameterSource[]::new);
jdbc.batchUpdate("update search_words set search_count = search_count + :count where norm = :norm", batch);
}
/**
* Слова (norm → word), начинающиеся с prefix, включая само слово prefix, если оно есть
* (prefix уже нормализован: нижний регистр, ё → е, только буквы и цифры).
* Популярность — и сколько объявлений со словом есть, и как часто его ищут;
* логарифм не даёт накрутить слово одними поисками.
*/
public Map<String, String> findByPrefix(String prefix, int limit) {
Map<String, String> words = new LinkedHashMap<>();
jdbc.query("""
select norm, word from search_words
where doc_count > 0 and norm like :prefix || '%'
order by ln(1 + doc_count) + ln(1 + search_count) desc, norm
limit :limit
""", new MapSqlParameterSource().addValue("prefix", prefix).addValue("limit", limit),
rs -> {
words.put(rs.getString("norm"), rs.getString("word"));
});
return words;
}
/** Похожие слова для ввода с опечаткой («барст» → «барсетка»). Словарь небольшой — без индекса. */
public List<String> findSimilar(String text, double threshold, int limit) {
return jdbc.queryForList("""
select word from search_words
where doc_count > 0 and word_similarity(:text, norm) >= :threshold
order by word_similarity(:text, norm) desc, ln(1 + doc_count) + ln(1 + search_count) desc, norm
limit :limit
""", new MapSqlParameterSource()
.addValue("text", text)
.addValue("threshold", threshold)
.addValue("limit", limit), String.class);
}
}

View File

@@ -0,0 +1,85 @@
package com.krylov.refound.search;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Расширяет tsquery синонимами: лексема 'кот' превращается в
* ( 'кот' | 'кошк' | 'котенок' ).
*
* <p>Работает с текстовым видом tsquery, который вернул websearch_to_tsquery,
* поэтому кавычки, минус-слова и OR из пользовательского ввода сохраняются:
* «-собака» исключит и собак, и щенков. Лексемы с префиксом или весом
* ('кош':*) не трогаем.
*
* <p>Почему синонимы на стороне Java, а не thesaurus-словарь Postgres:
* словарь — это файл в каталоге tsearch_data внутри контейнера БД, своя
* text search configuration и пересборка search_vector при каждой правке.
* Здесь синонимы — список в application.yaml, индекс от них не зависит.
*/
public class SynonymExpander {
// 'лексема' с необязательным суффиксом :* / :A и т.п.; '' внутри — экранированная кавычка
private static final Pattern LEXEME = Pattern.compile("'((?:[^']|'')*)'(:[*A-Da-d]+)?");
/** лексема → все лексемы её группы (в стабильном порядке) */
private final Map<String, List<String>> groupByLexeme;
/**
* @param groups группы синонимов в виде слов
* @param toLexemes слово → его лексемы по стеммеру Postgres
*/
public SynonymExpander(List<List<String>> groups, Function<String, List<String>> toLexemes) {
Map<String, List<String>> map = new HashMap<>();
for (List<String> group : groups) {
Set<String> lexemes = new LinkedHashSet<>();
for (String word : group) {
List<String> wordLexemes = toLexemes.apply(word);
// Синоним из нескольких слов одной лексемой не заменить — пропускаем
if (wordLexemes.size() == 1) {
lexemes.add(wordLexemes.get(0));
}
}
if (lexemes.size() < 2) {
continue;
}
List<String> alternatives = List.copyOf(lexemes);
for (String lexeme : lexemes) {
map.merge(lexeme, alternatives, (a, b) -> List.copyOf(new LinkedHashSet<>(
Stream.concat(a.stream(), b.stream()).toList())));
}
}
this.groupByLexeme = Map.copyOf(map);
}
/** Подставляет группы синонимов в текст tsquery. Пустую строку возвращает как есть. */
public String expand(String tsquery) {
if (tsquery == null || tsquery.isBlank() || groupByLexeme.isEmpty()) {
return tsquery;
}
Matcher m = LEXEME.matcher(tsquery);
StringBuilder out = new StringBuilder();
while (m.find()) {
String lexeme = m.group(1).replace("''", "'");
List<String> group = m.group(2) == null ? groupByLexeme.get(lexeme) : null;
String replacement = group == null
? m.group()
: group.stream().map(SynonymExpander::quote).collect(Collectors.joining(" | ", "( ", " )"));
m.appendReplacement(out, Matcher.quoteReplacement(replacement));
}
m.appendTail(out);
return out.toString();
}
private static String quote(String lexeme) {
return "'" + lexeme.replace("'", "''") + "'";
}
}

View File

@@ -6,43 +6,86 @@ import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.entity.Chat; import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Image; import com.krylov.refound.entity.Image;
import com.krylov.refound.entity.Message; import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.Post;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.ChatRepository; import com.krylov.refound.repository.ChatRepository;
import com.krylov.refound.repository.MessageRepository; import com.krylov.refound.repository.MessageRepository;
import com.krylov.refound.repository.PostRepository; import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.repository.UserRepository; import com.krylov.refound.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class ChatService { public class ChatService {
/** Максимальная длина сообщения в символах. */
public static final int MAX_MESSAGE_LENGTH = 4000;
private final ChatRepository chatRepository; private final ChatRepository chatRepository;
private final MessageRepository messageRepository; private final MessageRepository messageRepository;
private final SimpMessagingTemplate messagingTemplate; private final SimpMessagingTemplate messagingTemplate;
private final UserRepository userRepository; private final UserRepository userRepository;
private final PostRepository postRepository; private final PostRepository postRepository;
// Создать чат с пользователем (или вернуть существующий) /**
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
*/
@Transactional(readOnly = true)
public Optional<ChatDto> findChat(Long currentUserId, Long otherUserId, Long postId) {
Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId);
return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream()
.findFirst()
.map(chat -> toDto(chat, currentUserId));
}
/**
* Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт
* чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений.
*/
@Transactional @Transactional
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) { public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
validateContent(content);
if (currentUserId.equals(otherUserId)) { if (currentUserId.equals(otherUserId)) {
throw new IllegalArgumentException("Нельзя создать чат с самим собой"); throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
}
if (!userRepository.existsById(otherUserId)) {
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
}
if (postId != null) {
// Иначе клиент мог прикрепить к чату любое чужое объявление
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
Long ownerId = post.getUser().getId();
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
}
} }
Long userId1 = Math.min(currentUserId, otherUserId); Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId); Long userId2 = Math.max(currentUserId, otherUserId);
Chat chat = chatRepository.findByUsers(userId1, userId2).orElseGet(() -> { // Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
Chat newChat = new Chat(); Chat newChat = new Chat();
newChat.setUserOneId(userId1); newChat.setUserOneId(userId1);
newChat.setUserTwoId(userId2); newChat.setUserTwoId(userId2);
@@ -50,14 +93,23 @@ public class ChatService {
return chatRepository.save(newChat); return chatRepository.save(newChat);
}); });
saveAndBroadcast(chat, currentUserId, content);
return toDto(chat, currentUserId); return toDto(chat, currentUserId);
} }
// Все чаты пользователя // Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<ChatDto> getUserChats(Long userId) { public List<ChatDto> getUserChats(Long userId) {
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
}
return chatRepository.findAllByUserId(userId).stream() return chatRepository.findAllByUserId(userId).stream()
.map(c -> toDto(c, userId)) .map(c -> {
ChatDto dto = toDto(c, userId);
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
})
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
.map(ChatWithActivity::dto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -73,9 +125,26 @@ public class ChatService {
// Отправка сообщения (вызывается из WebSocket контроллера) // Отправка сообщения (вызывается из WebSocket контроллера)
@Transactional @Transactional
public void sendMessage(Long senderId, Long chatId, String content) { public void sendMessage(Long senderId, Long chatId, String content) {
validateContent(content);
Chat chat = getChatOrThrow(chatId); Chat chat = getChatOrThrow(chatId);
checkParticipant(chat, senderId); checkParticipant(chat, senderId);
saveAndBroadcast(chat, senderId, content);
}
private void validateContent(String content) {
if (content == null || content.isBlank()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
}
if (content.length() > MAX_MESSAGE_LENGTH) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
}
}
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
Long chatId = chat.getId();
Message message = new Message(); Message message = new Message();
message.setChatId(chatId); message.setChatId(chatId);
message.setSenderId(senderId); message.setSenderId(senderId);
@@ -84,8 +153,6 @@ public class ChatService {
MessageDto dto = toMessageDto(message); MessageDto dto = toMessageDto(message);
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
// Уведомляем получателя об непрочитанных // Уведомляем получателя об непрочитанных
Long recipientId = chat.getUserOneId().equals(senderId) Long recipientId = chat.getUserOneId().equals(senderId)
? chat.getUserTwoId() ? chat.getUserTwoId()
@@ -93,11 +160,28 @@ public class ChatService {
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId); long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
// историю, мог не увидеть ещё не закоммиченное сообщение
afterCommit(() -> {
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
messagingTemplate.convertAndSend( messagingTemplate.convertAndSend(
"/topic/user/" + recipientId + "/unread", "/topic/user/" + recipientId + "/unread",
Map.of("chatId", chatId, "unreadCount", unreadCount) Map.of("chatId", chatId, "unreadCount", unreadCount)
); );
});
}
private static void afterCommit(Runnable action) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
action.run();
}
});
} else {
action.run();
}
} }
@Transactional @Transactional
@@ -128,12 +212,13 @@ public class ChatService {
} }
private Chat getChatOrThrow(Long chatId) { private Chat getChatOrThrow(Long chatId) {
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден")); return chatRepository.findById(chatId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
} }
private void checkParticipant(Chat chat, Long userId) { private void checkParticipant(Chat chat, Long userId) {
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) { if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
throw new SecurityException("Вы не участник этого чата"); throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
} }
} }

View File

@@ -12,6 +12,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -38,14 +39,18 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
@Service @Service
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
public class FileStorageService { public class FileStorageService {
private final S3Client s3Client; private final S3Client s3Client;
private final S3Presigner s3Presigner;
private final MinioProperties properties; private final MinioProperties properties;
private final StringRedisTemplate redisTemplate; private final StringRedisTemplate redisTemplate;
private final ImageOptimizer imageOptimizer;
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of("image/jpeg", "image/png", "image/webp"); private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of("image/jpeg", "image/png", "image/webp");
@@ -59,6 +64,22 @@ public class FileStorageService {
private static final Duration OWNER_TTL = Duration.ofDays(180); private static final Duration OWNER_TTL = Duration.ofDays(180);
private static final String OWNER_KEY_PREFIX = "files:owner:"; private static final String OWNER_KEY_PREFIX = "files:owner:";
/**
* Presigned-ссылка для показа картинок. Ссылка живёт PRESIGNED_URL_TTL, но
* отдаём одну и ту же ссылку PRESIGNED_URL_CACHE_TTL: пока URL не меняется,
* браузер берёт картинку из своего кэша, а не скачивает заново при каждом
* открытии ленты. Запас (24ч - 12ч) покрывает время, пока ссылка лежит в
* кэше браузера (см. FileStorageController#REDIRECT_CACHE_MAX_AGE).
*/
public static final Duration PRESIGNED_URL_TTL = Duration.ofHours(24);
private static final Duration PRESIGNED_URL_CACHE_TTL = Duration.ofHours(12);
private static final String PRESIGNED_KEY_PREFIX = "files:presigned:";
/**
* Файлы неизменяемы (имя — UUID), поэтому браузеру можно хранить их долго.
* MinIO отдаёт этот заголовок по параметру response-cache-control в ссылке.
*/
private static final String IMAGE_CACHE_CONTROL = "private, max-age=31536000, immutable";
/** /**
* Загружает файл в MinIO в корень бакета. * Загружает файл в MinIO в корень бакета.
*/ */
@@ -75,24 +96,34 @@ public class FileStorageService {
// validateFile гарантирует, что originalFilename не null и не blank // validateFile гарантирует, что originalFilename не null и не blank
String originalFilename = file.getOriginalFilename(); String originalFilename = file.getOriginalFilename();
String extension = extractExtension(originalFilename);
String prefix = (folder != null && !folder.isBlank()) ? folder.replaceAll("/+$", "") + "/" : ""; String prefix = (folder != null && !folder.isBlank()) ? folder.replaceAll("/+$", "") + "/" : "";
String objectName = prefix + UUID.randomUUID() + extension;
log.info("Загрузка файла '{}'. Новое имя: {}", originalFilename, objectName);
try { try {
byte[] content = file.getBytes();
String contentType = file.getContentType();
String extension = extractExtension(originalFilename);
Optional<ImageOptimizer.OptimizedImage> optimized = imageOptimizer.optimize(content, contentType);
if (optimized.isPresent()) {
content = optimized.get().content();
contentType = optimized.get().contentType();
extension = optimized.get().extension();
}
String objectName = prefix + UUID.randomUUID() + extension;
log.info("Загрузка файла '{}'. Новое имя: {}", originalFilename, objectName);
Map<String, String> metadata = new HashMap<>(); Map<String, String> metadata = new HashMap<>();
metadata.put(ORIGINAL_FILENAME_METADATA_KEY, URLEncoder.encode(originalFilename, StandardCharsets.UTF_8)); metadata.put(ORIGINAL_FILENAME_METADATA_KEY, URLEncoder.encode(originalFilename, StandardCharsets.UTF_8));
PutObjectRequest request = PutObjectRequest.builder() PutObjectRequest request = PutObjectRequest.builder()
.bucket(properties.bucket()) .bucket(properties.bucket())
.key(objectName) .key(objectName)
.contentType(file.getContentType()) .contentType(contentType)
.metadata(metadata) .metadata(metadata)
.build(); .build();
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); s3Client.putObject(request, RequestBody.fromBytes(content));
registerOwner(objectName); registerOwner(objectName);
log.info("Файл '{}' успешно загружен.", objectName); log.info("Файл '{}' успешно загружен.", objectName);
return objectName; return objectName;
@@ -119,6 +150,11 @@ public class FileStorageService {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, disposition + "; filename*=UTF-8''" + encodedFilename); headers.add(HttpHeaders.CONTENT_DISPOSITION, disposition + "; filename*=UTF-8''" + encodedFilename);
if (file.contentType().startsWith("image/")) {
// Без явного заголовка Spring Security ставит no-store, и при каждом
// открытии приложения все картинки ленты скачиваются заново.
headers.add(HttpHeaders.CACHE_CONTROL, IMAGE_CACHE_CONTROL);
}
return ResponseEntity.ok() return ResponseEntity.ok()
.headers(headers) .headers(headers)
@@ -126,6 +162,64 @@ public class FileStorageService {
.body(file.content()); .body(file.content());
} }
/**
* Генерирует presigned URL для скачивания файла напрямую из MinIO/S3.
* Браузер будет загружать картинку по этому URL, минуя backend (меньше нагрузки).
*/
public String generatePresignedDownloadUrl(String objectName, Duration ttl) {
try {
GetObjectRequest getRequest = GetObjectRequest.builder()
.bucket(properties.bucket())
.key(objectName)
.responseCacheControl(IMAGE_CACHE_CONTROL)
.build();
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
.signatureDuration(ttl)
.getObjectRequest(getRequest)
.build();
String url = s3Presigner.presignGetObject(presignRequest).url().toString();
log.debug("Сгенерирован presigned URL для файла '{}', TTL={}", objectName, ttl);
return url;
} catch (S3Exception | SdkClientException e) {
log.error("Ошибка при генерации presigned URL для файла '{}': {}", objectName, e.getMessage(), e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при формировании ссылки на файл.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Генерирует presigned URL со стандартным TTL.
*/
public String generatePresignedDownloadUrl(String objectName) {
return generatePresignedDownloadUrl(objectName, PRESIGNED_URL_TTL);
}
/**
* Presigned URL со стандартным TTL, одинаковый для повторных запросов в
* течение PRESIGNED_URL_CACHE_TTL — чтобы браузер мог кэшировать картинку.
* Если Redis недоступен, просто генерируем новую ссылку.
*/
public String getCachedPresignedDownloadUrl(String objectName) {
String cacheKey = PRESIGNED_KEY_PREFIX + objectName;
try {
String cached = redisTemplate.opsForValue().get(cacheKey);
if (cached != null) {
return cached;
}
} catch (RuntimeException e) {
log.warn("Не удалось прочитать presigned URL из кэша для '{}': {}", objectName, e.getMessage());
}
String url = generatePresignedDownloadUrl(objectName, PRESIGNED_URL_TTL);
try {
redisTemplate.opsForValue().set(cacheKey, url, PRESIGNED_URL_CACHE_TTL);
} catch (RuntimeException e) {
log.warn("Не удалось сохранить presigned URL в кэш для '{}': {}", objectName, e.getMessage());
}
return url;
}
/** /**
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты. * Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler, * Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
@@ -150,6 +244,7 @@ public class FileStorageService {
s3Client.deleteObject(request); s3Client.deleteObject(request);
forgetOwner(objectName); forgetOwner(objectName);
forgetPresignedUrl(objectName);
log.info("Файл '{}' успешно удален.", objectName); log.info("Файл '{}' успешно удален.", objectName);
} catch (S3Exception | SdkClientException e) { } catch (S3Exception | SdkClientException e) {
log.error("Ошибка при удалении файла '{}': {}", objectName, e.getMessage(), e); log.error("Ошибка при удалении файла '{}': {}", objectName, e.getMessage(), e);
@@ -214,6 +309,14 @@ public class FileStorageService {
} }
} }
private void forgetPresignedUrl(String objectName) {
try {
redisTemplate.delete(PRESIGNED_KEY_PREFIX + objectName);
} catch (RuntimeException e) {
log.warn("Не удалось удалить presigned URL из кэша для '{}': {}", objectName, e.getMessage());
}
}
private String readOwner(String objectName) { private String readOwner(String objectName) {
try { try {
return redisTemplate.opsForValue().get(OWNER_KEY_PREFIX + objectName); return redisTemplate.opsForValue().get(OWNER_KEY_PREFIX + objectName);

View File

@@ -0,0 +1,147 @@
package com.krylov.refound.service;
import jakarta.annotation.PostConstruct;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Optional;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Component;
/**
* Готовит загруженные фото к показу в ленте. Снимки с телефона (особенно iPhone)
* весят 3–10 МБ при 12–24 Мп, и при первом открытии приложения браузер долго
* скачивает и декодирует такие оригиналы. Здесь картинка уменьшается до
* MAX_DIMENSION по большей стороне, поворачивается по EXIF (сами EXIF, включая
* геометку, при этом отбрасываются) и пережимается в progressive JPEG.
*/
@Slf4j
@Component
public class ImageOptimizer {
/** Больше на экране телефона/ноутбука не нужно даже с retina. */
static final int MAX_DIMENSION = 1600;
/** Такие файлы уже достаточно лёгкие — пережимать их нет смысла. */
static final long SKIP_BELOW_BYTES = 300 * 1024;
private static final float JPEG_QUALITY = 0.82f;
public record OptimizedImage(byte[] content, String contentType, String extension) {
}
@PostConstruct
void registerImageIoPlugins() {
// Плагины TwelveMonkeys (WebP, CMYK-JPEG) лежат внутри fat jar —
// явная регистрация гарантирует, что ImageIO их увидит.
ImageIO.scanForPlugins();
}
/**
* Возвращает облегчённую версию картинки или пустой Optional, если оригинал
* стоит сохранить как есть: он и так маленький, не читается или пережатая
* версия получилась не легче.
*/
public Optional<OptimizedImage> optimize(byte[] source, String contentType) {
if (source.length <= SKIP_BELOW_BYTES) {
return Optional.empty();
}
try {
Thumbnails.Builder<?> builder = Thumbnails.of(new ByteArrayInputStream(source));
// size() увеличивает маленькие картинки, поэтому для них только пережимаем.
builder = maxSide(source) > MAX_DIMENSION
? builder.size(MAX_DIMENSION, MAX_DIMENSION)
: builder.scale(1.0);
BufferedImage image = builder.asBufferedImage();
boolean keepAlpha = image.getColorModel().hasAlpha() && !"image/jpeg".equals(contentType);
OptimizedImage optimized = keepAlpha
? new OptimizedImage(writePng(image), "image/png", ".png")
: new OptimizedImage(writeJpeg(toRgb(image)), "image/jpeg", ".jpg");
if (optimized.content().length >= source.length) {
return Optional.empty();
}
log.info("Картинка сжата: {} КБ -> {} КБ ({}x{})",
source.length / 1024, optimized.content().length / 1024, image.getWidth(), image.getHeight());
return Optional.of(optimized);
} catch (IOException | RuntimeException e) {
log.warn("Не удалось оптимизировать картинку ({}), сохраняем оригинал: {}", contentType, e.getMessage());
return Optional.empty();
}
}
/** Размер из заголовка файла, без декодирования пикселей. */
private static int maxSide(byte[] source) throws IOException {
try (ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(source))) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if (!readers.hasNext()) {
throw new IOException("неизвестный формат");
}
ImageReader reader = readers.next();
try {
reader.setInput(in);
return Math.max(reader.getWidth(0), reader.getHeight(0));
} finally {
reader.dispose();
}
}
}
private static BufferedImage toRgb(BufferedImage image) {
if (image.getType() == BufferedImage.TYPE_INT_RGB) {
return image;
}
BufferedImage rgb = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = rgb.createGraphics();
try {
// Прозрачные места (PNG/WebP без альфы на выходе) заливаем белым, а не чёрным.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(image, 0, 0, null);
} finally {
g.dispose();
}
return rgb;
}
private static byte[] writeJpeg(BufferedImage image) throws IOException {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
if (!writers.hasNext()) {
throw new IOException("нет JPEG-кодировщика");
}
ImageWriter writer = writers.next();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(JPEG_QUALITY);
// Progressive: браузер сразу рисует размытый кадр и дорисовывает детали.
if (param.canWriteProgressive()) {
param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
}
writer.write(null, new IIOImage(image, null, null), param);
} finally {
writer.dispose();
}
return out.toByteArray();
}
private static byte[] writePng(BufferedImage image) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (!ImageIO.write(image, "png", out)) {
throw new IOException("нет PNG-кодировщика");
}
return out.toByteArray();
}
}

View File

@@ -55,6 +55,12 @@ public class PostModerationExecutorService {
return; return;
} }
if (!approved) {
postRepository.updateStatus(postId, PostStatus.REJECTED);
log.info("Пост {} отклонён модерацией.", post.getId());
return;
}
postRepository.updateStatus(postId, PostStatus.ACTIVE); postRepository.updateStatus(postId, PostStatus.ACTIVE);
log.info("Пост {} прошёл модерацию.", post.getId()); log.info("Пост {} прошёл модерацию.", post.getId());

View File

@@ -17,22 +17,22 @@ import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper; import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.ImageRepository; import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository; import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.PostSearchService;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.redis.MapCacheService; import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheKeyGenerator; import com.krylov.refound.service.redis.PostCacheKeyGenerator;
import com.krylov.refound.service.redis.PostCacheService; import com.krylov.refound.service.redis.PostCacheService;
import com.krylov.refound.util.PostSpecification; import com.krylov.refound.util.PostSpecification;
import com.krylov.refound.util.PostVisibility; import com.krylov.refound.util.PostVisibility;
import java.time.Duration; import com.krylov.refound.util.TimeZoneContext;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -40,6 +40,15 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Set;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j @Slf4j
@@ -59,6 +68,8 @@ public class PostService {
private final PostCacheService postCacheService; private final PostCacheService postCacheService;
private final PostCacheKeyGenerator postCacheKeyGenerator; private final PostCacheKeyGenerator postCacheKeyGenerator;
private final MapCacheService mapCacheService; private final MapCacheService mapCacheService;
private final PostSearchService postSearchService;
private final SearchSuggestService searchSuggestService;
@Transactional @Transactional
public PostRequest create(PostRequest request, List<MultipartFile> images) { public PostRequest create(PostRequest request, List<MultipartFile> images) {
@@ -66,10 +77,12 @@ public class PostService {
User currentUser = userService.getCurrentUser(); User currentUser = userService.getCurrentUser();
Post post = mapper.toEntity(request); Post post = mapper.toEntity(request);
post.setCreatedAt(LocalDateTime.now()); post.setCreatedAt(TimeZoneContext.now());
post.setStatus(PostStatus.MODERATION); post.setStatus(PostStatus.MODERATION);
post.setUser(currentUser); post.setUser(currentUser);
post.setIsReward(request.getReward()); post.setIsReward(request.getReward());
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
post.setAddress(normalizeAddress(request.getAddress()));
if (request.getLatitude() == null || request.getLongitude() == null) { if (request.getLatitude() == null || request.getLongitude() == null) {
post.setCity(request.getAddress()); post.setCity(request.getAddress());
} else { } else {
@@ -90,10 +103,35 @@ public class PostService {
return request; return request;
} }
public Page<PostResponse> getFeed(String search, Pageable pageable) { /**
* Публичная лента: фильтры по типу, категориям и городам + поиск по тексту.
* С текстом поиска — полнотекстовый поиск с ранжированием по релевантности
* (сортировка из pageable игнорируется) и без кэша: запросы почти всегда
* уникальны, а GIN-индекс отвечает быстро. Без текста — обычная лента,
* кэшируется в Redis с учётом фильтров.
*/
public Page<PostResponse> getFeed(String search, PostFeedFilter filter, Pageable pageable) {
PostFeedFilter feedFilter = filter == null ? PostFeedFilter.NONE : filter;
if (PostSearchService.hasSearchText(search)) {
Page<Long> ids = postSearchService.search(search, feedFilter, FEED_VISIBLE_STATUSES, pageable);
// Статистика для подсказок: только удачные поиски и только первая страница —
// подгрузка следующих страниц того же запроса не делает слово популярнее
if (pageable.getPageNumber() == 0 && ids.getTotalElements() > 0) {
searchSuggestService.recordSearch(search);
}
return new PageImpl<>(loadInOrder(ids.getContent()), ids.getPageable(), ids.getTotalElements());
}
// Без уникального ключа в сортировке порядок постов с одинаковым createdAt
// недетерминирован, и при LIMIT/OFFSET посты дублируются или пропадают между страницами
if (pageable.getSort().getOrderFor("id") == null) {
pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
pageable.getSort().and(Sort.by(Sort.Direction.DESC, "id")));
}
// Ключ содержит версию ленты, она читается до запроса в БД // Ключ содержит версию ленты, она читается до запроса в БД
String cacheKey = postCacheKeyGenerator.feedKey(search, pageable); String cacheKey = postCacheKeyGenerator.feedKey(feedFilter, pageable);
CachedPostPage cached = postCacheService.getFeed(cacheKey); CachedPostPage cached = postCacheService.getFeed(cacheKey);
@@ -104,7 +142,7 @@ public class PostService {
log.debug("Feed cache MISS: {}", cacheKey); log.debug("Feed cache MISS: {}", cacheKey);
Specification<Post> spec = PostSpecification.hasSearch(search) Specification<Post> spec = PostSpecification.feedFilter(feedFilter)
.and((root, query, cb) -> .and((root, query, cb) ->
root.get("status").in(FEED_VISIBLE_STATUSES) root.get("status").in(FEED_VISIBLE_STATUSES)
); );
@@ -125,6 +163,21 @@ public class PostService {
return responsePage; return responsePage;
} }
/** Загружает посты по id и отдаёт их в том же порядке (порядок релевантности поиска). */
private List<PostResponse> loadInOrder(List<Long> ids) {
if (ids.isEmpty()) {
return List.of();
}
Map<Long, Post> byId = postRepository.findAllById(ids).stream()
.collect(Collectors.toMap(Post::getId, Function.identity()));
return ids.stream()
.map(byId::get)
// пост могли удалить между двумя запросами — просто пропускаем
.filter(Objects::nonNull)
.map(post -> toResponse(post, true))
.toList();
}
/** /**
* Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id, * Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id,
* несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер, * несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер,
@@ -190,6 +243,7 @@ public class PostService {
post.setType(request.getType()); post.setType(request.getType());
post.setIsReward(request.getReward()); post.setIsReward(request.getReward());
post.setReward(request.getRewardText()); post.setReward(request.getRewardText());
post.setAddress(normalizeAddress(request.getAddress()));
if (request.getLatitude() != null && request.getLongitude() != null) { if (request.getLatitude() != null && request.getLongitude() != null) {
post.setLatitude(request.getLatitude()); post.setLatitude(request.getLatitude());
@@ -401,4 +455,8 @@ public class PostService {
return toResponse(post, true); return toResponse(post, true);
} }
private static String normalizeAddress(String address) {
return StringUtils.hasText(address) ? address.trim() : null;
}
} }

View File

@@ -4,12 +4,12 @@ import com.krylov.refound.dto.ReviewRequestDto;
import com.krylov.refound.dto.ReviewResponseDto; import com.krylov.refound.dto.ReviewResponseDto;
import com.krylov.refound.entity.Review; import com.krylov.refound.entity.Review;
import com.krylov.refound.repository.ReviewRepository; import com.krylov.refound.repository.ReviewRepository;
import jakarta.validation.Valid; import com.krylov.refound.util.TimeZoneContext;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class ReviewService { public class ReviewService {
@@ -28,7 +28,7 @@ public class ReviewService {
review.setAuthorName(username); // или firstName из User review.setAuthorName(username); // или firstName из User
review.setRating(request.getRating()); review.setRating(request.getRating());
review.setText(request.getText()); review.setText(request.getText());
review.setCreatedAt(LocalDateTime.now()); review.setCreatedAt(TimeZoneContext.now());
Review saved = reviewRepository.save(review); Review saved = reviewRepository.save(review);
return toResponse(saved); return toResponse(saved);

View File

@@ -4,6 +4,8 @@ import com.krylov.refound.entity.Post;
import com.krylov.refound.enums.PostStatus; import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.repository.FavoriteRepository; import com.krylov.refound.repository.FavoriteRepository;
import com.krylov.refound.repository.PostRepository; import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheService;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -20,6 +22,8 @@ public class SchedulerService {
private final PostRepository postRepository; private final PostRepository postRepository;
private final FavoriteRepository favoriteRepository; private final FavoriteRepository favoriteRepository;
private final PostModerationExecutorService postModerationExecutorService; private final PostModerationExecutorService postModerationExecutorService;
private final PostCacheService postCacheService;
private final MapCacheService mapCacheService;
/** /**
* Runs every day at 00:01 to delete: * Runs every day at 00:01 to delete:
@@ -55,6 +59,12 @@ public class SchedulerService {
log.info("Deleted {} posts older than 6 months", oldPosts.size()); log.info("Deleted {} posts older than 6 months", oldPosts.size());
} }
if (!closedPosts.isEmpty() || !oldPosts.isEmpty()) {
// Иначе удалённые посты висят в ленте и на карте до TTL кэша
postCacheService.invalidatePosts();
mapCacheService.clearMapMarkersCache();
}
log.info("Scheduled cleanup completed successfully"); log.info("Scheduled cleanup completed successfully");
} }

View File

@@ -139,6 +139,9 @@ public class AdminPostService {
if (StringUtils.hasText(category)) { if (StringUtils.hasText(category)) {
post.setCategory(PostCategory.fromDisplayName(category)); post.setCategory(PostCategory.fromDisplayName(category));
} }
if (StringUtils.hasText(address)) {
post.setAddress(address.trim());
}
if (latitude != null && longitude != null) { if (latitude != null && longitude != null) {
post.setLatitude(latitude); post.setLatitude(latitude);
post.setLongitude(longitude); post.setLongitude(longitude);
@@ -303,6 +306,7 @@ public class AdminPostService {
.category(post.getCategory() == null ? null : post.getCategory().getDisplayName()) .category(post.getCategory() == null ? null : post.getCategory().getDisplayName())
.city(post.getCity()) .city(post.getCity())
.district(post.getDistrict()) .district(post.getDistrict())
.address(post.getAddress())
.latitude(post.getLatitude()) .latitude(post.getLatitude())
.longitude(post.getLongitude()) .longitude(post.getLongitude())
.phone(post.getPhone()) .phone(post.getPhone())

View File

@@ -36,13 +36,13 @@ public class AdvertisingSelectionService {
String resolvedSessionId = sessionId != null ? sessionId : request.getSession(true).getId(); String resolvedSessionId = sessionId != null ? sessionId : request.getSession(true).getId();
if (!frequencyService.isSessionCooldownPassed(resolvedSessionId)) { if (!frequencyService.isSessionCooldownPassed(resolvedSessionId)) {
log.warn("isSessionCooldownPassed by {} resolvedSessionId is empty", resolvedSessionId); log.debug("Session cooldown not passed for sessionId={}", resolvedSessionId);
return Optional.empty(); return Optional.empty();
} }
List<Advertising> eligible = adRepository.findEligibleAds(LocalDateTime.now()); List<Advertising> eligible = adRepository.findEligibleAds(LocalDateTime.now());
if (eligible.isEmpty()) { if (eligible.isEmpty()) {
log.warn("findEligibleAds is empty"); log.debug("No eligible ads to show");
return Optional.empty(); return Optional.empty();
} }

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.service.redis;
import com.krylov.refound.enums.PostCategory; import com.krylov.refound.enums.PostCategory;
import com.krylov.refound.enums.PostType; import com.krylov.refound.enums.PostType;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.service.redis.PostCacheService; import com.krylov.refound.service.redis.PostCacheService;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -18,7 +19,8 @@ public class PostCacheKeyGenerator {
private final PostCacheService postCacheService; private final PostCacheService postCacheService;
public String feedKey(String search, Pageable pageable) { /** Ключ кэша ленты без текстового поиска (поиск не кэшируется). */
public String feedKey(PostFeedFilter filter, Pageable pageable) {
// Версия читается здесь, то есть в самом начале getFeed, до запроса в БД // Версия читается здесь, то есть в самом начале getFeed, до запроса в БД
String version = postCacheService.currentVersion(); String version = postCacheService.currentVersion();
@@ -28,7 +30,7 @@ public class PostCacheKeyGenerator {
.collect(Collectors.joining(",")); .collect(Collectors.joining(","));
return PREFIX + version return PREFIX + version
+ ":search=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(search)) + ":filter=" + RedisCacheKeyUtil.sha256(filter.cacheKeyPart())
+ ":page=" + pageable.getPageNumber() + ":page=" + pageable.getPageNumber()
+ ":size=" + pageable.getPageSize() + ":size=" + pageable.getPageSize()
+ ":sort=" + sort; + ":sort=" + sort;

View File

@@ -4,6 +4,7 @@ import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User; import com.krylov.refound.entity.User;
import com.krylov.refound.enums.PostStatus; import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.enums.PostType; import com.krylov.refound.enums.PostType;
import com.krylov.refound.search.PostFeedFilter;
import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.Join;
import java.util.Set; import java.util.Set;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
@@ -45,17 +46,19 @@ public class PostSpecification {
); );
} }
public static Specification<Post> hasSearch(String search) { /** Фильтры публичной ленты: тип, категории, города (город или район, без учёта регистра). */
return (root, query, cb) -> { public static Specification<Post> feedFilter(PostFeedFilter filter) {
if (search == null || search.isBlank()) { return Specification.allOf(
return cb.conjunction(); (root, query, cb) -> filter.type() == null ? cb.conjunction() : cb.equal(root.get("type"), filter.type()),
} (root, query, cb) -> filter.categories().isEmpty()
String pattern = "%" + search.toLowerCase() + "%"; ? cb.conjunction()
return cb.or( : root.get("category").in(filter.categories()),
cb.like(cb.lower(root.get("title")), pattern), (root, query, cb) -> filter.cities().isEmpty()
cb.like(cb.lower(root.get("description")), pattern) ? cb.conjunction()
: cb.or(
cb.lower(root.get("city")).in(filter.cities()),
cb.lower(root.get("district")).in(filter.cities()))
); );
};
} }
public static Specification<Post> cityOrDistrictLike(String query) { public static Specification<Post> cityOrDistrictLike(String query) {

View File

@@ -0,0 +1,84 @@
package com.krylov.refound.util;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
/**
* Хранит таймзону текущего пользователя в ThreadLocal и отдаёт локальное время
* в этой зоне. Значение выставляет {@link com.krylov.refound.config.TimeZoneFilter}
* из заголовка {@code X-Timezone}; для WebSocket — из CONNECT-заголовка.
*
* <p>Принимаются IANA-идентификаторы ("Europe/Moscow"), offset ("+03:00") и
* смещение в минутах ("180"). Если клиент таймзону не прислал, используется
* зона сервера.
*/
public final class TimeZoneContext {
public static final String HEADER = "X-Timezone";
public static final String WS_HEADER = "timezone";
public static final String SESSION_ATTRIBUTE = "timezone";
private static final ThreadLocal<ZoneId> CURRENT = new ThreadLocal<>();
private TimeZoneContext() {
}
public static void set(String rawZone) {
ZoneId zone = parse(rawZone);
if (zone == null) {
CURRENT.remove();
} else {
CURRENT.set(zone);
}
}
public static void clear() {
CURRENT.remove();
}
public static ZoneId get() {
ZoneId zone = CURRENT.get();
return zone != null ? zone : ZoneId.systemDefault();
}
/**
* @return текущее время в зоне пользователя (или сервера, если зона не задана).
*/
public static LocalDateTime now() {
return LocalDateTime.now(get());
}
/**
* @return распознанная зона или {@code null}, если значение не задано/невалидно.
*/
public static ZoneId parse(String raw) {
if (raw == null) {
return null;
}
String value = raw.trim();
if (value.isEmpty()) {
return null;
}
// смещение в минутах от UTC: "180", "-300"
try {
int minutes = Integer.parseInt(value);
return ZoneId.ofOffset("UTC", ZoneOffset.ofTotalSeconds(minutes * 60));
} catch (NumberFormatException ignored) {
// значение не число — пробуем другие форматы
}
// offset: "+03:00", "+0300", "+03"
try {
return ZoneOffset.of(value);
} catch (DateTimeException ignored) {
// не offset — пробуем IANA
}
// IANA-идентификатор: "Europe/Moscow", "UTC+3"
try {
return ZoneId.of(value);
} catch (DateTimeException ignored) {
return null;
}
}
}

View File

@@ -82,6 +82,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
accessor.getSessionAttributes().put(USER_ID_ATTR, userId); accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
accessor.getSessionAttributes().put(ROLE_ATTR, role); accessor.getSessionAttributes().put(ROLE_ATTR, role);
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
if (timezone != null) {
accessor.getSessionAttributes().put(TimeZoneContext.SESSION_ATTRIBUTE, timezone);
}
log.info("WS connected: userId={} role={}", userId, role); log.info("WS connected: userId={} role={}", userId, role);
} }

View File

@@ -1,5 +1,5 @@
ffmpeg: ffmpeg:
binary-path: C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe binary-path: ${FFMPEG_PATH:C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe}
spring: spring:
servlet: servlet:
@@ -8,9 +8,9 @@ spring:
max-request-size: 20MB max-request-size: 20MB
datasource: datasource:
url: jdbc:postgresql://localhost:5432/nahodka url: ${DB_URL:jdbc:postgresql://localhost:5432/nahodka}
username: user username: ${DB_USER:user}
password: pass password: ${DB_PASSWORD:pass}
driver-class-name: org.postgresql.Driver driver-class-name: org.postgresql.Driver
jpa: jpa:
@@ -19,7 +19,7 @@ spring:
# из-за чего базы расходились. Для разработки можно переопределить # из-за чего базы расходились. Для разработки можно переопределить
# переменной окружения JPA_DDL_AUTO=update. # переменной окружения JPA_DDL_AUTO=update.
ddl-auto: ${JPA_DDL_AUTO:validate} ddl-auto: ${JPA_DDL_AUTO:validate}
show-sql: true show-sql: ${JPA_SHOW_SQL:true}
properties: properties:
hibernate: hibernate:
format_sql: true format_sql: true
@@ -49,16 +49,44 @@ minio:
ai: ai:
url: ${AI_SERVICE_URL:http://localhost:8000} url: ${AI_SERVICE_URL:http://localhost:8000}
timeout: 10 timeout: 10
image-timeout: ${AI_IMAGE_TIMEOUT:30}
# Должно совпадать с TEXT_MAX_LENGTH AI-сервиса; длиннее — отправляется частями
text-max-length: ${AI_TEXT_MAX_LENGTH:5000}
retry: retry:
max-attempts: 3 max-attempts: 3
delay: 500 delay: 500
multiplier: 2 multiplier: 2
# Поиск по объявлениям (PostSearchService)
search:
typo-threshold: 0.3
min-prefix-length: 3
# Слово из группы ищется вместе со всеми словами группы. Форма слова не важна —
# к основе приводит русский стеммер Postgres. Синонимы из нескольких слов не поддерживаются.
synonyms:
- [кот, кошка, котёнок, котята, котик]
- [собака, пёс, щенок, щенки, собачка, пёсик]
- [телефон, смартфон, мобильник, айфон, iphone]
- [кошелёк, портмоне, бумажник]
- [ключи, ключ, связка]
- [паспорт, документы]
- [рюкзак, ранец]
- [очки, окуляры]
- [попугай, попугайчик]
# Подсказки при вводе (SearchSuggestService): словарь слов из заголовков объявлений
suggest:
limit: 8
min-length: 2
typo-min-length: 4
typo-threshold: 0.5
refresh-interval: PT10M # пересборка словаря
flush-interval: PT1M # запись накопленной статистики поисков
jwt: jwt:
secret: ${JWT_SECRET:mySuperSecretKeyForJwtTokenGenerationThatIsLongEnough2024!ReFound} secret: ${JWT_SECRET}
access-expiration: ${JWT_ACCESS_EXPIRATION:900000} # 15 минут access-expiration: ${JWT_ACCESS_EXPIRATION:900000} # 15 минут
refresh-expiration: ${JWT_REFRESH_EXPIRATION:604800000} # 7 дней refresh-expiration: ${JWT_REFRESH_EXPIRATION:604800000} # 7 дней
app: app:
cors: cors:
allowed-origins: http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000 allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000}

View File

@@ -0,0 +1,19 @@
databaseChangeLog:
- changeSet:
id: 018-add-address-posts
author: krylov
comment: >
Полный адрес, который пользователь выбрал/ввёл в форме. Раньше он
терялся: при наличии координат city/district перезаписывались данными
Nominatim, а сам адрес нигде не хранился.
preConditions:
onFail: MARK_RAN
not:
columnExists:
tableName: posts
columnName: address
changes:
- addColumn:
tableName: posts
columns:
- column: { name: address, type: VARCHAR(500) }

View File

@@ -0,0 +1,39 @@
databaseChangeLog:
- changeSet:
id: 015-chats-unique-per-post
author: krylov
comment: >
Чат теперь уникален для пары пользователей И объявления. Раньше уникальной была
только пара, и при обращении к тому же автору по другому объявлению возвращался
старый чат со старым post_id (не та картинка во вкладке чатов).
Имя старого ограничения может отличаться (таблицу раньше создавал Hibernate),
поэтому удаляем любое unique-ограничение ровно по (user_one_id, user_two_id).
preConditions:
onFail: MARK_RAN
tableExists:
tableName: chats
changes:
- sql:
splitStatements: false
sql: |
DO $$
DECLARE r record;
BEGIN
FOR r IN
SELECT con.conname
FROM pg_constraint con
JOIN pg_class t ON t.oid = con.conrelid
WHERE t.relname = 'chats'
AND con.contype = 'u'
AND (SELECT array_agg(a.attname::text ORDER BY a.attname::text)
FROM pg_attribute a
WHERE a.attrelid = t.oid AND a.attnum = ANY (con.conkey))
= ARRAY['user_one_id', 'user_two_id']
LOOP
EXECUTE format('ALTER TABLE chats DROP CONSTRAINT %I', r.conname);
END LOOP;
END $$;
- addUniqueConstraint:
tableName: chats
columnNames: user_one_id, user_two_id, post_id
constraintName: uq_chat_users_post

View File

@@ -29,3 +29,7 @@ databaseChangeLog:
- include: { file: db/changelog/create/006-create-chats.yaml } - include: { file: db/changelog/create/006-create-chats.yaml }
- include: { file: db/changelog/add/017-messages-chat-id.yaml } - include: { file: db/changelog/add/017-messages-chat-id.yaml }
- include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml } - include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml }
- include: { file: db/changelog/alter/015-chats-unique-per-post.yaml }
- include: { file: db/changelog/add/018-add-address-posts.yaml }
- include: { file: db/changelog/search/019-posts-full-text-search.yaml }
- include: { file: db/changelog/search/020-search-words.yaml }

View File

@@ -0,0 +1,34 @@
databaseChangeLog:
- changeSet:
id: 019-posts-full-text-search
author: krylov
comment: >
Полнотекстовый поиск по объявлениям. search_vector — сгенерированная
колонка: Postgres сам пересчитывает её при изменении title/description,
приложению её писать не нужно (в сущности Post она не маппится).
Заголовок весит больше описания (A > B) — это учитывает ts_rank_cd.
Конфигурация 'russian' стеммит слова: «кот» находит «кота», «коты»,
но не «который». pg_trgm — для поиска с опечатками по заголовку.
changes:
- sql:
sql: CREATE EXTENSION IF NOT EXISTS pg_trgm
- sql:
sql: >
ALTER TABLE posts ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('russian'::regconfig, coalesce(title, '')), 'A') ||
setweight(to_tsvector('russian'::regconfig, coalesce(description, '')), 'B')
) STORED
- sql:
sql: CREATE INDEX idx_posts_search_vector ON posts USING gin (search_vector)
- sql:
# Выражение должно совпадать с тем, что в PostSearchRepository,
# иначе индекс не используется. translate — чтобы «ё» и «е» не мешали опечаткам.
sql: CREATE INDEX idx_posts_title_trgm ON posts USING gin (translate(lower(title), 'ё', 'е') gin_trgm_ops)
rollback:
- sql:
sql: DROP INDEX IF EXISTS idx_posts_title_trgm
- sql:
sql: DROP INDEX IF EXISTS idx_posts_search_vector
- sql:
sql: ALTER TABLE posts DROP COLUMN IF EXISTS search_vector

View File

@@ -0,0 +1,23 @@
databaseChangeLog:
- changeSet:
id: 020-search-words
author: krylov
comment: >
Словарь для подсказок при вводе поиска. Слова берутся из заголовков
видимых объявлений (doc_count — в скольких объявлениях встречается),
search_count — сколько раз слово искали с ненулевым результатом.
Таблицу пересобирает SearchSuggestService по расписанию; search_count
при пересборке сохраняется. norm — слово в нижнем регистре с ё → е,
в collation "C", чтобы первичный ключ обслуживал LIKE 'префикс%'.
changes:
- sql:
sql: >
CREATE TABLE search_words (
norm text COLLATE "C" PRIMARY KEY,
word text NOT NULL,
doc_count int NOT NULL DEFAULT 0,
search_count bigint NOT NULL DEFAULT 0
)
rollback:
- sql:
sql: DROP TABLE IF EXISTS search_words

View File

@@ -0,0 +1,109 @@
package com.krylov.refound.ai.client;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.WebClientConfig;
import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
class AiMultipartHttpClientTest {
private static final String URI = "/api/v1/moderation/image";
private HttpServer server;
@AfterEach
void stopServer() {
if (server != null) {
server.stop(0);
}
}
@Test
void returnsResponseWhenServiceAnswersInTime() throws IOException {
startServer(0, 200, "{\"approved\":true}");
Map<?, ?> response = client(baseUrl(), 2).post(URI, image(), Map.class);
assertThat(response.get("approved")).isEqualTo(true);
}
@Test
void slowResponseBecomesTimeoutException() throws IOException {
startServer(2500, 200, "{\"approved\":true}");
assertThatThrownBy(() -> client(baseUrl(), 1).post(URI, image(), Map.class))
.isInstanceOf(AiTimeoutException.class);
}
@Test
void serverErrorIsNotWrappedSoItCanBeRetried() throws IOException {
startServer(0, 500, "boom");
assertThatThrownBy(() -> client(baseUrl(), 2).post(URI, image(), Map.class))
.isInstanceOf(AiServerException.class);
}
@Test
void refusedConnectionBecomesUnavailableException() throws IOException {
int freePort;
try (ServerSocket socket = new ServerSocket(0)) {
freePort = socket.getLocalPort();
}
assertThatThrownBy(() -> client("http://localhost:" + freePort, 2).post(URI, image(), Map.class))
.isInstanceOf(AiUnavailableException.class);
}
private void startServer(long delayMs, int status, String body) throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext(URI, exchange -> {
exchange.getRequestBody().readAllBytes();
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
try {
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
} catch (IOException ignored) {
// клиент уже закрыл соединение по таймауту
}
});
server.start();
}
private String baseUrl() {
return "http://localhost:" + server.getAddress().getPort();
}
private static AiMultipartHttpClient client(String url, int imageTimeoutSeconds) {
AiProperties properties = new AiProperties();
properties.setUrl(url);
properties.setTimeout(10);
properties.setImageTimeout(imageTimeoutSeconds);
return new AiMultipartHttpClient(new WebClientConfig().aiWebClient(properties), properties);
}
private static MockMultipartFile image() {
return new MockMultipartFile("file", "photo.jpg", "image/jpeg", new byte[] {1, 2, 3});
}
}

View File

@@ -0,0 +1,102 @@
package com.krylov.refound.ai.client;
import static org.assertj.core.api.Assertions.assertThat;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.WebClientConfig;
import com.krylov.refound.ai.dto.ImageModerationResponse;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.dto.TextModerationRequest;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
/**
* Ответы AI-сервиса (Python, snake_case) должны разбираться в DTO целиком —
* в том числе detected_labels, которые уходят в ContentBlockedException.
*/
class AiResponseMappingTest {
private HttpServer server;
@AfterEach
void stopServer() {
if (server != null) {
server.stop(0);
}
}
@Test
void imageResponseMapsDetectedLabels() throws IOException {
startServer("/api/v1/moderation/image",
"{\"approved\":false,\"score\":0.93,\"reason\":\"FORBIDDEN_CONTENT\","
+ "\"label\":\"a gun\",\"detected_labels\":[\"a gun\",\"a knife\"]}");
ImageModerationResponse response = new AiMultipartHttpClient(webClient(), properties())
.post("/api/v1/moderation/image",
new MockMultipartFile("file", "photo.jpg", "image/jpeg", new byte[] {1, 2, 3}),
ImageModerationResponse.class);
assertThat(response.getApproved()).isFalse();
assertThat(response.getScore()).isEqualTo(0.93);
assertThat(response.getReason()).isEqualTo("FORBIDDEN_CONTENT");
assertThat(response.getDetectedLabels()).containsExactly("a gun", "a knife");
}
@Test
void textResponseIsDeserialized() throws IOException {
startServer("/api/v1/moderation/text",
"{\"approved\":false,\"score\":1.0,\"reason\":\"PROFANITY\",\"detected_labels\":[\"word\"]}");
ModerationResponse response = new AiHttpClient(webClient())
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
assertThat(response.getApproved()).isFalse();
assertThat(response.getScore()).isEqualTo(1.0);
assertThat(response.getReason()).isEqualTo("PROFANITY");
assertThat(response.getDetectedLabels()).containsExactly("word");
}
@Test
void textResponseWithoutLabelsIsDeserialized() throws IOException {
// Сейчас текстовый эндпоинт отдаёт только эти три поля
startServer("/api/v1/moderation/text", "{\"approved\":true,\"score\":0.01,\"reason\":\"OK\"}");
ModerationResponse response = new AiHttpClient(webClient())
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
assertThat(response.getApproved()).isTrue();
assertThat(response.getDetectedLabels()).isNull();
}
private void startServer(String uri, String body) throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext(uri, exchange -> {
exchange.getRequestBody().readAllBytes();
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
server.start();
}
private AiProperties properties() {
AiProperties properties = new AiProperties();
properties.setUrl("http://localhost:" + server.getAddress().getPort());
properties.setTimeout(5);
properties.setImageTimeout(5);
return properties;
}
private org.springframework.web.reactive.function.client.WebClient webClient() {
return new WebClientConfig().aiWebClient(properties());
}
}

View File

@@ -0,0 +1,122 @@
package com.krylov.refound.ai.pipeline;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.ai.client.TextModerationClient;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.exception.ContentBlockedException;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
class TextModerationProcessorTest {
private static final int MAX = 5000;
private TextModerationClient client;
private TextModerationProcessor processor;
@BeforeEach
void setUp() {
client = mock(TextModerationClient.class);
AiProperties properties = new AiProperties();
properties.setTextMaxLength(MAX);
processor = new TextModerationProcessor(client, properties);
}
@Test
void shortTextIsSentAsIs() {
when(client.moderate(anyString())).thenReturn(ok());
assertThat(processor.process(context("Потерял кошелёк", "В парке"))).isTrue();
verify(client).moderate("Потерял кошелёк\nВ парке");
}
@Test
void longTextIsSentInChunksWithinServiceLimit() {
when(client.moderate(anyString())).thenReturn(ok());
String description = "Потерял кошелёк в парке у фонтана. ".repeat(500); // ~17 500 символов
assertThat(processor.process(context("Кошелёк", description))).isTrue();
ArgumentCaptor<String> sent = ArgumentCaptor.forClass(String.class);
verify(client, times(4)).moderate(sent.capture());
assertThat(sent.getAllValues()).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(MAX));
}
@Test
void toxicTailOfLongTextBlocksPost() {
String description = "Нейтральный текст объявления. ".repeat(300) + "ТОКСИЧНО";
when(client.moderate(anyString())).thenAnswer(invocation ->
invocation.<String>getArgument(0).contains("ТОКСИЧНО") ? blocked() : ok());
assertThatThrownBy(() -> processor.process(context("Заголовок", description)))
.isInstanceOf(ContentBlockedException.class)
.satisfies(ex -> assertThat(((ContentBlockedException) ex).getDetectedLabels()).containsExactly("word"));
}
@Test
void unavailableServiceOnAnyChunkGivesNull() {
when(client.moderate(anyString())).thenReturn(ok()).thenReturn(null);
assertThat(processor.process(context("Заголовок", "а ".repeat(4000)))).isNull();
}
@Test
void blankTextIsNotSentToService() {
assertThat(processor.process(context(null, " "))).isTrue();
assertThat(processor.process(context(null, null))).isTrue();
verify(client, never()).moderate(anyString());
}
@Test
void splitCoversWholeTextWithOverlapAndRespectsLimit() {
String text = "слово ".repeat(3000);
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
assertThat(chunks).hasSizeGreaterThan(1);
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
assertThat(text).startsWith(chunks.get(0));
assertThat(text).endsWith(chunks.get(chunks.size() - 1));
for (int i = 1; i < chunks.size(); i++) {
String previous = chunks.get(i - 1);
// первые 200 символов следующей части повторяют конец предыдущей
assertThat(previous).endsWith(chunks.get(i).substring(0, 200));
}
}
@Test
void splitWithoutSpacesStillTerminates() {
String text = "x".repeat(12_345);
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
assertThat(String.join("", chunks).length()).isGreaterThanOrEqualTo(text.length());
}
private static ModerationContext context(String title, String description) {
return ModerationContext.builder().title(title).description(description).build();
}
private static ModerationResponse ok() {
return ModerationResponse.builder().approved(true).score(0.01).reason("OK").build();
}
private static ModerationResponse blocked() {
return ModerationResponse.builder()
.approved(false).score(1.0).reason("PROFANITY").detectedLabels(List.of("word")).build();
}
}

View File

@@ -0,0 +1,115 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.ChatRepository;
import com.krylov.refound.repository.MessageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.repository.UserRepository;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.simp.SimpMessagingTemplate;
class ChatServiceTest {
private ChatRepository chatRepository;
private UserRepository userRepository;
private PostRepository postRepository;
private MessageRepository messageRepository;
private ChatService chatService;
@BeforeEach
void setUp() {
chatRepository = mock(ChatRepository.class);
userRepository = mock(UserRepository.class);
postRepository = mock(PostRepository.class);
messageRepository = mock(MessageRepository.class);
chatService = new ChatService(chatRepository, messageRepository, mock(SimpMessagingTemplate.class),
userRepository, postRepository);
when(userRepository.existsById(anyLong())).thenReturn(true);
when(messageRepository.findFirstByChatIdOrderByCreatedAtDesc(any())).thenReturn(Optional.empty());
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
Chat chat = inv.getArgument(0);
chat.setId(100L);
return chat;
});
when(messageRepository.save(any(Message.class))).thenAnswer(inv -> {
Message message = inv.getArgument(0);
message.setId(500L);
return message;
});
}
private void postOwnedBy(long postId, long ownerId) {
User owner = new User();
owner.setId(ownerId);
Post post = new Post();
post.setId(postId);
post.setUser(owner);
when(postRepository.findById(postId)).thenReturn(Optional.of(post));
}
@Test
void startChatCreatesChatTogetherWithFirstMessage() {
postOwnedBy(41L, 19L);
ChatDto chat = chatService.startChat(14L, 19L, 41L, "Здравствуйте");
assertThat(chat.getPostId()).isEqualTo(41L);
assertThat(chat.getOtherUserId()).isEqualTo(19L);
ArgumentCaptor<Message> saved = ArgumentCaptor.forClass(Message.class);
verify(messageRepository).save(saved.capture());
assertThat(saved.getValue().getChatId()).isEqualTo(100L);
assertThat(saved.getValue().getContent()).isEqualTo("Здравствуйте");
}
@Test
void findChatDoesNotCreateChat() {
assertThat(chatService.findChat(14L, 19L, 41L)).isEmpty();
verify(chatRepository, never()).save(any());
}
@Test
void rejectsEmptyFirstMessageWithoutCreatingChat() {
postOwnedBy(41L, 19L);
assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, " "))
.isInstanceOf(ApiException.class);
verify(chatRepository, never()).save(any());
}
@Test
void rejectsPostOfThirdUser() {
postOwnedBy(41L, 7L);
assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, "Здравствуйте"))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
verify(chatRepository, never()).save(any());
}
@Test
void rejectsChatWithYourself() {
assertThatThrownBy(() -> chatService.startChat(19L, 19L, 41L, "Здравствуйте"))
.isInstanceOf(ApiException.class)
.hasMessageContaining("самим собой");
}
}

View File

@@ -0,0 +1,84 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.config.MinioProperties;
import java.net.URL;
import java.time.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
class FileStorageServicePresignedUrlTest {
private static final String KEY = "photo.webp";
private static final String CACHE_KEY = "files:presigned:" + KEY;
private static final String FRESH_URL = "http://minio/bucket/photo.webp?sig=fresh";
private S3Presigner presigner;
private StringRedisTemplate redis;
private ValueOperations<String, String> values;
private FileStorageService service;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() throws Exception {
presigner = mock(S3Presigner.class);
redis = mock(StringRedisTemplate.class);
values = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(values);
PresignedGetObjectRequest presigned = mock(PresignedGetObjectRequest.class);
when(presigned.url()).thenReturn(new URL(FRESH_URL));
when(presigner.presignGetObject(any(GetObjectPresignRequest.class))).thenReturn(presigned);
MinioProperties properties = mock(MinioProperties.class);
when(properties.bucket()).thenReturn("bucket");
service = new FileStorageService(mock(S3Client.class), presigner, properties, redis, new ImageOptimizer());
}
@Test
void returnsCachedUrlWithoutPresigningAgain() {
when(values.get(CACHE_KEY)).thenReturn("http://minio/cached");
assertThat(service.getCachedPresignedDownloadUrl(KEY)).isEqualTo("http://minio/cached");
verify(presigner, never()).presignGetObject(any(GetObjectPresignRequest.class));
}
@Test
void presignsAndCachesWhenMissing() {
String url = service.getCachedPresignedDownloadUrl(KEY);
assertThat(url).isEqualTo(FRESH_URL);
verify(values).set(eq(CACHE_KEY), eq(FRESH_URL), eq(Duration.ofHours(12)));
ArgumentCaptor<GetObjectPresignRequest> captor = ArgumentCaptor.forClass(GetObjectPresignRequest.class);
verify(presigner).presignGetObject(captor.capture());
assertThat(captor.getValue().signatureDuration()).isEqualTo(Duration.ofHours(24));
assertThat(captor.getValue().getObjectRequest().responseCacheControl()).contains("immutable");
}
@Test
void worksWhenRedisIsDown() {
when(values.get(anyString())).thenThrow(new RedisConnectionFailureException("down"));
org.mockito.Mockito.doThrow(new RedisConnectionFailureException("down"))
.when(values).set(anyString(), anyString(), any(Duration.class));
assertThat(service.getCachedPresignedDownloadUrl(KEY)).isEqualTo(FRESH_URL);
}
}

View File

@@ -0,0 +1,90 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Optional;
import java.util.Random;
import javax.imageio.ImageIO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ImageOptimizerTest {
private ImageOptimizer optimizer;
@BeforeEach
void setUp() {
optimizer = new ImageOptimizer();
optimizer.registerImageIoPlugins();
}
@Test
void largePhotoIsDownscaledToJpeg() throws IOException {
byte[] source = encode(noise(4032, 3024, BufferedImage.TYPE_INT_RGB), "jpg");
Optional<ImageOptimizer.OptimizedImage> result = optimizer.optimize(source, "image/jpeg");
assertThat(result).isPresent();
assertThat(result.get().contentType()).isEqualTo("image/jpeg");
assertThat(result.get().extension()).isEqualTo(".jpg");
assertThat(result.get().content().length).isLessThan(source.length);
BufferedImage decoded = decode(result.get().content());
assertThat(decoded.getWidth()).isEqualTo(ImageOptimizer.MAX_DIMENSION);
assertThat(decoded.getHeight()).isEqualTo(1200);
}
@Test
void smallFileIsKeptAsIs() throws IOException {
byte[] source = encode(noise(200, 150, BufferedImage.TYPE_INT_RGB), "jpg");
assertThat(source.length).isLessThanOrEqualTo((int) ImageOptimizer.SKIP_BELOW_BYTES);
assertThat(optimizer.optimize(source, "image/jpeg")).isEmpty();
}
@Test
void transparentPngStaysPng() throws IOException {
byte[] source = encode(noise(2400, 1800, BufferedImage.TYPE_INT_ARGB), "png");
Optional<ImageOptimizer.OptimizedImage> result = optimizer.optimize(source, "image/png");
assertThat(result).isPresent();
assertThat(result.get().contentType()).isEqualTo("image/png");
BufferedImage decoded = decode(result.get().content());
assertThat(decoded.getColorModel().hasAlpha()).isTrue();
assertThat(Math.max(decoded.getWidth(), decoded.getHeight())).isEqualTo(ImageOptimizer.MAX_DIMENSION);
}
@Test
void unreadableFileFallsBackToOriginal() {
byte[] garbage = new byte[(int) ImageOptimizer.SKIP_BELOW_BYTES + 1];
new Random(1).nextBytes(garbage);
assertThat(optimizer.optimize(garbage, "image/jpeg")).isEmpty();
}
/** Шум плохо сжимается — так файл гарантированно тяжелее порога. */
private static BufferedImage noise(int width, int height, int type) {
BufferedImage image = new BufferedImage(width, height, type);
Random random = new Random(42);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
image.setRGB(x, y, random.nextInt());
}
}
return image;
}
private static byte[] encode(BufferedImage image, String format) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, format, out);
return out.toByteArray();
}
private static BufferedImage decode(byte[] content) throws IOException {
return ImageIO.read(new ByteArrayInputStream(content));
}
}

View File

@@ -0,0 +1,394 @@
package com.krylov.refound.service.admin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krylov.refound.dto.AddressInfo;
import com.krylov.refound.dto.admin.AdminPostResponse;
import com.krylov.refound.entity.Image;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.PostCategory;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.enums.PostType;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.repository.ChatRepository;
import com.krylov.refound.repository.FavoriteRepository;
import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.FileStorageService;
import com.krylov.refound.service.GeocodingService;
import com.krylov.refound.service.StatisticsService;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheService;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
@ExtendWith(MockitoExtension.class)
class AdminPostServiceTest {
@Mock
private PostRepository postRepository;
@Mock
private ImageRepository imageRepository;
@Mock
private FavoriteRepository favoriteRepository;
@Mock
private ChatRepository chatRepository;
@Mock
private FileStorageService fileStorageService;
@Mock
private GeocodingService geocodingService;
@Mock
private PostCacheService postCacheService;
@Mock
private MapCacheService mapCacheService;
@Mock
private StatisticsService statisticsService;
@Spy
private ObjectMapper objectMapper = new ObjectMapper();
@InjectMocks
private AdminPostService service;
private static Post post(Long id, PostStatus status) {
User owner = new User();
owner.setId(7L);
owner.setLogin("ivan");
owner.setName("Иван");
owner.setLastName("Петров");
Post post = new Post();
post.setId(id);
post.setStatus(status);
post.setType(PostType.LOSS);
post.setTitle("Кот");
post.setCategory(PostCategory.ANIMAL);
post.setCity("Москва");
post.setUser(owner);
return post;
}
@Test
void getPosts_fillsOwnerAndImages() {
Post post = post(1L, PostStatus.ACTIVE);
Image image = new Image();
image.setId(5L);
image.setUrl("images/cat.png");
image.setPost(post);
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(post)));
when(imageRepository.findByPostIdIn(anyCollection())).thenReturn(List.of(image));
List<AdminPostResponse> content = service
.getPosts(null, null, null, PageRequest.of(0, 20))
.getContent();
assertThat(content).hasSize(1);
AdminPostResponse dto = content.get(0);
assertThat(dto.getOwnerLogin()).isEqualTo("ivan");
assertThat(dto.getOwnerFirstName()).isEqualTo("Иван");
assertThat(dto.getOwnerLastName()).isEqualTo("Петров");
assertThat(dto.getImages()).containsExactly("images/cat.png");
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
}
@Test
void getPosts_rejectsUnknownFilterValue() {
assertThatThrownBy(() -> service.getPosts(null, "WRONG", null, PageRequest.of(0, 20)))
.isInstanceOf(ApiException.class)
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void getPosts_clampsPageSize() {
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of()));
service.getPosts(null, null, null, PageRequest.of(0, 5000));
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
verify(postRepository).findAll(any(Specification.class), captor.capture());
assertThat(captor.getValue().getPageSize()).isEqualTo(100);
assertThat(captor.getValue().getSort().getOrderFor("createdAt")).isNotNull();
}
@Test
void getPosts_limitsStatusesToActiveAndClosed() {
assertThat(statusesUsedByGetPosts()).containsExactlyInAnyOrder(PostStatus.ACTIVE, PostStatus.CLOSED);
}
@Test
void getRejectedPosts_limitsStatusesToRejected() {
assertThat(statusesUsedByGetRejectedPosts()).containsExactly(PostStatus.REJECTED);
}
@Test
void feedsRejectStatusFromAnotherFeed() {
assertThatThrownBy(() -> service.getPosts(null, null, "REJECTED", PageRequest.of(0, 20)))
.isInstanceOf(ApiException.class)
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> service.getRejectedPosts(null, null, "ACTIVE", PageRequest.of(0, 20)))
.isInstanceOf(ApiException.class)
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
verify(postRepository, never()).findAll(any(Specification.class), any(Pageable.class));
}
@Test
void getRejectedPosts_returnsRejectedPostsWithOwnerAndImages() {
Post post = post(1L, PostStatus.REJECTED);
Image image = new Image();
image.setUrl("images/cat.png");
image.setPost(post);
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(post)));
when(imageRepository.findByPostIdIn(anyCollection())).thenReturn(List.of(image));
List<AdminPostResponse> content = service
.getRejectedPosts(null, null, null, PageRequest.of(0, 20))
.getContent();
assertThat(content).hasSize(1);
assertThat(content.get(0).getStatus()).isEqualTo(PostStatus.REJECTED);
assertThat(content.get(0).getOwnerLogin()).isEqualTo("ivan");
assertThat(content.get(0).getImages()).containsExactly("images/cat.png");
}
/**
* Статусы достаются из спецификации, которую сервис отдал в репозиторий: сам SQL
* без БД не проверить, а IN(...) собирается ровно из переданного allow-list.
*/
private Set<PostStatus> statusesUsedByGetPosts() {
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of()));
service.getPosts(null, null, null, PageRequest.of(0, 20));
return capturedStatuses();
}
private Set<PostStatus> statusesUsedByGetRejectedPosts() {
when(postRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of()));
service.getRejectedPosts(null, null, null, PageRequest.of(0, 20));
return capturedStatuses();
}
@SuppressWarnings("unchecked")
private Set<PostStatus> capturedStatuses() {
ArgumentCaptor<Specification<Post>> specCaptor = ArgumentCaptor.forClass(Specification.class);
verify(postRepository).findAll(specCaptor.capture(), any(Pageable.class));
Set<PostStatus> statuses = EnumSet.noneOf(PostStatus.class);
// Hibernate отдаёт из Path.in() объект, который ещё и Predicate, — в тесте так же.
Path<Object> path = (Path<Object>) mock(Path.class, withSettings().extraInterfaces(Predicate.class));
Expression<Integer> inExpression = (Expression<Integer>) (Expression<?>) path;
Root<Post> root = mock(Root.class);
// deep stubs: Specification.allOf комбинирует предикаты через CriteriaBuilder.and()
CriteriaBuilder cb = mock(CriteriaBuilder.class, RETURNS_DEEP_STUBS);
when(root.<Object>get(anyString())).thenReturn(path);
when(path.in(any(Collection.class))).thenAnswer(invocation -> {
statuses.addAll((Collection<PostStatus>) invocation.getArgument(0));
return inExpression;
});
specCaptor.getValue().toPredicate(root, mock(CriteriaQuery.class), cb);
return statuses;
}
@Test
void updatePost_keepsStatusAndInvalidatesCache() {
Post post = post(1L, PostStatus.ACTIVE);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
AdminPostResponse dto = service.updatePost(1L, "FOUND", "Найден кот", "Москва",
null, null, "описание", null, "+7", true, "100", List.of(), "[]");
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
assertThat(post.getStatus()).isEqualTo(PostStatus.ACTIVE);
assertThat(post.getType()).isEqualTo(PostType.FOUND);
assertThat(post.getCity()).isEqualTo("Москва");
assertThat(post.getIsReward()).isTrue();
verify(postCacheService).invalidatePosts();
verify(mapCacheService).clearMapMarkersCache();
}
@Test
void updatePost_dropsImagesMissingFromExistingList() {
Post post = post(1L, PostStatus.ACTIVE);
Image kept = new Image();
kept.setUrl("images/keep.png");
kept.setPost(post);
Image dropped = new Image();
dropped.setUrl("images/drop.png");
dropped.setPost(post);
post.getImages().addAll(List.of(kept, dropped));
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
service.updatePost(1L, "LOSS", "Кот", "Москва", null, null, null, null, null,
false, null, List.of(), "[\"images/keep.png\"]");
assertThat(post.getImages()).extracting(Image::getUrl).containsExactly("images/keep.png");
verify(fileStorageService).deleteFile("images/drop.png");
verify(fileStorageService, never()).deleteFile("images/keep.png");
}
@Test
void updatePost_fallsBackToAddressWhenGeocodingUnavailable() {
Post post = post(1L, PostStatus.ACTIVE);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
when(geocodingService.getAddress("55.0", "37.0"))
.thenThrow(new ApiException(com.krylov.refound.enums.ErrorCode.INTERNAL_ERROR,
"Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE));
service.updatePost(1L, "LOSS", "Кот", "Тверь", 55.0, 37.0, null, null, null,
false, null, List.of(), "[]");
assertThat(post.getCity()).isEqualTo("Тверь");
}
@Test
void updatePost_keepsClientAddressAndTakesCityFromGeocoder() {
Post post = post(1L, PostStatus.ACTIVE);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
when(geocodingService.getAddress("55.0", "37.0"))
.thenReturn(new com.krylov.refound.dto.AddressInfo("Москва", "Тверской район"));
AdminPostResponse dto = service.updatePost(1L, "LOSS", "Кот", " Москва, Тверская улица, 7 ",
55.0, 37.0, null, null, null, false, null, List.of(), "[]");
assertThat(post.getAddress()).isEqualTo("Москва, Тверская улица, 7");
assertThat(post.getCity()).isEqualTo("Москва");
assertThat(post.getDistrict()).isEqualTo("Тверской район");
assertThat(dto.getAddress()).isEqualTo("Москва, Тверская улица, 7");
}
@Test
void updateStatus_closesPostAndIncrementsStatistics() {
Post post = post(1L, PostStatus.ACTIVE);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
AdminPostResponse dto = service.updateStatus(1L, "CLOSED");
assertThat(dto.getStatus()).isEqualTo(PostStatus.CLOSED);
verify(statisticsService).incrementFound();
verify(postCacheService).invalidatePosts();
}
@Test
void updateStatus_reopeningDoesNotTouchStatistics() {
Post post = post(1L, PostStatus.CLOSED);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
when(postRepository.save(any(Post.class))).thenAnswer(inv -> inv.getArgument(0));
AdminPostResponse dto = service.updateStatus(1L, "active");
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
verify(statisticsService, never()).incrementFound();
}
@Test
void updateStatus_sameStatusIsNoop() {
Post post = post(1L, PostStatus.ACTIVE);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
AdminPostResponse dto = service.updateStatus(1L, "ACTIVE");
assertThat(dto.getStatus()).isEqualTo(PostStatus.ACTIVE);
verify(postRepository, never()).save(any(Post.class));
verify(statisticsService, never()).incrementFound();
verify(postCacheService, never()).invalidatePosts();
}
@Test
void updateStatus_rejectsGarbage() {
assertThatThrownBy(() -> service.updateStatus(1L, "banana"))
.isInstanceOf(ApiException.class)
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void updatePost_throwsNotFoundForMissingPost() {
when(postRepository.findById(99L)).thenReturn(java.util.Optional.empty());
assertThatThrownBy(() -> service.updatePost(99L, "LOSS", "t", null, null, null, null, null,
null, false, null, List.of(), "[]"))
.isInstanceOf(ApiException.class)
.satisfies(ex -> assertThat(((ApiException) ex).getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void deletePost_clearsFilesFavoritesAndChatLinks() {
Post post = post(1L, PostStatus.CLOSED);
Image image = new Image();
image.setUrl("images/cat.png");
image.setPost(post);
post.getImages().add(image);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
service.deletePost(1L);
verify(fileStorageService).deleteFile("images/cat.png");
verify(favoriteRepository).deleteByPostIn(anyList());
verify(chatRepository).clearPostReference(1L);
verify(postRepository).delete(post);
verify(postCacheService).invalidatePosts();
}
@Test
void deletePost_doesNotFailWhenFileStorageIsDown() {
Post post = post(1L, PostStatus.CLOSED);
Image image = new Image();
image.setUrl("images/cat.png");
image.setPost(post);
post.getImages().add(image);
when(postRepository.findById(1L)).thenReturn(java.util.Optional.of(post));
org.mockito.Mockito.doThrow(new RuntimeException("MinIO недоступен"))
.when(fileStorageService).deleteFile(any());
service.deletePost(1L);
verify(postRepository).delete(post);
}
}