Compare commits
60 Commits
master
...
3eab2f30e0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3eab2f30e0 | ||
|
|
45854ef2bd | ||
|
|
1a3be8e3ee | ||
|
|
1cd72fbec4 | ||
|
|
aa7c9f25f0 | ||
|
|
bbc9079502 | ||
|
|
838e4aa6d5 | ||
|
|
d6c88f9e57 | ||
|
|
f660e6828b | ||
|
|
0dba36f3aa | ||
|
|
7766fb0b07 | ||
|
|
d782bee645 | ||
|
|
13d09d0073 | ||
|
|
ee5fb4e0e0 | ||
|
|
248b4de752 | ||
|
|
ba6935bb1f | ||
|
|
4ff61d8eda | ||
|
|
3dcd27d08a | ||
|
|
85a2773f60 | ||
|
|
2f52e6df70 | ||
|
|
477737c161 | ||
|
|
48351398b5 | ||
|
|
a696a21a1f | ||
|
|
83270a8ece | ||
|
|
7b81c18614 | ||
|
|
6b647e0bbf | ||
|
|
3fd045131c | ||
|
|
a909b1f08b | ||
|
|
6e001fbc41 | ||
|
|
98e6789b7e | ||
|
|
5cd60b6318 | ||
|
|
71e69c4af8 | ||
|
|
a68b89981c | ||
|
|
d63a3309fa | ||
|
|
a564e6f97d | ||
|
|
91ceafe75b | ||
|
|
057cdddff6 | ||
|
|
72486a54f7 | ||
|
|
96b4be5e6f | ||
|
|
c1b14da7b9 | ||
|
|
307c4ae432 | ||
|
|
4d9cb9946d | ||
|
|
c83d41a036 | ||
|
|
13bb0c8503 | ||
|
|
03e2b36c8d | ||
|
|
f8ccb15185 | ||
|
|
01ac227bdb | ||
|
|
9eae82f6df | ||
|
|
cd0d2a4081 | ||
|
|
73463f6c5b | ||
|
|
da7d68c31a | ||
|
|
45c4273ea8 | ||
|
|
008852c781 | ||
|
|
d19f03d412 | ||
|
|
5ea7b438f5 | ||
|
|
9dbf2dd043 | ||
|
|
e321fa4c60 | ||
|
|
4119b767c3 | ||
|
|
68d53fadf3 | ||
|
|
818c8f6a11 |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
||||
.git
|
||||
.gradle
|
||||
build
|
||||
target
|
||||
.idea
|
||||
60
.env.example
Normal file
60
.env.example
Normal file
@@ -0,0 +1,60 @@
|
||||
# Шаблон переменных окружения. Скопируй в .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 (HMAC-SHA): строка не короче 32 байт. Значения
|
||||
# по умолчанию нет — без переменной приложение не стартует.
|
||||
# Сгенерировать, например, так:
|
||||
# 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
|
||||
# AI_IMAGE_TIMEOUT=30
|
||||
# AI_TEXT_MAX_LENGTH=5000
|
||||
# FFMPEG_PATH=ffmpeg
|
||||
# DB_URL=jdbc:postgresql://localhost:5432/nahodka
|
||||
# DB_USER=user
|
||||
# DB_PASSWORD=pass
|
||||
# CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
|
||||
# FORWARD_HEADERS_STRATEGY=native
|
||||
# RATE_LIMIT_ENABLED=true
|
||||
# WS_CLUSTER_BROADCAST=true
|
||||
# GEOCODING_URL=https://nominatim.openstreetmap.org
|
||||
# GEOCODING_USER_AGENT=ReFound/1.0 (admin@example.com)
|
||||
# GEOCODING_MIN_INTERVAL=PT1S
|
||||
# STORAGE_ORPHAN_CLEANUP_ENABLED=true
|
||||
# ADS_TIMEZONE=Europe/Moscow
|
||||
# ADS_TRACKING_SECRET=
|
||||
# ADS_REQUIRE_TRACKING_TOKEN=false
|
||||
# JWT_ACCESS_EXPIRATION=900000
|
||||
# JWT_REFRESH_EXPIRATION=604800000
|
||||
# JPA_DDL_AUTO=validate
|
||||
# JPA_SHOW_SQL=false
|
||||
|
||||
# Защита номеров от сбора (docs/phone-protection.md)
|
||||
# PHONE_REVEAL_SECRET=
|
||||
# id объявлений-ловушек через запятую
|
||||
# PHONE_TRAP_POST_IDS=
|
||||
16
.gitea/workflows/deploy.yml
Normal file
16
.gitea/workflows/deploy.yml
Normal 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
|
||||
41
.github/workflows/ci.yml
vendored
Normal file
41
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master]
|
||||
push:
|
||||
branches: [master]
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: gradle test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 25
|
||||
cache: gradle
|
||||
|
||||
# gradlew мог попасть в репозиторий с CRLF и без бита исполнения
|
||||
- name: Prepare gradlew
|
||||
run: sed -i 's/\r$//' gradlew && chmod +x gradlew
|
||||
|
||||
# Testcontainers поднимает PostgreSQL 15 в Docker раннера
|
||||
- name: Test
|
||||
run: ./gradlew test --no-daemon
|
||||
|
||||
- name: Upload test reports
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: test-reports
|
||||
path: build/reports/tests
|
||||
retention-days: 14
|
||||
18
Dockerfile
Normal file
18
Dockerfile
Normal 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"]
|
||||
14
build.gradle
14
build.gradle
@@ -52,6 +52,11 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
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
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5'
|
||||
@@ -60,6 +65,11 @@ dependencies {
|
||||
//WebClient
|
||||
implementation 'org.springframework.boot:spring-boot-starter-webflux'
|
||||
|
||||
// Фоновые задачи (@Scheduled) при нескольких экземплярах выполняет только один —
|
||||
// блокировка в Redis
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-spring:6.10.0'
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-provider-redis-spring:6.10.0'
|
||||
|
||||
implementation 'org.springframework.retry:spring-retry'
|
||||
implementation 'org.springframework:spring-aspects'
|
||||
|
||||
@@ -70,6 +80,10 @@ dependencies {
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
|
||||
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'
|
||||
}
|
||||
|
||||
|
||||
389
docs/advertising.md
Normal file
389
docs/advertising.md
Normal file
@@ -0,0 +1,389 @@
|
||||
# Реклама в ReFound
|
||||
|
||||
В приложении два вида рекламы:
|
||||
|
||||
- **ротируемая реклама** (`Campaign` → `Advertising`) — баннеры-картинки и
|
||||
ролики, которые клиент запрашивает через `GET /api/ads/next`; выбор
|
||||
учитывает веса, дневной лимит показов кампании одному пользователю и паузу
|
||||
между показами, а показы и клики подтверждаются подписанным токеном;
|
||||
- **полноэкранная реклама** (`FullscreenAdvertising`) — один ролик на всё
|
||||
приложение (обычно показывается при запуске), активным может быть только один.
|
||||
|
||||
Пакеты: `controller/advertising`, `service/advertising`,
|
||||
`entity/advertising`, `repository/advertising`, `dto/advertising`,
|
||||
`enums/advertising`. Таблицы — changelog `create/010-add-advertising.yaml`,
|
||||
`create/011-create-fullscreen-ads.yaml` и правки `alter/012`, `alter/013`, `add/016`.
|
||||
|
||||
## Сущности
|
||||
|
||||
```
|
||||
campaign 1 ──── * advertising 1 ──── * impression
|
||||
1 ──── * click
|
||||
fullscreen_advertising (отдельно)
|
||||
```
|
||||
|
||||
### `Campaign` — рекламная кампания
|
||||
|
||||
| Поле | Смысл |
|
||||
|---|---|
|
||||
| `name` | название (обязательно, ≤ 255) |
|
||||
| `status` | `DRAFT`, `ACTIVE`, `PAUSED`, `FINISHED` |
|
||||
| `startDate`, `endDate` | окно показа; реклама выдаётся, только если сейчас между ними |
|
||||
| `dailyImpressionCap` | сколько показов кампании (всех её объявлений вместе) один пользователь/сессия может увидеть за календарные сутки (`ads.timezone`) |
|
||||
| `createdAt` | время создания |
|
||||
|
||||
### `Advertising` — объявление (креатив) кампании
|
||||
|
||||
| Поле | Смысл |
|
||||
|---|---|
|
||||
| `campaign` | кампания (обязательно) |
|
||||
| `type` | `IMAGE` или `VIDEO` |
|
||||
| `mediaKey` | ключ файла в бакете `ads-media`; у видео пуст до конца транскодинга |
|
||||
| `targetUrl` | куда ведёт клик; только абсолютный `http(s)`, ≤ 1024 |
|
||||
| `weight` | вес в ротации, > 0 |
|
||||
| `transcodingStatus` | `PENDING`, `PROCESSING`, `READY`, `FAILED`; у картинки сразу `READY` |
|
||||
|
||||
### `Impression` и `Click` — учёт показов и кликов
|
||||
|
||||
`advertising`, `userId` (если пользователь авторизован), `sessionId`
|
||||
(≤ 64 символов, только `[A-Za-z0-9._:-]`; без идентификатора — `unknown`),
|
||||
время `shownAt`/`clickedAt`. Отчёт по ним — `GET /api/v1/admin/campaigns/{id}/stats`.
|
||||
|
||||
### `FullscreenAdvertising` — полноэкранный ролик
|
||||
|
||||
`mediaKey`, `targetUrl` (необязательна; если задана — `http(s)`), `status`
|
||||
(`DRAFT`, `ACTIVE`, `INACTIVE`), `transcodingStatus`, `createdAt`.
|
||||
Частичный уникальный индекс `uq_fullscreen_ad_single_active` гарантирует в БД
|
||||
не больше одной строки со статусом `ACTIVE`.
|
||||
|
||||
## Жизненный цикл кампании
|
||||
|
||||
```
|
||||
PATCH status=ACTIVE PATCH status=PAUSED
|
||||
DRAFT ─────────────────────► ACTIVE ◄──────────────────────► PAUSED
|
||||
│ PATCH status=ACTIVE │
|
||||
│ FINISHED │ FINISHED
|
||||
▼ ▼
|
||||
FINISHED (конечный, вернуть нельзя)
|
||||
```
|
||||
|
||||
- Новая кампания всегда создаётся в `DRAFT` (`CampaignService.createCampaign`).
|
||||
- Разрешённые переходы — `CampaignService.isValidTransition`; переход в тот
|
||||
же статус или недопустимый → **422** `INVALID_STATUS_TRANSITION`.
|
||||
- Кампании `ACTIVE` и `PAUSED` с прошедшим `endDate` раз в 10 минут
|
||||
переводятся в `FINISHED` (`CampaignLifecycleService.finishExpiredCampaigns`,
|
||||
ShedLock — выполняет один экземпляр). Даты кампании трактуются в поясе
|
||||
`ads.timezone` (по умолчанию `Europe/Moscow`).
|
||||
- Удаления кампаний и объявлений в API нет.
|
||||
|
||||
Объявление участвует в ротации, когда одновременно:
|
||||
`campaign.status = ACTIVE`, `startDate ≤ now ≤ endDate`,
|
||||
`advertising.transcodingStatus = READY`, `mediaKey` задан
|
||||
(`AdvertisingRepository.findEligible`).
|
||||
|
||||
## Загрузка медиа
|
||||
|
||||
### Картинка (`IMAGE`)
|
||||
|
||||
1. `POST /api/v1/admin/ads/image` (multipart, поле `file`) →
|
||||
`AdvertisingMediaService.uploadImage`:
|
||||
- файл не пустой, есть имя, ≤ 10 МБ, `Content-Type` jpeg/png/webp;
|
||||
- формат подтверждается сигнатурой файла (`util/ImageFormat`), расширение
|
||||
и `Content-Type` объекта берутся из неё;
|
||||
- ключ `images/<uuid>.<ext>` в бакете `ads-media`. Сжатия нет (в отличие
|
||||
от фото объявлений).
|
||||
- Ответ: `{"mediaKey": "images/....png"}`.
|
||||
2. `POST /api/v1/admin/ads` с `type=IMAGE` и этим `mediaKey` — объявление
|
||||
создаётся сразу в `READY`.
|
||||
|
||||
### Видео (`VIDEO`) — прямая загрузка в MinIO и транскодинг
|
||||
|
||||
```
|
||||
админка бэкенд MinIO (ads-media)
|
||||
│ POST /api/v1/admin/ads (type=VIDEO) ──► Advertising(PENDING, mediaKey=null)
|
||||
│ POST /{id}/video/presign-upload {contentType}
|
||||
│ ──► sourceKey = sources/{id}/<uuid>.mp4|.mov|.webm
|
||||
│ ◄── {uploadUrl, sourceKey, expiryMinutes: 30}
|
||||
│ PUT uploadUrl (файл, тот же Content-Type) ─────────────────────────────► sources/{id}/...
|
||||
│ POST /{id}/video/confirm-upload {sourceKey}
|
||||
│ ──► проверка: sourceKey начинается с sources/{id}/
|
||||
│ ──► transcodingStatus = PROCESSING, событие VideoUploadConfirmedEvent
|
||||
│ ◄── 202 Accepted
|
||||
│ после коммита: VideoUploadEventListener (@TransactionalEventListener AFTER_COMMIT)
|
||||
│ → AdvertisingTranscodingService (@Async "ffmpegExecutor")
|
||||
│ → VideoTranscoderService.transcode:
|
||||
│ скачать исходник во временный файл ◄──────────── sources/{id}/...
|
||||
│ ffmpeg → H.264 720p, AAC 128k, faststart
|
||||
│ залить videos/<uuid>.mp4 ─────────────────────► videos/...
|
||||
│ удалить исходник (и при ошибке тоже) ─────────► ✕ sources/{id}/...
|
||||
│ → AdvertisingStatusService.markReady / markFailed
|
||||
│ ◄── STOMP /topic/ads/{id}/status {advertisingId, transcodingStatus}
|
||||
│ GET /{id}/status — то же самое опросом
|
||||
```
|
||||
|
||||
Детали:
|
||||
|
||||
- Допустимые типы — `video/mp4`, `video/quicktime`, `video/webm`; иначе 400.
|
||||
- Presigned PUT подписан на 30 минут и на конкретный `Content-Type`
|
||||
(`AdvertisingMediaService.getPresignedUploadUrl`).
|
||||
- Браузер грузит файл в MinIO напрямую, поэтому бакету `ads-media` нужен
|
||||
CORS (`minio/cors.json`, накладывает `mc-init`). Сейчас там только
|
||||
`localhost:5173` и `localhost:3000` — для боевого домена правило нужно дополнить.
|
||||
- `confirm-upload` принимает только ключ из `sources/{id}/` этого объявления:
|
||||
транскодер удаляет исходник после работы, и чужой ключ (например, готовый
|
||||
ролик другого объявления) был бы удалён.
|
||||
- ffmpeg: `ffmpeg -nostdin -y -i <src> -vf scale=-2:720 -c:v libx264 -preset medium
|
||||
-b:v 1500k -maxrate 2000k -bufsize 3000k -c:a aac -b:a 128k -movflags +faststart <out>`.
|
||||
Путь — `ffmpeg.binary-path` (`FFMPEG_PATH`); в Docker-образе ffmpeg
|
||||
ставится из apt. Вывод пишется во временный лог, при ошибке или таймауте
|
||||
(5 минут — процесс убивается) в лог приложения попадает хвост вывода.
|
||||
- Пул `ffmpegExecutor` (`config/AsyncConfig`): 2 потока, очередь 20. При
|
||||
переполнении очереди `@Async` бросит `TaskRejectedException` уже после
|
||||
коммита — статус останется `PROCESSING`.
|
||||
- Статус транскодинга шлётся в `/topic/ads/{id}/status` через Redis во все
|
||||
экземпляры (`config/ClusterMessaging`), так что админ получит его, к какому
|
||||
бы экземпляру ни был подключён. Подписаться на
|
||||
`/topic/ads/**` и `/topic/fullscreen-ads/**` может только `ADMIN`
|
||||
(`util/WsStompInterceptor`).
|
||||
|
||||
Полноэкранный ролик загружается так же, но через
|
||||
`/api/v1/admin/fullscreen-ads/{id}/video/...`: ключи `fullscreen-sources/{id}/...`,
|
||||
результат `fullscreen/<uuid>.mp4`, сервисы `FullscreenAdTranscodingService`,
|
||||
`FullscreenAdStatusService`, топик `/topic/fullscreen-ads/{id}/status`.
|
||||
|
||||
## Как это устроено: выдача → показ → клик
|
||||
|
||||
Схема та же, что у рекламных серверов: **выдача** (ad decision) ещё не показ.
|
||||
Клиент получает рекламу вместе с подписанным **токеном показа**, отрисовывает
|
||||
её и сообщает о показе, возвращая токен; клик сообщается с тем же токеном.
|
||||
|
||||
```
|
||||
клиент бэкенд Redis
|
||||
│ GET /api/ads/next ───────► кандидаты (кэш 30 с) ──────────────────────────
|
||||
│ дневные показы кампаний субъекту ── MGET ──► ad:cap:<субъект>:<кампания>:<день>
|
||||
│ взвешенный выбор
|
||||
│ пауза между показами ── SET NX EX 30 ──────► ad:cooldown:<субъект>
|
||||
│ ◄── {advertisingId, type, mediaUrl, targetUrl, impressionToken}
|
||||
│ (реклама отрисована)
|
||||
│ POST /api/ads/impression {advertisingId, sessionId, token}
|
||||
│ подпись и срок токена (HMAC, 1 ч)
|
||||
│ токен ещё не засчитан ── SET NX ───────────► ad:imp:<nonce>
|
||||
│ +1 к дневному счётчику кампании ── INCR ──► ad:cap:...
|
||||
│ строка impression в БД
|
||||
│ (клик)
|
||||
│ POST /api/ads/click {advertisingId, sessionId, token}
|
||||
│ подпись, однократность ── SET NX ─────────► ad:clk:<nonce>
|
||||
│ строка click в БД
|
||||
```
|
||||
|
||||
### Выдача — `GET /api/ads/next` (публично)
|
||||
|
||||
Заголовок `X-Session-Id` — стабильный идентификатор устройства/браузера.
|
||||
Токен авторизации необязателен: если он есть, лимиты считаются по пользователю.
|
||||
|
||||
`AdvertisingSelectionService.selectAdvertising`:
|
||||
|
||||
1. **Субъект** — `u{userId}` для авторизованного пользователя, иначе
|
||||
`s{sessionId}`. Сессия — `X-Session-Id` (недопустимые символы заменяются
|
||||
`_`, обрезается до 64), без заголовка — `ip:{адрес клиента}`. HTTP-сессия
|
||||
на сервере не создаётся.
|
||||
2. **Кандидаты** — `findEligible(now)`: объявления активных кампаний в окне дат с
|
||||
готовым медиа. Список держится в памяти экземпляра `ads.eligible-cache-ttl`
|
||||
(30 с) и сбрасывается сразу после правок в админке этого экземпляра;
|
||||
остальные экземпляры увидят правку в пределах 30 секунд.
|
||||
3. **Дневной лимит** — одним `MGET` читаются показы кампаний субъекту за
|
||||
сегодня (`ad:cap:<субъект>:<кампания>:<yyyyMMdd>`, сутки в `ads.timezone`).
|
||||
Кампании, достигшие `dailyImpressionCap`, отбрасываются.
|
||||
4. **Взвешенный выбор** среди оставшихся: ключ `u^(1/weight)`, побеждает
|
||||
максимальный (Efraimidis–Spirakis) — вероятность пропорциональна весу.
|
||||
5. **Пауза между показами** — `SET ad:cooldown:<субъект> NX EX 30`
|
||||
(`ads.session-cooldown`). Если ключ уже есть — 204. Ставится в момент выдачи,
|
||||
поэтому параллельные запросы одного клиента не получат две рекламы.
|
||||
6. **Токен показа** — `AdTrackingTokenService.issue(adId, campaignId, subject)`.
|
||||
|
||||
Нет кандидатов, все кампании исчерпали лимит, идёт пауза или недоступен
|
||||
Redis → **204** (реклама не показывается, запрос не падает).
|
||||
|
||||
Ответ 200:
|
||||
|
||||
```json
|
||||
{
|
||||
"advertisingId": 12,
|
||||
"type": "VIDEO",
|
||||
"mediaUrl": "/api/v1/ads-media/videos/3f0c....mp4",
|
||||
"targetUrl": "https://example.com/promo",
|
||||
"impressionToken": "djF8MTJ8M3x1NDJ8MTc2MDk1...Q.4mK1f..."
|
||||
}
|
||||
```
|
||||
|
||||
`mediaUrl` — относительный путь на прокси бэкенда, а не presigned URL:
|
||||
presigned-ссылка подписана под адрес MinIO, который снаружи может быть
|
||||
недоступен.
|
||||
|
||||
### Токен показа
|
||||
|
||||
`AdTrackingTokenService`: `base64url(v1|adId|campaignId|subject|issuedAt|nonce)`
|
||||
`.` `base64url(HMAC-SHA256)`. Ключ — `ads.tracking.secret`
|
||||
(`ADS_TRACKING_SECRET`), если не задан — `jwt.secret`. Срок —
|
||||
`ads.tracking.token-ttl` (1 час).
|
||||
|
||||
Что даёт токен:
|
||||
|
||||
- **нельзя засчитать показ рекламы, которая не выдавалась**, или приписать его
|
||||
другому пользователю — субъект и кампания берутся из подписанного токена, а
|
||||
не из тела запроса;
|
||||
- **повтор не учитывается** — каждый nonce засчитывается один раз
|
||||
(`ad:imp:<nonce>`, `ad:clk:<nonce>` на срок жизни токена);
|
||||
- **лимит считается по факту показа**: дневной счётчик растёт на `/impression`,
|
||||
а не при выдаче. Выданная, но не показанная реклама лимит не тратит
|
||||
(от частых запросов защищает пауза между показами).
|
||||
|
||||
### Показы и клики
|
||||
|
||||
| Запрос | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `POST /api/ads/impression` (публично) | `{"advertisingId": 12, "sessionId": "...", "token": "..."}` | 202 |
|
||||
| `POST /api/ads/click` (публично) | `{"advertisingId": 12, "sessionId": "...", "token": "..."}` | 202 |
|
||||
|
||||
`AdvertisingTrackingService`:
|
||||
|
||||
- с токеном: неверная подпись, истёкший срок, `advertisingId` не из токена,
|
||||
повтор → событие молча пропускается (202, без записи);
|
||||
- без токена (старые клиенты): пока `ads.tracking.require-token=false`,
|
||||
событие учитывается по-старому — по `advertisingId` и субъекту из
|
||||
запроса, без защиты от повторов. После обновления фронта включите
|
||||
`ADS_REQUIRE_TRACKING_TOKEN=true` — запросы без токена получат 400;
|
||||
- `/impression` читает тело строкой и разбирает JSON сам — так его можно слать
|
||||
через `navigator.sendBeacon` с `Content-Type: text/plain`;
|
||||
- оба эндпоинта ограничены по IP (`rate-limit.rules`, 120 запросов в минуту).
|
||||
|
||||
Если Redis недоступен при показе: проверить повтор нельзя — событие
|
||||
засчитывается; дневной счётчик не вырастет, строка в БД сохраняется.
|
||||
|
||||
### Медиа — `GET /api/v1/ads-media/{*key}` (публично)
|
||||
|
||||
`AdvertisingMediaService.downloadMedia` отдаёт файл из `ads-media` потоком,
|
||||
с поддержкой `Range` (206/416) и `Cache-Control: public, max-age=2592000`.
|
||||
Подробно — в [images-storage.md](images-storage.md#медиа-рекламы--get-apiv1ads-mediakey-публично).
|
||||
|
||||
### Полноэкранная реклама — `GET /api/fullscreen-ad` (публично)
|
||||
|
||||
`FullscreenAdController`: берёт запись со статусом `ACTIVE`. Нет активной или
|
||||
у неё пустой `mediaKey` → 204. Иначе:
|
||||
|
||||
```json
|
||||
{ "mediaUrl": "/api/v1/ads-media/fullscreen/....mp4", "targetUrl": "https://..." }
|
||||
```
|
||||
|
||||
Лимитов и паузы у полноэкранной рекламы нет — частоту показа решает клиент;
|
||||
показы полноэкранного ролика не учитываются.
|
||||
|
||||
## Статистика
|
||||
|
||||
`GET /api/v1/admin/campaigns/{id}/stats?from=2026-10-01&to=2026-10-20`
|
||||
(`CampaignStatsService`) — показы, клики и CTR (в процентах) по кампании и
|
||||
каждому её объявлению за дни `from..to` включительно (по умолчанию последние
|
||||
30 дней, не больше 366):
|
||||
|
||||
```json
|
||||
{
|
||||
"campaignId": 3, "from": "2026-10-01", "to": "2026-10-20",
|
||||
"impressions": 1200, "clicks": 18, "ctr": 1.5,
|
||||
"advertisings": [ {"advertisingId": 12, "impressions": 800, "clicks": 14, "ctr": 1.75} ]
|
||||
}
|
||||
```
|
||||
|
||||
Для запросов есть индексы `impression(advertising_id, shown_at)` и
|
||||
`click(advertising_id, clicked_at)` (changelog `add/021`).
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
### Публичные
|
||||
|
||||
| Метод и путь | Что делает |
|
||||
|---|---|
|
||||
| `GET /api/ads/next` | выбрать объявление (200 или 204) |
|
||||
| `POST /api/ads/impression` | записать показ |
|
||||
| `POST /api/ads/click` | записать клик |
|
||||
| `GET /api/fullscreen-ad` | активный полноэкранный ролик (200 или 204) |
|
||||
| `GET /api/v1/ads-media/{*key}` | файл медиа (поток, Range) |
|
||||
|
||||
### Админка (роль `ADMIN`: `/api/v1/admin/**` + `@PreAuthorize`)
|
||||
|
||||
Кампании — `CampaignAdminController`, `/api/v1/admin/campaigns`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /` | — | список `CampaignResponseDto` (новые сверху) |
|
||||
| `GET /{campaignId}` | — | `CampaignResponseDto`; нет → 404 |
|
||||
| `POST /` | `{name, startDate, endDate, dailyImpressionCap}` | 201; `startDate ≥ endDate` или кап ≤ 0 → 400 |
|
||||
| `PUT /{campaignId}` | то же | 200; те же проверки → 400 |
|
||||
| `PATCH /{campaignId}/status` | `{status}` | 200 с новым статусом; недопустимый переход → 422 |
|
||||
| `GET /{campaignId}/stats?from=&to=` | — | `CampaignStatsDto` (раздел «Статистика») |
|
||||
|
||||
`CampaignResponseDto`: `{id, name, status, startDate, endDate, dailyImpressionCap}`.
|
||||
|
||||
Объявления — `AdvertisingAdminController`, `/api/v1/admin/ads`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /?campaignId=` | — | список `AdvertisingAdminResponseDto` |
|
||||
| `POST /` | `{campaignId, type, mediaKey, targetUrl, weight}` | 201; кампании нет → 404; `weight ≤ 0`, `IMAGE` без `mediaKey`, плохой `targetUrl` → 400 |
|
||||
| `PUT /{advertisingId}` | `{targetUrl, weight}` | 200 |
|
||||
| `POST /image` | multipart `file` | `{mediaKey}` |
|
||||
| `POST /{advertisingId}/video/presign-upload` | `{contentType}` | `{uploadUrl, sourceKey, expiryMinutes}` |
|
||||
| `POST /{advertisingId}/video/confirm-upload` | `{sourceKey}` | 202; чужой ключ → 400 |
|
||||
| `GET /{advertisingId}/status` | — | `{advertisingId, transcodingStatus}` |
|
||||
|
||||
`AdvertisingAdminResponseDto`: `{id, campaignId, type, targetUrl, weight, transcodingStatus}`.
|
||||
|
||||
Полноэкранная реклама — `FullscreenAdAdminController`, `/api/v1/admin/fullscreen-ads`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /` | — | список `FullscreenAdAdminResponseDto` |
|
||||
| `POST /` | `{targetUrl}` | 201, статус `DRAFT` |
|
||||
| `POST /{id}/video/presign-upload` | `{contentType}` | как у объявлений |
|
||||
| `POST /{id}/video/confirm-upload` | `{sourceKey}` | 202; ключ не из `fullscreen-sources/{id}/` → 400 |
|
||||
| `GET /{id}/status` | — | `{advertisingId, transcodingStatus}` |
|
||||
| `PATCH /{id}/activate` | — | делает ролик единственным `ACTIVE` (прежний → `INACTIVE`); ролик не `READY` → 422 |
|
||||
| `PATCH /{id}/deactivate` | — | `INACTIVE` |
|
||||
|
||||
`FullscreenAdAdminResponseDto`: `{id, targetUrl, status, transcodingStatus}`.
|
||||
При активации прежний активный ролик сохраняется в БД первым (`saveAndFlush`),
|
||||
иначе порядок UPDATE мог нарушить уникальный индекс.
|
||||
|
||||
## Ошибки
|
||||
|
||||
| Ситуация | Ответ |
|
||||
|---|---|
|
||||
| нет кампании/объявления/ролика (`EntityNotFoundException`) | 404 `NOT_FOUND` |
|
||||
| невалидное тело (`@Valid`), плохая ссылка, неверный тип файла | 400 `VALIDATION_ERROR` (или пустой 400 из контроллера) |
|
||||
| недопустимый переход статуса кампании | 422 `INVALID_STATUS_TRANSITION` |
|
||||
| нет роли `ADMIN` | 403 |
|
||||
|
||||
## Настройки (`ads.*`, `AdsProperties`)
|
||||
|
||||
| Свойство | Переменная | По умолчанию | Смысл |
|
||||
|---|---|---|---|
|
||||
| `ads.timezone` | `ADS_TIMEZONE` | `Europe/Moscow` | пояс дат кампаний и суток дневного лимита |
|
||||
| `ads.session-cooldown` | — | `PT30S` | пауза между показами одному субъекту |
|
||||
| `ads.eligible-cache-ttl` | — | `PT30S` | кэш кандидатов в памяти экземпляра |
|
||||
| `ads.finish-expired-cron` | — | каждые 10 минут | завершение кампаний по `endDate` |
|
||||
| `ads.tracking.secret` | `ADS_TRACKING_SECRET` | `jwt.secret` | ключ подписи токенов показа |
|
||||
| `ads.tracking.token-ttl` | — | `PT1H` | сколько после выдачи принимается показ/клик |
|
||||
| `ads.tracking.require-token` | `ADS_REQUIRE_TRACKING_TOKEN` | `false` | отклонять показы/клики без токена |
|
||||
|
||||
## Что можно улучшить
|
||||
|
||||
- Включить `ads.tracking.require-token` после того, как фронт начнёт
|
||||
присылать `impressionToken`.
|
||||
- Viewability (засчитывать показ, когда ≥ 50% баннера видно ≥ 1 с, по стандарту
|
||||
IAB/MRC) — решается на клиенте: отправлять `/impression` по
|
||||
IntersectionObserver.
|
||||
- Бюджеты и общий лимит показов кампании (не на пользователя), темп
|
||||
расходования (pacing).
|
||||
- Удаление кампаний/объявлений с чисткой медиа в MinIO (сейчас их архивирует
|
||||
статус `FINISHED`).
|
||||
- Восстановление транскодинга: если экземпляр упал во время ffmpeg, объявление
|
||||
останется в `PROCESSING` — нужен повторный `confirm-upload`.
|
||||
281
docs/images-storage.md
Normal file
281
docs/images-storage.md
Normal file
@@ -0,0 +1,281 @@
|
||||
# Картинки и файловое хранилище
|
||||
|
||||
Как ReFound принимает, хранит, отдаёт и удаляет картинки: фото объявлений,
|
||||
аватары и медиа рекламы. Всё описано по коду; имена классов — от пакета
|
||||
`com.krylov.refound`.
|
||||
|
||||
## Коротко
|
||||
|
||||
```
|
||||
клиент ──multipart──► контроллер ──► FileStorageService.uploadFile
|
||||
│ 1. validateFile: не пустой, есть имя, ≤ 10 МБ, Content-Type jpeg/png/webp
|
||||
│ 2. ImageFormat.detect: сигнатура файла = JPEG/PNG/WebP
|
||||
│ 3. ImageOptimizer.optimize: > 300 КБ → до 1600px, JPEG 0.82
|
||||
│ 4. PutObject в бакет minio.bucket, ключ <папка/>UUID.<ext>
|
||||
│ 5. Redis files:owner:<ключ> = логин (180 дней)
|
||||
▼
|
||||
ключ объекта (строка) ──► хранится в БД (images.url, users.avatar_url)
|
||||
|
||||
показ: GET /api/v1/files/<ключ> → прокси через бэкенд (байты + Cache-Control)
|
||||
GET /api/v1/files/<ключ>?presigned=true → 302 на presigned URL MinIO (ссылка кэшируется в Redis)
|
||||
GET /api/v1/files/url/<ключ> → {"url": presigned URL}
|
||||
модерация: PostModerationExecutorService скачивает файлы из MinIO и шлёт их в AI-сервис
|
||||
удаление: сервисы после коммита транзакции; DELETE /api/v1/files/<ключ> — владелец или админ
|
||||
```
|
||||
|
||||
## Где что лежит
|
||||
|
||||
| Что | Бакет | Ключ | Кто пишет |
|
||||
|---|---|---|---|
|
||||
| Фото объявлений | `minio.bucket` (`refound-images`) | `<uuid>.<ext>` (в корне) | `PostService.attachImages`, `AdminPostService.syncImages`, `POST /api/v1/files` |
|
||||
| Аватары | `minio.bucket` | `avatars/<uuid>.<ext>` | `UserService.updateUser` |
|
||||
| Картинки рекламы | `minio.ads-bucket` (`ads-media`) | `images/<uuid>.<ext>` | `AdvertisingMediaService.uploadImage` |
|
||||
| Исходники видео рекламы | `minio.ads-bucket` | `sources/<adId>/<uuid>.<ext>`, `fullscreen-sources/<id>/<uuid>.<ext>` | браузер админа по presigned PUT |
|
||||
| Готовые ролики | `minio.ads-bucket` | `videos/<uuid>.mp4`, `fullscreen/<uuid>.mp4` | `VideoTranscoderService` |
|
||||
|
||||
В БД хранится только **ключ** объекта (`images.url`, `users.avatar_url`,
|
||||
`advertising.media_key`, `fullscreen_advertising.media_key`), а не URL: адрес
|
||||
MinIO и срок ссылок могут меняться.
|
||||
|
||||
## Подключение к MinIO
|
||||
|
||||
- `config/MinioProperties` — типизированные `minio.*` (`endpoint`, `bucket`,
|
||||
`access-key`, `secret-key`, `region`), все обязательны (`@Validated`).
|
||||
`minio.ads-bucket` читается через `@Value` в рекламных сервисах.
|
||||
- `config/S3ClientConfig` создаёт `S3Client` и `S3Presigner` (AWS SDK v2) с
|
||||
`endpointOverride` и path-style адресами — так работает MinIO.
|
||||
- Автоконфигурация Spring Cloud AWS S3 отключена в `ReFoundApplication`
|
||||
(`exclude = S3AutoConfiguration.class`), клиенты свои.
|
||||
- Зависимость `io.minio:minio` в `build.gradle` есть, но в коде не используется.
|
||||
|
||||
### Что происходит при старте
|
||||
|
||||
`health/StorageStructureService` по `ContextRefreshedEvent`:
|
||||
|
||||
1. создаёт бакет `minio.bucket`, если его нет;
|
||||
2. включает версионирование;
|
||||
3. ставит правило жизненного цикла: **неактуальные версии** (то, что осталось
|
||||
после удаления/перезаписи) удаляются через 30 дней, «пустые» delete-маркеры
|
||||
убираются. Текущие версии файлов не истекают никогда.
|
||||
|
||||
Ошибки на любом шаге только логируются — приложение стартует и без MinIO.
|
||||
|
||||
> Раньше правило удаляло **все** объекты старше 180 дней, включая аватары и
|
||||
> картинки живых объявлений. Теперь файлы удаляет само приложение (см.
|
||||
> «Удаление»), а правило подчищает только старые версии.
|
||||
|
||||
Бакет `ads-media` и его CORS (`minio/cors.json`) создаёт контейнер `mc-init`
|
||||
из `docker-compose.yaml`. CORS там разрешает только `localhost:5173` и
|
||||
`localhost:3000` — для боевого домена админки правило нужно дополнить, иначе
|
||||
браузер не сможет загрузить видео по presigned PUT.
|
||||
|
||||
## Загрузка
|
||||
|
||||
### Валидация — `FileStorageService.validateFile` + `util/ImageFormat`
|
||||
|
||||
По порядку:
|
||||
|
||||
| Проверка | Ответ при нарушении |
|
||||
|---|---|
|
||||
| файл не пустой | 400 `VALIDATION_ERROR` «Файл не может быть пустым.» |
|
||||
| у файла есть оригинальное имя | 400 «Имя файла отсутствует.» |
|
||||
| размер ≤ 10 МБ (`MAX_FILE_SIZE`) | 400 «Файл слишком большой (максимум 10 МБ).» |
|
||||
| заявленный `Content-Type` ∈ `image/jpeg`, `image/png`, `image/webp` | 400 «Недопустимый тип файла.» |
|
||||
| **сигнатура файла** — JPEG (`FF D8 FF`), PNG (`89 50 4E 47 0D 0A 1A 0A`) или WebP (`RIFF....WEBP`) | 400 «Недопустимый тип файла.» |
|
||||
|
||||
Расширение ключа и `Content-Type` объекта берутся **из распознанного
|
||||
формата**, а не из имени файла и заголовка клиента. Иначе HTML/SVG с
|
||||
`Content-Type: image/png` сохранялся бы под ключом `<uuid>.html`.
|
||||
|
||||
Кроме того, Spring ограничивает multipart (`application.yaml`):
|
||||
`max-file-size: 10MB`, `max-request-size: 20MB`. Превышение даёт 413
|
||||
(`MaxUploadSizeExceededException` в `GlobalExceptionHandler`).
|
||||
|
||||
Картинки рекламы (`AdvertisingMediaService.uploadImage`) проверяются так же,
|
||||
но без оптимизации.
|
||||
|
||||
### Сжатие — `service/ImageOptimizer`
|
||||
|
||||
Фото с телефона весят 3–10 МБ при 12–24 Мп; лента с такими оригиналами
|
||||
открывается медленно. `optimize(byte[] source, String contentType)`:
|
||||
|
||||
1. Файлы **≤ 300 КБ** (`SKIP_BELOW_BYTES`) не трогает — они и так лёгкие.
|
||||
2. Размер читает из заголовка без декодирования пикселей (`maxSide`).
|
||||
Если большая сторона > **1600 px** (`MAX_DIMENSION`) — уменьшает до 1600
|
||||
по большей стороне с сохранением пропорций (Thumbnailator); меньшие
|
||||
картинки не увеличивает, только пережимает.
|
||||
3. Thumbnailator поворачивает картинку по EXIF-ориентации; сами EXIF
|
||||
(включая геометку) в результат не попадают.
|
||||
4. Картинку с прозрачностью (PNG/WebP с альфой) сохраняет в **PNG**; всё
|
||||
остальное — в **progressive JPEG** с качеством **0.82** (прозрачные места
|
||||
заливаются белым).
|
||||
5. Если результат не меньше оригинала или файл не читается — возвращает
|
||||
`Optional.empty()`, и сохраняется оригинал.
|
||||
|
||||
Плагины TwelveMonkeys (`imageio-jpeg`, `imageio-webp`) дают чтение WebP и
|
||||
CMYK-JPEG; `ImageIO.scanForPlugins()` в `@PostConstruct` регистрирует их в fat jar.
|
||||
Запись WebP не поддерживается, поэтому WebP после сжатия становится JPEG/PNG.
|
||||
|
||||
### Сохранение
|
||||
|
||||
`FileStorageService.uploadFile(file, folder)`:
|
||||
|
||||
- ключ: `<folder>/` + `UUID` + расширение (`.jpg`/`.png`/`.webp`);
|
||||
- метаданные объекта: `original-filename` (URL-encoded исходное имя) — нужно
|
||||
для `Content-Disposition` при скачивании;
|
||||
- после `PutObject` — `registerOwner`: в Redis `files:owner:<ключ>` = логин
|
||||
текущего пользователя на 180 дней (только если запрос авторизован);
|
||||
- ошибки S3 → 500 `INTERNAL_ERROR` «Ошибка при загрузке файла.».
|
||||
|
||||
Кто вызывает:
|
||||
|
||||
| Вызов | Папка |
|
||||
|---|---|
|
||||
| `POST /api/v1/posts` (multipart `images`) → `PostService.create` → `attachImages` | корень |
|
||||
| `PUT /api/v1/posts/{id}` → `PostService.update` | корень |
|
||||
| `PUT /api/v1/admin/posts/{id}` → `AdminPostService.updatePost` | корень |
|
||||
| `PUT /api/v1/users/{id}` (multipart `avatar`) → `UserService.updateUser` | `avatars` |
|
||||
| `POST /api/v1/files` (поле `file`) → возвращает ключ строкой | корень |
|
||||
|
||||
При создании и правке объявления (`PostService.create`/`update`) фото
|
||||
загружаются **до** транзакции БД — соединение с базой не держится, пока идёт
|
||||
загрузка в MinIO и запрос к геокодеру. Если загрузка одного из фото или
|
||||
транзакция упали, уже загруженные файлы удаляются. То, что всё же осталось
|
||||
без ссылки (например, `POST /api/v1/files` без последующего сохранения
|
||||
формы), убирает ночная чистка (см. ниже). Админская правка
|
||||
(`AdminPostService`) по-прежнему загружает файлы внутри транзакции.
|
||||
|
||||
## Отдача
|
||||
|
||||
### Прокси через бэкенд — `GET /api/v1/files/{*key}` (публично)
|
||||
|
||||
`FileStorageService.downloadFile`: `HeadObject` (тип, исходное имя) +
|
||||
`GetObjectAsBytes`. Ответ:
|
||||
|
||||
- `Content-Type` — как сохранён;
|
||||
- `Content-Disposition: inline` для картинок, `attachment` для остального,
|
||||
с исходным именем (`filename*=UTF-8''...`);
|
||||
- для картинок `Cache-Control: private, max-age=31536000, immutable` — ключи
|
||||
уникальны (UUID) и не меняются, так что браузер может хранить картинку год.
|
||||
Без явного заголовка Spring Security ставил бы `no-store`, и лента
|
||||
перекачивала бы все картинки при каждом открытии.
|
||||
|
||||
Файл целиком читается в память (до 10 МБ на картинку). Отсутствующий ключ → 404.
|
||||
|
||||
### Presigned URL
|
||||
|
||||
- `GET /api/v1/files/{*key}?presigned=true` → **302** на presigned GET URL
|
||||
MinIO. `FileStorageService.getCachedPresignedDownloadUrl` кэширует ссылку
|
||||
в Redis (`files:presigned:<ключ>`, TTL 12 ч), сама ссылка живёт 24 ч, а
|
||||
редирект браузер кэширует 6 ч (`Cache-Control: private, max-age=21600`).
|
||||
Пока URL одинаковый, браузер берёт картинку из своего кэша. В ссылку
|
||||
зашит `response-cache-control`, поэтому MinIO отдаёт тот же
|
||||
`immutable`-заголовок. Если Redis недоступен — генерируется новая ссылка.
|
||||
- `GET /api/v1/files/url/{*key}?ttlHours=24` → `{"url": "..."}`. `ttlHours`
|
||||
ограничен 168 часами (7 дней — максимум подписи SigV4); ≤ 0 → 24 ч.
|
||||
|
||||
Presigned URL подписан под `minio.endpoint`. Если это внутренний адрес
|
||||
(`http://minio:9010`), снаружи ссылка не откроется — тогда используйте
|
||||
прокси-вариант или задайте публичный `MINIO_ENDPOINT`.
|
||||
|
||||
### Медиа рекламы — `GET /api/v1/ads-media/{*key}` (публично)
|
||||
|
||||
`AdvertisingMediaService.downloadMedia` отдаёт объект из `ads-media`
|
||||
**потоком** (`InputStreamResource`), не загружая его в память, и понимает
|
||||
`Range`:
|
||||
|
||||
- без `Range` — 200, `Content-Length`, `Accept-Ranges: bytes`;
|
||||
- `Range: bytes=a-b` (а также `a-` и `-n`) — 206 и `Content-Range`, из MinIO
|
||||
читается только нужный кусок;
|
||||
- диапазон за пределами файла — 416 с `Content-Range: bytes */<длина>`;
|
||||
- `Cache-Control: public, max-age=2592000` (30 дней): ключи медиа неизменяемы.
|
||||
|
||||
Range нужен видеоплееру: Safari на iOS без 206 видео не воспроизводит, а
|
||||
перемотка в остальных браузерах иначе качает файл с начала.
|
||||
|
||||
## Удаление
|
||||
|
||||
| Сценарий | Что удаляется | Когда |
|
||||
|---|---|---|
|
||||
| Владелец удаляет объявление (`DELETE /api/v1/posts/{id}`) | все картинки поста | после коммита (`PostDeletionService`) |
|
||||
| Админ удаляет объявление (`DELETE /api/v1/admin/posts/{id}`) | все картинки поста | после коммита |
|
||||
| Ночная чистка (`SchedulerService.deleteExpiredPosts`, 00:01) — CLOSED и старше 6 мес. | все картинки постов | после коммита |
|
||||
| Правка объявления — картинки, которых нет в `existingImages` | убранные картинки | после коммита (`PostDeletionService.deleteFilesAfterCommit`) |
|
||||
| Новый аватар или `removeAvatar=true` | старый аватар | после сохранения профиля |
|
||||
| Ночная чистка сирот (`OrphanFileCleanupService`, 03:30) | файлы старше суток без ссылок из `images.url` и `users.avatar_url` | сразу, не больше 5000 за прогон |
|
||||
| `DELETE /api/v1/files/{*key}` | один файл | сразу; только владелец (по `files:owner:<ключ>`) или `ADMIN` |
|
||||
| Транскодинг видео рекламы | исходник `sources/...` | после транскодинга, в т.ч. неудачного |
|
||||
|
||||
`FileStorageService.deleteFile` удаляет объект и записи Redis
|
||||
`files:owner:<ключ>` и `files:presigned:<ключ>`. Ошибки хранилища при
|
||||
удалении постов только логируются (`warn`) — объявление удаляется в любом случае.
|
||||
|
||||
Почему «после коммита»: если транзакция удаления/правки откатится, пост
|
||||
останется с целыми картинками, а не со ссылками на удалённые файлы.
|
||||
|
||||
Через `DELETE /api/v1/files` удалить можно только файл, у которого есть
|
||||
отметка о владельце (загружен через API, не старше 180 дней). Файлы без
|
||||
отметки удаляет только администратор.
|
||||
|
||||
Бакет версионируемый: после удаления объект становится неактуальной
|
||||
версией и физически исчезает через 30 дней (правило жизненного цикла).
|
||||
|
||||
### Чистка файлов-сирот
|
||||
|
||||
`service/OrphanFileCleanupService` (cron `storage.orphan-cleanup.cron`,
|
||||
по умолчанию 03:30, ShedLock — один экземпляр):
|
||||
|
||||
1. собирает все значения `images.url` и `users.avatar_url` и приводит их к
|
||||
ключу (полные URL и пути `/bucket/key` в старых записях тоже распознаются);
|
||||
2. листает бакет `minio.bucket` постранично;
|
||||
3. удаляет объекты старше `min-age` (24 ч), на которые нет ссылок, — не
|
||||
больше `max-deletes` (5000) за прогон.
|
||||
|
||||
Выключается `STORAGE_ORPHAN_CLEANUP_ENABLED=false`. Ошибочно удалённое можно
|
||||
восстановить из неактуальной версии в течение 30 дней.
|
||||
|
||||
## Отправка на AI-модерацию
|
||||
|
||||
Картинки модерируются не при загрузке, а фоновой задачей:
|
||||
|
||||
1. `PostService.create`/`update` ставит посту статус `MODERATION`.
|
||||
2. `SchedulerService.moderatePendingPosts` раз в 60 секунд (одним экземпляром — ShedLock) берёт id постов
|
||||
на модерации и для каждого вызывает `PostModerationExecutorService.moderateOne`.
|
||||
3. Короткая транзакция читает снимок поста: заголовок, описание, ключи картинок.
|
||||
4. Без транзакции каждая картинка скачивается из MinIO
|
||||
(`FileStorageService.downloadFileRaw` — уже сжатая версия) и
|
||||
оборачивается в `util/ByteArrayMultipartFile`.
|
||||
5. `ContentModerationFacade` → `ContentModerationPipeline`:
|
||||
`TextModerationProcessor` (order 10), затем `ImageModerationProcessor`
|
||||
(order 20). Каждая картинка уходит в `ImageModerationClient` →
|
||||
`AiMultipartHttpClient`: `POST {ai.url}/api/v1/moderation/image`,
|
||||
multipart-поле `file`, таймаут ответа `ai.image-timeout` (30 с),
|
||||
ретраи по `ai.retry.*` на 5xx/503/таймаут/недоступность.
|
||||
6. Ответ `approved=false` → `ContentBlockedException` → пост `REJECTED`.
|
||||
7. Новая транзакция ставит `ACTIVE`/`REJECTED`, только если пост всё ещё в
|
||||
`MODERATION` и не менялся с момента снимка (заголовок, описание, набор
|
||||
картинок). Иначе вердикт отбрасывается и новая версия проверяется в
|
||||
следующий запуск.
|
||||
|
||||
| Ситуация | Статус поста |
|
||||
|---|---|
|
||||
| AI одобрил текст и все картинки | `ACTIVE` (+ сброс кэша ленты/карты) |
|
||||
| AI отклонил текст или картинку | `REJECTED` |
|
||||
| AI вернул 4xx (не принимает файл) | `REJECTED` |
|
||||
| Картинки нет в MinIO (404) | `REJECTED` |
|
||||
| AI недоступен после ретраев, MinIO недоступен, иная ошибка | остаётся `MODERATION`, повтор через минуту |
|
||||
|
||||
## Связанные классы
|
||||
|
||||
| Класс | Роль |
|
||||
|---|---|
|
||||
| `controller/FileStorageController` | `/api/v1/files`: загрузка, прокси, presigned, удаление |
|
||||
| `service/FileStorageService` | работа с бакетом картинок, владельцы, кэш ссылок |
|
||||
| `service/ImageOptimizer` | ресайз и пережатие |
|
||||
| `util/ImageFormat` | распознавание формата по сигнатуре |
|
||||
| `service/PostDeletionService` | удаление постов и файлов после коммита |
|
||||
| `service/OrphanFileCleanupService` | ночная чистка файлов без ссылок |
|
||||
| `service/PostModerationExecutorService` | модерация одного поста |
|
||||
| `health/StorageStructureService` | бакет, версионирование, lifecycle |
|
||||
| `config/S3ClientConfig`, `config/MinioProperties` | клиенты S3 |
|
||||
| `controller/advertising/AdvertisingMediaController`, `service/advertising/AdvertisingMediaService` | медиа рекламы |
|
||||
66
docs/phone-protection.md
Normal file
66
docs/phone-protection.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Номера телефонов: согласие и защита от сбора
|
||||
|
||||
## Согласие (152-ФЗ)
|
||||
|
||||
- По умолчанию объявление в режиме «только чат»: `posts.phone_visible = false`, номер не хранится.
|
||||
- Номер сохраняется только с явной галочкой «Показывать мой номер…» в форме (`phoneVisible=true`).
|
||||
Время согласия — `posts.phone_consent_at`. Без галочки или после её снятия номер стирается.
|
||||
- У объявлений, созданных до миграции 023, явного согласия не было: их номера скрыты,
|
||||
пока автор не отредактирует объявление и не поставит галочку.
|
||||
- Админ может поправить или убрать номер, но не включить показ за автора.
|
||||
|
||||
## Как отдаётся номер
|
||||
|
||||
В ленте, на карте, в избранном и в кэше Redis номера нет: `PostResponse.phone` заполняется
|
||||
только для автора (свои объявления, ответы на создание и правку). Остальные видят
|
||||
`phoneVisible: true` и кнопку «Показать номер»:
|
||||
|
||||
1. `GET /api/v1/posts/{id}/phone/challenge` → задача proof-of-work (формат ALTCHA:
|
||||
`algorithm, challenge, salt, maxNumber, signature`).
|
||||
2. Браузер перебирает `n` до `SHA-256(salt + n) == challenge` (`src/utils/proofOfWork.js`).
|
||||
3. `POST /api/v1/posts/{id}/phone` `{salt, number, signature}` → `{phone}`.
|
||||
|
||||
Задача подписана HMAC, привязана к объявлению, живёт 2 минуты и принимается один раз.
|
||||
Номер отдаётся только у активных объявлений с согласием. Оба эндпоинта публичные,
|
||||
регистрация не нужна.
|
||||
|
||||
Время решения (JS, худший случай, десктоп; телефон в 3–5 раз медленнее, в среднем — вдвое быстрее):
|
||||
|
||||
| maxNumber | когда | время |
|
||||
|---|---|---|
|
||||
| 100 000 | первые 5 номеров за час с IP | ~0,15 с |
|
||||
| 400 000 | 5–9 | ~0,5 с |
|
||||
| 1 600 000 | 10–14 | ~1,6 с |
|
||||
| 5 000 000 | 15+ (предел) | ~4,5 с |
|
||||
|
||||
## Лимиты и ловушки (`phone-reveal.*`)
|
||||
|
||||
- С IP: 30 номеров в час, 100 в сутки; с аккаунта — 50 в сутки. Сверх — 429 с `Retry-After`.
|
||||
- Всплески: `rate-limit.rules` — 20 задач и 10 открытий в минуту с IP.
|
||||
- Подозрительные запросы — те, что интерфейс не делает: номер объявления без номера,
|
||||
закрытого или несуществующего; неверное решение. 5 таких за час → бан IP на 24 часа
|
||||
(ответ — тот же 429, причину не раскрываем).
|
||||
- Объявления-ловушки: `PHONE_TRAP_POST_IDS=900001,900002` — запрос номера по ним сразу банит IP.
|
||||
Берите id удалённых объявлений или далеко за текущим максимумом.
|
||||
- Каждый показ пишется в лог: `Показан номер: postId=…, ip=…, userId=…`.
|
||||
|
||||
## nginx перед API (если есть)
|
||||
|
||||
Бесплатный первый рубеж до Spring; IP клиента в Spring приходит через `X-Forwarded-For`.
|
||||
|
||||
```nginx
|
||||
limit_req_zone $binary_remote_addr zone=phone:10m rate=10r/m;
|
||||
|
||||
location ~ ^/api/v1/posts/\d+/phone {
|
||||
limit_req zone=phone burst=5 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_pass http://backend;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
```
|
||||
|
||||
## Ограничения
|
||||
|
||||
Абсолютной защиты нет: сборщик на резидентных прокси с настоящим браузером обойдёт всё.
|
||||
Цель — сделать массовый сбор дорогим. Id объявлений остаются последовательными:
|
||||
лента и так отдаёт их все, поэтому UUID тут почти ничего не добавляют.
|
||||
231
docs/redis.md
Normal file
231
docs/redis.md
Normal file
@@ -0,0 +1,231 @@
|
||||
# Redis в ReFound
|
||||
|
||||
Redis — общий для всех экземпляров приложения слой: кэш, refresh-токены,
|
||||
лимиты запросов и рекламы, распределённые блокировки фоновых задач и шина
|
||||
WebSocket-событий. Источник правды везде — PostgreSQL или MinIO, кроме
|
||||
refresh-токенов и счётчиков: они живут только в Redis.
|
||||
|
||||
## Подключение
|
||||
|
||||
`application.yaml`:
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
host: ${REDIS_HOST:localhost}
|
||||
port: 6379
|
||||
password: ${REDIS_PASSWORD} # обязателен, значения по умолчанию нет
|
||||
timeout: 500ms # таймаут команды
|
||||
connect-timeout: 500ms
|
||||
```
|
||||
|
||||
Клиент — Lettuce (по умолчанию в `spring-boot-starter-data-redis`).
|
||||
Шаблоны (`config/RedisConfig`):
|
||||
|
||||
| Бин | Значение | Сериализация |
|
||||
|---|---|---|
|
||||
| `StringRedisTemplate` (автоконфигурация) | строки | ключ и значение — строки |
|
||||
| `postCacheRedisTemplate` | `dto/CachedPostPage` — страница ленты | ключ — строка, значение — JSON (Jackson) |
|
||||
| `mapRedisTemplate` | `List<dto/MapMarkerDto>` — метки карты | ключ — строка, значение — JSON |
|
||||
|
||||
Для JSON-шаблонов берётся копия `ObjectMapper` приложения с
|
||||
`FAIL_ON_UNKNOWN_PROPERTIES=false`: новые поля DTO не ломают чтение старых
|
||||
записей кэша.
|
||||
|
||||
### Redis в docker-compose
|
||||
|
||||
```
|
||||
redis-server --requirepass $REDIS_PASSWORD --maxmemory 256mb
|
||||
--maxmemory-policy volatile-lru --save "" --appendonly no
|
||||
```
|
||||
|
||||
- `volatile-lru` — при нехватке памяти вытесняются только ключи **с TTL**.
|
||||
Ключ версии кэша (`posts:version`) живёт без TTL и поэтому не вытесняется.
|
||||
Обратная сторона: refresh-токены тоже с TTL и при нехватке памяти могут
|
||||
быть вытеснены — пользователю придётся войти заново.
|
||||
- Персистентность выключена: после перезапуска Redis пропадают все
|
||||
refresh-токены (пользователи перелогиниваются, когда истечёт access-токен)
|
||||
и счётчики лимитов. Кэши восстанавливаются сами. Для production включите
|
||||
AOF (`--appendonly yes`) или используйте управляемый Redis с репликой, а
|
||||
для refresh-токенов — политику `noeviction` или отдельный экземпляр.
|
||||
- Порт открыт только на `127.0.0.1`.
|
||||
|
||||
## Все ключи
|
||||
|
||||
| Ключ | Тип | TTL | Что хранит | Класс |
|
||||
|---|---|---|---|---|
|
||||
| `posts:version` | string (INCR) | нет | версия всех данных объявлений | `service/redis/PostCacheService` |
|
||||
| `posts:feed:v{версия}:filter={sha256}:page={n}:size={n}:sort={поле:направление,...}` | JSON | 2 мин | страница публичной ленты | `PostService.getFeed`, `PostCacheKeyGenerator.feedKey` |
|
||||
| `posts:map:v{версия}:bbox={minLat},{maxLat},{minLng},{maxLng}:type={тип}:category={категория}` | JSON | 5 мин | метки карты | `MapService.findMarkers`, `PostCacheKeyGenerator.mapKey` |
|
||||
| `refresh_token:{uuid}` | string | `jwt.refresh-expiration` (7 дней) | логин владельца refresh-токена | `service/RefreshTokenService` |
|
||||
| `files:owner:{ключ файла}` | string | 180 дней | логин того, кто загрузил файл | `FileStorageService.registerOwner` |
|
||||
| `files:presigned:{ключ файла}` | string | 12 ч | presigned URL картинки | `FileStorageService.getCachedPresignedDownloadUrl` |
|
||||
| `geo:{lat}:{lon}` | JSON | 30 дней | город/район по координатам (округлены до 4 знаков) | `service/GeocodingService` |
|
||||
| `geo:throttle` | string | 1 с | слот общего лимита 1 запрос/с к Nominatim | `GeocodingService.acquireSlot` |
|
||||
| `ad:cap:{субъект}:{кампания}:{yyyyMMdd}` | string (INCR) | 48 ч | показы кампании субъекту за календарные сутки | `service/advertising/AdvertisingFrequencyService` |
|
||||
| `ad:cooldown:{субъект}` | string | 30 с | пауза между показами рекламы | `AdvertisingFrequencyService.tryStartCooldown` |
|
||||
| `ad:imp:{nonce}`, `ad:clk:{nonce}` | string | 1 ч (срок токена) | токен показа уже засчитан как показ/клик | `AdvertisingFrequencyService.markOnce` |
|
||||
| `rl:{правило}:{ip}:{номер окна}` | string (INCR) | длина окна | счётчик лимита запросов | `ratelimit/RedisRateLimiter` |
|
||||
| `rl:login-failures:{логин}:{номер окна}` | string (INCR) | 15 мин | неудачные входы в аккаунт | `AuthService.loginUser` |
|
||||
| `job-lock:refound:{задача}` | string | `lockAtMostFor` задачи | блокировка фоновой задачи (ShedLock) | `config/SchedulerLockConfig` |
|
||||
| канал `ws:broadcast` | pub/sub | — | STOMP-события для всех экземпляров | `config/ClusterMessaging` |
|
||||
|
||||
Субъект рекламы — `u{userId}` для авторизованного пользователя или
|
||||
`s{sessionId}` для гостя.
|
||||
|
||||
В старых базах могут остаться ключи прежних версий: `maps:markers:version`,
|
||||
`ad:freq:*`, `ad:session:*:cooldown`. Их никто не читает — удалите или
|
||||
дождитесь TTL.
|
||||
|
||||
## Кэш ленты и карты
|
||||
|
||||
### Что кэшируется
|
||||
|
||||
- **Лента без поиска** — `GET /api/v1/posts` без параметра `search`
|
||||
(`PostService.getFeed`). Ключ учитывает фильтры (`PostFeedFilter.cacheKeyPart()`
|
||||
→ SHA-256: тип, категории, города), номер и размер страницы и сортировку.
|
||||
К сортировке всегда добавляется `id DESC`, чтобы страницы были стабильными.
|
||||
TTL 2 минуты.
|
||||
- **Метки карты** — `GET /api/v1/posts/map` (`MapService.findMarkers`). Углы
|
||||
прямоугольника округляются до сетки 0,01° (≈1 км), чтобы соседние положения
|
||||
карты попадали в один ключ. TTL 5 минут.
|
||||
|
||||
Не кэшируются: поиск по тексту (запросы почти всегда уникальны, отвечает
|
||||
GIN-индекс), объявления пользователя, карточка объявления, избранное, чаты,
|
||||
админская лента.
|
||||
|
||||
### Инвалидация через версию
|
||||
|
||||
Удалять ключи по шаблону (`KEYS`/`SCAN`) дорого, поэтому версия — часть ключа:
|
||||
|
||||
1. Перед запросом в БД читается `posts:version` (нет ключа или Redis недоступен
|
||||
→ `"0"`), из неё строится ключ.
|
||||
2. Любое изменение объявлений вызывает `PostCacheService.invalidatePosts()`,
|
||||
который делает `INCR posts:version` **после коммита** транзакции
|
||||
(`TransactionSynchronization.afterCommit`; вне транзакции — сразу).
|
||||
3. Следующие запросы строят ключи с новой версией и идут в БД; старые записи
|
||||
никто не читает, они умирают по TTL.
|
||||
|
||||
Версия читается **до** запроса в БД: если пост изменится между чтением
|
||||
версии и сохранением кэша, устаревшая страница ляжет под старую версию и
|
||||
читаться не будет.
|
||||
|
||||
Кто сбрасывает кэш:
|
||||
|
||||
| Событие | Где |
|
||||
|---|---|
|
||||
| создание, правка, смена статуса объявления владельцем | `PostService.create`, `update`, `updateStatus` |
|
||||
| удаление владельцем, админом, ночной чисткой | `PostDeletionService.delete` |
|
||||
| правка и смена статуса админом | `AdminPostService.updatePost`, `updateStatus` |
|
||||
| пост прошёл AI-модерацию (стал виден) | `PostModerationExecutorService.moderateOne` |
|
||||
|
||||
Одна версия на ленту и карту: изменение поста сбрасывает оба представления.
|
||||
Смена имени, логина или аватара пользователя кэш не сбрасывает — в ленте
|
||||
старые данные видны до истечения TTL (до 2 минут).
|
||||
|
||||
## Refresh-токены
|
||||
|
||||
`RefreshTokenService`:
|
||||
|
||||
- **выдача** (`/auth/register`, `/auth/login`, `/auth/refresh`): клиент
|
||||
получает строку `{uuid}.{jwt}`; в Redis пишется `refresh_token:{uuid}` =
|
||||
логин с TTL, равным сроку жизни refresh-JWT;
|
||||
- **обмен** (`POST /api/v1/auth/refresh`): JWT проверяется по подписи и типу
|
||||
(`typ=refresh`), затем запись забирается атомарно `GETDEL`. Повторный или
|
||||
параллельный обмен того же токена получает 401 — токен одноразовый.
|
||||
Логин из Redis должен совпадать с логином в JWT;
|
||||
- **выход** (`POST /api/v1/auth/logout`): запись удаляется.
|
||||
|
||||
Если Redis недоступен, вход, регистрация и обмен токена отвечают ошибкой —
|
||||
без Redis новые сессии не создаются. Уже выданные access-токены (15 минут)
|
||||
продолжают работать: они проверяются только по подписи.
|
||||
|
||||
## Файлы
|
||||
|
||||
- `files:owner:{ключ}` — кто загрузил файл. Нужен только для
|
||||
`DELETE /api/v1/files/{ключ}`: удалить может владелец или админ. Без
|
||||
записи (старый файл, Redis очищен) удалить файл через API может только админ.
|
||||
- `files:presigned:{ключ}` — одна и та же presigned-ссылка на 12 часов, чтобы
|
||||
браузер кэшировал картинку (сама ссылка живёт 24 ч).
|
||||
|
||||
Обе записи удаляются вместе с файлом (`FileStorageService.deleteFile`).
|
||||
Ошибки Redis здесь не роняют запрос: владелец не сохранится, ссылка
|
||||
сгенерируется заново.
|
||||
|
||||
Подробнее — в [images-storage.md](images-storage.md).
|
||||
|
||||
## Реклама
|
||||
|
||||
`AdvertisingFrequencyService` (подробно — в [advertising.md](advertising.md)):
|
||||
|
||||
- **дневной лимит кампании**: при выдаче одним `MGET` читаются
|
||||
`ad:cap:{субъект}:{кампания}:{день}` всех кампаний-кандидатов; на
|
||||
подтверждённом показе счётчик растёт Lua-скриптом `INCR` + `PEXPIRE 48h`.
|
||||
Сутки — календарные в `ads.timezone`;
|
||||
- **пауза между показами**: `SET ad:cooldown:{субъект} NX EX 30` в момент выдачи;
|
||||
- **однократный учёт**: `SET ad:imp:{nonce} NX EX 3600` (и `ad:clk:`) — токен
|
||||
показа засчитывается один раз.
|
||||
|
||||
Если Redis недоступен, `GET /api/ads/next` отвечает 204 (реклама не
|
||||
показывается); показ по токену сохраняется в БД без проверки повтора.
|
||||
|
||||
## Лимиты запросов
|
||||
|
||||
`ratelimit/RateLimitFilter` + `RedisRateLimiter`: фиксированное окно,
|
||||
ключ `rl:{правило}:{ip}:{номер окна}`, `INCR` и `PEXPIRE` одним Lua-скриптом
|
||||
(атомарно, ключ без TTL не появится). Правила — `rate-limit.rules` в
|
||||
`application.yaml` (вход, регистрация, refresh, check-login, создание
|
||||
объявлений, загрузка файлов, начало чата, реклама). Превышение — 429 с
|
||||
`Retry-After`.
|
||||
|
||||
Отдельно `AuthService` считает неудачные входы в аккаунт
|
||||
(`rl:login-failures:{логин}:...`): после 10 за 15 минут вход в этот аккаунт
|
||||
блокируется до конца окна (429), успешный вход сбрасывает счётчик.
|
||||
|
||||
Лимиты — защитный слой: при недоступном Redis запросы пропускаются
|
||||
(fail-open), чтобы сбой Redis не остановил API. IP клиента за прокси берётся
|
||||
из `X-Forwarded-For` (`server.forward-headers-strategy=native`).
|
||||
|
||||
## Несколько экземпляров приложения
|
||||
|
||||
- **Фоновые задачи** — ShedLock (`RedisLockProvider`, ключ
|
||||
`job-lock:refound:{задача}`): ночная чистка постов, модерация, словарь
|
||||
подсказок, завершение кампаний, чистка файлов-сирот выполняются одним
|
||||
экземпляром. Нет Redis — задача пропускает запуск.
|
||||
- **WebSocket** — брокер STOMP встроенный (в памяти экземпляра), поэтому
|
||||
события (новые сообщения чата, счётчики непрочитанных, статусы
|
||||
транскодинга) публикуются в канал `ws:broadcast`; каждый экземпляр
|
||||
подписан на канал (`RedisMessageListenerContainer`) и отдаёт событие своим
|
||||
подписчикам. Выключается `app.websocket.cluster-broadcast=false`. Без Redis
|
||||
событие доставляется только локально.
|
||||
- Кэши, лимиты, токены и блокировки в Redis — общие; в памяти экземпляра
|
||||
остаются только список кандидатов рекламы (30 с) и буфер статистики
|
||||
поисков (сбрасывается в БД раз в минуту).
|
||||
|
||||
## Чего в Redis нет
|
||||
|
||||
- **HTTP-сессий** — приложение stateless (`SessionCreationPolicy.STATELESS`),
|
||||
Spring Session не подключён.
|
||||
- **Spring Cache (`@Cacheable`)** — не используется, кэш собран вручную.
|
||||
- **Подсказки поиска** — `SearchSuggestService` копит статистику поисков в
|
||||
памяти процесса и раз в минуту пишет её в PostgreSQL (`search_words`).
|
||||
|
||||
## Поведение при недоступности Redis
|
||||
|
||||
| Функция | Что происходит |
|
||||
|---|---|
|
||||
| Лента, карта | кэш пропускается (warn в лог), данные из БД |
|
||||
| Presigned-ссылки | генерируется новая ссылка на каждый запрос |
|
||||
| Владельцы файлов | не сохраняются; удалить файл через API сможет только админ |
|
||||
| Вход, регистрация, refresh, logout | ошибка 500 |
|
||||
| Лимиты запросов и блокировка перебора | не применяются (fail-open) |
|
||||
| Геокодер | без кэша и общего лимита |
|
||||
| Реклама `/api/ads/next` | 204, реклама не показывается |
|
||||
| Показы/клики | сохраняются, без проверки повторов и без роста дневного лимита |
|
||||
| Фоновые задачи | пропускают запуск (блокировку не взять) |
|
||||
| WebSocket между экземплярами | события доставляются только подписчикам своего экземпляра |
|
||||
| Проверка access-токенов, чаты по REST, остальное API | работает |
|
||||
|
||||
Команды ограничены таймаутом 500 мс, так что недоступный Redis не вешает
|
||||
запросы надолго.
|
||||
@@ -3,6 +3,10 @@ package com.krylov.refound;
|
||||
import com.krylov.refound.ai.config.AiProperties;
|
||||
import com.krylov.refound.ai.config.AiRetryProperties;
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.ratelimit.RateLimitProperties;
|
||||
import com.krylov.refound.search.SearchProperties;
|
||||
import com.krylov.refound.service.advertising.AdsProperties;
|
||||
import com.krylov.refound.service.phone.PhoneRevealProperties;
|
||||
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -15,7 +19,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
scanBasePackages = "com.krylov.refound",
|
||||
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
||||
)@EnableScheduling
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class})
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
||||
SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class})
|
||||
@EnableRetry
|
||||
public class ReFoundApplication {
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
package com.krylov.refound.ai.client;
|
||||
|
||||
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.AiTimeoutException;
|
||||
import com.krylov.refound.ai.exception.AiUnavailableException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.reactive.function.client.WebClientRequestException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -39,13 +40,16 @@ public class AiHttpClient {
|
||||
|
||||
log.info("AI response received");
|
||||
return response;
|
||||
} catch (WebClientRequestException ex) {
|
||||
log.error("AI connection failed", ex);
|
||||
throw new AiUnavailableException(ex);
|
||||
|
||||
} catch (Exception ex) {
|
||||
log.error("AI request failed", ex);
|
||||
throw new AiUnavailableException(ex);
|
||||
AiException error = AiClientErrors.translate(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
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.AiException;
|
||||
import com.krylov.refound.ai.exception.AiServerException;
|
||||
import com.krylov.refound.ai.exception.AiTimeoutException;
|
||||
import com.krylov.refound.ai.exception.AiUnavailableException;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
@@ -12,19 +17,28 @@ import org.springframework.http.client.MultipartBodyBuilder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import org.springframework.web.reactive.function.client.WebClientRequestException;
|
||||
import reactor.netty.http.client.HttpClientRequest;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AiMultipartHttpClient {
|
||||
private final WebClient aiWebClient;
|
||||
private final AiProperties properties;
|
||||
|
||||
public <R> R post(String uri, MultipartFile file, Class<R> responseType) {
|
||||
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 {
|
||||
MultipartBodyBuilder builder = new MultipartBodyBuilder();
|
||||
builder.part("file", new ByteArrayResource(file.getBytes()) {
|
||||
builder.part("file", new ByteArrayResource(bytes) {
|
||||
@Override
|
||||
public String getFilename() {
|
||||
return file.getOriginalFilename();
|
||||
@@ -36,6 +50,8 @@ public class AiMultipartHttpClient {
|
||||
.uri(uri)
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.bodyValue(builder.build())
|
||||
// Картинки обрабатываются дольше текста — свой таймаут ответа
|
||||
.httpRequest(req -> ((HttpClientRequest) req.getNativeRequest()).responseTimeout(timeout))
|
||||
.retrieve()
|
||||
.onStatus(
|
||||
HttpStatusCode::is4xxClientError,
|
||||
@@ -51,12 +67,16 @@ public class AiMultipartHttpClient {
|
||||
.block();
|
||||
log.info("AI image response received");
|
||||
return response;
|
||||
} catch (WebClientRequestException ex) {
|
||||
log.error("WebClientRequestException in AiMultipartHttpClient {}", ex.getMessage(), ex);
|
||||
throw new AiUnavailableException(ex);
|
||||
} catch (Exception ex) {
|
||||
log.error("Exception in AiMultipartHttpClient {}", ex.getMessage(), ex);
|
||||
throw new RuntimeException("Cannot send image to AI", ex);
|
||||
AiException error = AiClientErrors.translate(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.krylov.refound.ai.client;
|
||||
|
||||
import com.krylov.refound.ai.dto.ImageModerationResponse;
|
||||
import com.krylov.refound.ai.exception.AiServerException;
|
||||
import com.krylov.refound.ai.exception.AiTimeoutException;
|
||||
import com.krylov.refound.ai.exception.AiUnavailableException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -18,25 +19,36 @@ public class ImageModerationClient {
|
||||
private final AiMultipartHttpClient client;
|
||||
|
||||
@Retryable(
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class},
|
||||
maxAttempts = 3,
|
||||
backoff = @Backoff(delay = 500, multiplier = 2)
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
|
||||
// Параметры из ai.retry.* (AiRetryProperties); раньше они были захардкожены
|
||||
maxAttemptsExpression = "${ai.retry.max-attempts:3}",
|
||||
backoff = @Backoff(delayExpression = "${ai.retry.delay:500}",
|
||||
multiplierExpression = "${ai.retry.multiplier:2}")
|
||||
)
|
||||
public ImageModerationResponse moderate(MultipartFile file) {
|
||||
log.info("Calling AI ImageModeration service");
|
||||
return client.post("/api/v1/moderation/image", file, ImageModerationResponse.class);
|
||||
}
|
||||
|
||||
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
|
||||
// проверяется снова при следующем запуске планировщика.
|
||||
@Recover
|
||||
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;
|
||||
}
|
||||
|
||||
@Recover
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.krylov.refound.ai.client;
|
||||
import com.krylov.refound.ai.dto.ModerationResponse;
|
||||
import com.krylov.refound.ai.dto.TextModerationRequest;
|
||||
import com.krylov.refound.ai.exception.AiServerException;
|
||||
import com.krylov.refound.ai.exception.AiTimeoutException;
|
||||
import com.krylov.refound.ai.exception.AiUnavailableException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -19,25 +20,36 @@ public class TextModerationClient {
|
||||
private final AiHttpClient client;
|
||||
|
||||
@Retryable(
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class},
|
||||
maxAttempts = 3,
|
||||
backoff = @Backoff(delay = 500, multiplier = 2)
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
|
||||
// Параметры из ai.retry.* (AiRetryProperties); раньше они были захардкожены
|
||||
maxAttemptsExpression = "${ai.retry.max-attempts:3}",
|
||||
backoff = @Backoff(delayExpression = "${ai.retry.delay:500}",
|
||||
multiplierExpression = "${ai.retry.multiplier:2}")
|
||||
)
|
||||
public ModerationResponse moderate(String text) {
|
||||
log.info("Calling AI TextModeration service");
|
||||
return client.post("/api/v1/moderation/text", new TextModerationRequest(text), ModerationResponse.class);
|
||||
}
|
||||
|
||||
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
|
||||
// проверяется снова при следующем запуске планировщика.
|
||||
@Recover
|
||||
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;
|
||||
}
|
||||
|
||||
@Recover
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -19,4 +19,17 @@ public class AiProperties {
|
||||
* 10 seconds
|
||||
*/
|
||||
private int timeout;
|
||||
|
||||
/**
|
||||
* Таймаут ответа для модерации изображений, секунды. Картинки AI-сервис
|
||||
* обрабатывает заметно дольше текста, особенно первую после простоя.
|
||||
*/
|
||||
private int imageTimeout = 30;
|
||||
|
||||
/**
|
||||
* Максимальная длина текста в одном запросе к AI-сервису (TEXT_MAX_LENGTH
|
||||
* на его стороне). Более длинный текст отправляется частями — иначе сервис
|
||||
* отвечает 422, и пост ошибочно отклоняется.
|
||||
*/
|
||||
private int textMaxLength = 5000;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.config;
|
||||
|
||||
import io.netty.channel.ChannelOption;
|
||||
import java.time.Duration;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
@@ -14,11 +15,15 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
@EnableConfigurationProperties(AiProperties.class)
|
||||
public class WebClientConfig {
|
||||
|
||||
private static final int CONNECT_TIMEOUT_MILLIS = 3_000;
|
||||
|
||||
@Bean
|
||||
public WebClient aiWebClient(AiProperties properties) {
|
||||
log.info("aiWebClient get for properties {}", properties);
|
||||
HttpClient httpClient =
|
||||
HttpClient.create()
|
||||
// Без явного таймаута соединения недоступный хост держал поток модерации ~30 с на попытку
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
|
||||
.responseTimeout(
|
||||
Duration.ofSeconds(properties.getTimeout())
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -11,5 +12,7 @@ public class ImageModerationResponse {
|
||||
|
||||
private String reason;
|
||||
|
||||
// AI-сервис (Python) отдаёт поля в snake_case
|
||||
@JsonProperty("detected_labels")
|
||||
private List<String> detectedLabels;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -14,6 +15,8 @@ public class ModerationResponse {
|
||||
|
||||
private String reason;
|
||||
|
||||
// AI-сервис (Python) отдаёт поля в snake_case
|
||||
@JsonProperty("detected_labels")
|
||||
private List<String> detectedLabels;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.krylov.refound.ai.pipeline;
|
||||
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.annotation.Order;
|
||||
@@ -14,17 +17,40 @@ import org.springframework.stereotype.Component;
|
||||
@Order(10)
|
||||
public class TextModerationProcessor implements ModerationProcessor {
|
||||
|
||||
/**
|
||||
* Перекрытие соседних частей: фраза на стыке целиком попадает хотя бы в одну.
|
||||
*/
|
||||
static final int CHUNK_OVERLAP = 200;
|
||||
|
||||
private final TextModerationClient client;
|
||||
private final AiProperties properties;
|
||||
|
||||
@Override
|
||||
public Boolean process(ModerationContext context) {
|
||||
log.info("process TextModerationProcessor for context {}", context);
|
||||
// Весь контекст (текст поста, файлы) в лог не пишем — только размер
|
||||
log.debug("process TextModerationProcessor: images={}", context.getImages() == null ? 0 : context.getImages().size());
|
||||
String text = buildText(
|
||||
context.getTitle(),
|
||||
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) {
|
||||
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
|
||||
return null;
|
||||
@@ -35,10 +61,49 @@ public class TextModerationProcessor implements ModerationProcessor {
|
||||
if (!Boolean.TRUE.equals(response.getApproved())) {
|
||||
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.connection.Message;
|
||||
import org.springframework.data.redis.connection.MessageListener;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Рассылка STOMP-сообщений во все экземпляры приложения.
|
||||
*
|
||||
* <p>WebSocket-брокер (simple broker) живёт в памяти процесса: подписчики,
|
||||
* подключённые к другому экземпляру, сообщение не получили бы. Поэтому событие
|
||||
* публикуется в канал Redis {@value #CHANNEL}, каждый экземпляр (включая
|
||||
* отправителя) получает его и отдаёт своему локальному брокеру — а тот своим
|
||||
* подписчикам. Права на подписку по-прежнему проверяет WsStompInterceptor в
|
||||
* том экземпляре, где подключён клиент.
|
||||
*
|
||||
* <p>Если Redis недоступен, сообщение доставляется хотя бы локально.
|
||||
* Включается свойством {@code app.websocket.cluster-broadcast} (по умолчанию да).
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ClusterMessaging implements MessageListener {
|
||||
|
||||
public static final String CHANNEL = "ws:broadcast";
|
||||
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final boolean clusterBroadcast;
|
||||
|
||||
public ClusterMessaging(SimpMessagingTemplate messagingTemplate, StringRedisTemplate redisTemplate,
|
||||
ObjectMapper objectMapper, @Value("${app.websocket.cluster-broadcast:true}") boolean clusterBroadcast) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.clusterBroadcast = clusterBroadcast;
|
||||
}
|
||||
|
||||
record Envelope(String destination, JsonNode payload) {
|
||||
}
|
||||
|
||||
/** Отправляет сообщение подписчикам destination во всех экземплярах. */
|
||||
public void convertAndSend(String destination, Object payload) {
|
||||
if (!clusterBroadcast) {
|
||||
messagingTemplate.convertAndSend(destination, payload);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(new Envelope(destination, objectMapper.valueToTree(payload)));
|
||||
redisTemplate.convertAndSend(CHANNEL, json);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось опубликовать WS-сообщение в Redis ({}), доставляем локально: {}",
|
||||
destination, e.getMessage());
|
||||
messagingTemplate.convertAndSend(destination, payload);
|
||||
}
|
||||
}
|
||||
|
||||
/** Сообщение из канала Redis — от этого или другого экземпляра. */
|
||||
@Override
|
||||
public void onMessage(Message message, byte[] pattern) {
|
||||
try {
|
||||
Envelope envelope = objectMapper.readValue(new String(message.getBody(), StandardCharsets.UTF_8), Envelope.class);
|
||||
if (envelope.destination() == null) {
|
||||
return;
|
||||
}
|
||||
messagingTemplate.convertAndSend(envelope.destination(), envelope.payload());
|
||||
} catch (Exception e) {
|
||||
log.warn("Некорректное WS-сообщение из Redis: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isClusterBroadcast() {
|
||||
return clusterBroadcast;
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,16 @@ package com.krylov.refound.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.dto.CachedMapMarkers;
|
||||
import com.krylov.refound.dto.CachedPostPage;
|
||||
import com.krylov.refound.dto.MapMarkerDto;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.listener.ChannelTopic;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@@ -21,11 +23,6 @@ public class RedisConfig {
|
||||
return buildTemplate(connectionFactory, objectMapper, CachedPostPage.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, CachedMapMarkers> feedRedisTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper) {
|
||||
return buildTemplate(connectionFactory, objectMapper, CachedMapMarkers.class);
|
||||
}
|
||||
|
||||
private static <T> RedisTemplate<String, T> buildTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper, Class<T> type) {
|
||||
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
|
||||
// а неизвестные поля в старых записях не должны валить десериализацию
|
||||
@@ -60,4 +57,15 @@ public class RedisConfig {
|
||||
template.setValueSerializer(valueSerializer);
|
||||
return template;
|
||||
}
|
||||
|
||||
/** Подписка на канал рассылки WebSocket-сообщений между экземплярами (см. ClusterMessaging). */
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "app.websocket.cluster-broadcast", havingValue = "true", matchIfMissing = true)
|
||||
public RedisMessageListenerContainer wsBroadcastListenerContainer(RedisConnectionFactory connectionFactory,
|
||||
ClusterMessaging clusterMessaging) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
container.addMessageListener(clusterMessaging, new ChannelTopic(ClusterMessaging.CHANNEL));
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import net.javacrumbs.shedlock.core.LockProvider;
|
||||
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider;
|
||||
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
|
||||
/**
|
||||
* Распределённая блокировка фоновых задач (ShedLock). Приложение может работать
|
||||
* в нескольких экземплярах: без блокировки ночная чистка и модерация запускались
|
||||
* бы в каждом из них одновременно. Задача с {@code @SchedulerLock} выполняется
|
||||
* тем экземпляром, который первым взял блокировку в Redis
|
||||
* ({@code job-lock:refound:<имя задачи>}); остальные пропускают запуск.
|
||||
*
|
||||
* <p>Если Redis недоступен, блокировку взять нельзя и задача пропускается до
|
||||
* следующего запуска — это безопаснее, чем выполнить её во всех экземплярах.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
|
||||
public class SchedulerLockConfig {
|
||||
|
||||
static final String LOCK_ENVIRONMENT = "refound";
|
||||
|
||||
@Bean
|
||||
public LockProvider lockProvider(RedisConnectionFactory connectionFactory) {
|
||||
return new RedisLockProvider(connectionFactory, LOCK_ENVIRONMENT);
|
||||
}
|
||||
}
|
||||
32
src/main/java/com/krylov/refound/config/TimeZoneFilter.java
Normal file
32
src/main/java/com/krylov/refound/config/TimeZoneFilter.java
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.dto.StartChatRequest;
|
||||
import com.krylov.refound.service.ChatService;
|
||||
import com.krylov.refound.service.UserService;
|
||||
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.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -29,12 +32,21 @@ public class ChatController {
|
||||
private final UserService userService;
|
||||
private final ChatService chatService;
|
||||
|
||||
// Создать чат с пользователем или получить существующий
|
||||
@PostMapping("/with/{otherUserId}")
|
||||
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
|
||||
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
|
||||
@GetMapping("/with/{otherUserId}")
|
||||
public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
|
||||
Long currentUserId = extractUserId(auth);
|
||||
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
|
||||
return chatService.getOrCreateChat(currentUserId, otherUserId, postId);
|
||||
log.info("findChat currentUserId {}, otherUserId {}, postId {}", 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());
|
||||
}
|
||||
|
||||
// Список всех чатов текущего пользователя
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.dto.SendMessageRequest;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.service.ChatService;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -43,10 +45,14 @@ public class ChatWebSocketController {
|
||||
}
|
||||
|
||||
try {
|
||||
Object timezone = sessionAttributes.get(TimeZoneContext.SESSION_ATTRIBUTE);
|
||||
TimeZoneContext.set(timezone instanceof String tz ? tz : null);
|
||||
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
|
||||
} catch (SecurityException | IllegalArgumentException e) {
|
||||
} catch (ApiException | IllegalArgumentException e) {
|
||||
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
|
||||
);
|
||||
} finally {
|
||||
TimeZoneContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.service.FileStorageService;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -18,6 +22,13 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
@RequestMapping("/api/v1/files")
|
||||
@RequiredArgsConstructor
|
||||
public class FileStorageController {
|
||||
/**
|
||||
* Сколько браузер помнит редирект на presigned URL и не ходит за ним на бэк.
|
||||
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
|
||||
*/
|
||||
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
|
||||
private static final long MAX_PRESIGNED_TTL_HOURS = 7 * 24;
|
||||
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
@PostMapping
|
||||
@@ -34,6 +45,36 @@ public class FileStorageController {
|
||||
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;
|
||||
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
|
||||
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||
return ResponseEntity.ok(Map.of("url", url));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{*objectName}")
|
||||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||||
log.info("deleteFile {}", objectName);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.dto.PhoneRevealRequest;
|
||||
import com.krylov.refound.dto.PhoneRevealResponse;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.service.phone.PhoneRevealService;
|
||||
import com.krylov.refound.service.phone.ProofOfWorkService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.RestController;
|
||||
|
||||
/**
|
||||
* Показ номера автора: сначала задача proof-of-work, затем номер в обмен на
|
||||
* решение. Оба эндпоинта публичные — позвонить можно без регистрации.
|
||||
* IP — {@code request.getRemoteAddr()}, за прокси восстанавливается из
|
||||
* X-Forwarded-For (server.forward-headers-strategy).
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/posts/{id:\\d+}/phone")
|
||||
@RequiredArgsConstructor
|
||||
public class PhoneRevealController {
|
||||
|
||||
private final PhoneRevealService phoneRevealService;
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/challenge")
|
||||
public ResponseEntity<ProofOfWorkService.Challenge> challenge(@PathVariable Long id, HttpServletRequest request) {
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.noStore())
|
||||
.body(phoneRevealService.challenge(id, request.getRemoteAddr()));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<PhoneRevealResponse> reveal(@PathVariable Long id, @RequestBody PhoneRevealRequest body,
|
||||
HttpServletRequest request) {
|
||||
String phone = phoneRevealService.reveal(id, body.salt(), body.number(), body.signature(),
|
||||
request.getRemoteAddr(), currentUserId());
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.noStore())
|
||||
.body(new PhoneRevealResponse(phone));
|
||||
}
|
||||
|
||||
/** id пользователя с токеном или null для анонимного запроса. */
|
||||
private Long currentUserId() {
|
||||
try {
|
||||
User user = userService.getCurrentUser();
|
||||
return user == null ? null : user.getId();
|
||||
} catch (ApiException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,12 @@ package com.krylov.refound.controller;
|
||||
import com.krylov.refound.dto.PostRequest;
|
||||
import com.krylov.refound.dto.PostResponse;
|
||||
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 jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -11,7 +16,11 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import java.net.URI;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
@@ -32,33 +41,62 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
public class PostController {
|
||||
|
||||
private final PostService service;
|
||||
private final SearchSuggestService searchSuggestService;
|
||||
|
||||
/** 201 с созданным объявлением и Location на него (раньше — эхо PostRequest). */
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
log.info("create post {}", request.toString());
|
||||
return service.create(request, images);
|
||||
public ResponseEntity<PostResponse> create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
|
||||
PostResponse created = service.create(request, images);
|
||||
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
|
||||
.path("/{id}").buildAndExpand(created.getId()).toUri();
|
||||
return ResponseEntity.created(location).body(created);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
log.info("get all feed");
|
||||
return service.getFeed(search, pageable);
|
||||
public Page<PostResponse> getFeed(@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false) String type,
|
||||
@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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Одно объявление. Неопубликованное (MODERATION, REJECTED) видит только
|
||||
* владелец, остальным — 404. Объявления пользователя —
|
||||
* GET /api/v1/users/{userId}/posts.
|
||||
*/
|
||||
@GetMapping("/{id:\\d+}")
|
||||
public List<PostResponse> getById(@PathVariable Long id) {
|
||||
log.info("get feed by id {}", id);
|
||||
return service.getPostsByUserId(id);
|
||||
public PostResponse getById(@PathVariable Long id) {
|
||||
log.info("get post by id {}", id);
|
||||
return service.getPostById(id);
|
||||
}
|
||||
|
||||
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public PostResponse update(@PathVariable Long id, @RequestParam String type, @RequestParam String title, @RequestParam(required = false) String address,
|
||||
@RequestParam(required = false) Double latitude, @RequestParam(required = false) Double longitude, @RequestParam(required = false) String description,
|
||||
@RequestParam(required = false) String category, @RequestParam(required = false) String phone, @RequestParam(required = false) Boolean reward,
|
||||
@RequestParam(required = false) String category, @RequestParam(required = false) String phone,
|
||||
@RequestParam(required = false) Boolean phoneVisible, @RequestParam(required = false) Boolean reward,
|
||||
@RequestParam(required = false) String rewardText,
|
||||
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) {
|
||||
log.info("update post {}", id);
|
||||
return service.update(id, type, title, address, latitude, longitude, description, category, phone, reward, rewardText, images, existingImagesJson);
|
||||
return service.update(id, type, title, address, latitude, longitude, description, category, phone, phoneVisible, reward, rewardText, images,
|
||||
existingImagesJson);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@@ -73,22 +111,17 @@ public class PostController {
|
||||
return service.updateStatus(id, request.getStatus());
|
||||
}
|
||||
|
||||
@GetMapping("/search")
|
||||
public List<PostResponse> search(@RequestParam(required = false) String city) {
|
||||
log.info("search posts by city {}", city);
|
||||
return service.searchByCity(city);
|
||||
}
|
||||
|
||||
@GetMapping("/cities")
|
||||
public List<String> getCities() {
|
||||
log.info("get distinct cities");
|
||||
return service.getCities();
|
||||
}
|
||||
|
||||
/** Прежний адрес одного объявления — алиас GET /api/v1/posts/{id}. */
|
||||
@GetMapping("/detail/{postId}")
|
||||
public PostResponse getPostOnMapById(@PathVariable Long postId) {
|
||||
log.info("get post on map by id {}", postId);
|
||||
return service.getPostOnMapById(postId);
|
||||
public PostResponse getPostDetail(@PathVariable Long postId) {
|
||||
log.info("get post detail {}", postId);
|
||||
return service.getPostById(postId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.dto.PostResponse;
|
||||
import com.krylov.refound.service.PostService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Объявления пользователя: GET /api/v1/users/{userId}/posts. Публичный —
|
||||
* владельцу (с токеном) отдаются и неопубликованные (MODERATION, REJECTED).
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class UserPostController {
|
||||
|
||||
private final PostService postService;
|
||||
|
||||
@GetMapping("/api/v1/users/{userId:\\d+}/posts")
|
||||
public Page<PostResponse> getUserPosts(@PathVariable Long userId,
|
||||
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
log.info("get posts of user {}", userId);
|
||||
return postService.getPostsByUser(userId, pageable);
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,10 @@ public class AdvertisingAdminController {
|
||||
log.info("confirmUpload for advertisingId {}", advertisingId);
|
||||
Advertising advertising = advertisingRepository.findById(advertisingId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
|
||||
if (!advertisingAdminService.isOwnSourceKey(advertisingId, request.sourceKey())) {
|
||||
log.warn("confirmUpload: foreign sourceKey {} for advertisingId {}", request.sourceKey(), advertisingId);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
advertisingAdminService.updateTranscodingStatus(advertising.getId());
|
||||
eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey()));
|
||||
@@ -139,13 +143,14 @@ public class AdvertisingAdminController {
|
||||
log.warn("weight AdvertisingCreateRequestDto {} <= 0", request);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
||||
// Проверка до создания: раньше объявление создавалось и только потом отвечали 400
|
||||
if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) {
|
||||
log.warn("advertising image has bad mediaKey() or mediaKey isBlank");
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
||||
|
||||
AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(adminDto);
|
||||
}
|
||||
|
||||
@@ -6,10 +6,9 @@ import com.krylov.refound.dto.advertising.AdvertisingResponseDto;
|
||||
import com.krylov.refound.dto.advertising.ClickRequestDto;
|
||||
import com.krylov.refound.dto.advertising.ImpressionRequestDto;
|
||||
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
|
||||
import com.krylov.refound.service.advertising.AdvertisingClickService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingImpressionService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingSelectionService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingTrackingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -30,37 +29,40 @@ public class AdvertisingController {
|
||||
|
||||
private final AdvertisingSelectionService advertisingSelectionService;
|
||||
private final AdvertisingMediaService advertisingMediaService;
|
||||
private final AdvertisingImpressionService advertisingImpressionService;
|
||||
private final AdvertisingClickService advertisingClickService;
|
||||
private final AdvertisingTrackingService advertisingTrackingService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@GetMapping("/api/ads/next")
|
||||
public ResponseEntity<AdvertisingResponseDto> getNextAdvertising(Authentication authentication, @RequestHeader(value = "X-Session-Id", required = false) String sessionId, HttpServletRequest request) {
|
||||
log.info("getNextAdvertising");
|
||||
log.debug("getNextAdvertising");
|
||||
Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request);
|
||||
if (selected.isEmpty()) {
|
||||
log.warn("failed get advertising");
|
||||
// Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
|
||||
log.debug("No advertising to show, returning 204");
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
SelectedAdvertisingDto advertising = selected.get();
|
||||
String mediaUrl = advertisingMediaService.getMediaUrl(advertising.mediaKey());
|
||||
|
||||
return ResponseEntity.ok(new AdvertisingResponseDto(advertising.advertisingId(), advertising.type(), mediaUrl, advertising.targetUrl()));
|
||||
return ResponseEntity.ok(new AdvertisingResponseDto(advertising.advertisingId(), advertising.type(), mediaUrl,
|
||||
advertising.targetUrl(), advertising.impressionToken()));
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/impression")
|
||||
public ResponseEntity<Void> registerImpression(@RequestBody String body, Authentication authentication) throws JsonProcessingException {
|
||||
log.info("registerImpression for body {}", body);
|
||||
log.debug("registerImpression for body {}", body);
|
||||
ImpressionRequestDto request = objectMapper.readValue(body, ImpressionRequestDto.class);
|
||||
advertisingImpressionService.recordImpression(request.advertisingId(), authentication, request.sessionId());
|
||||
advertisingTrackingService.recordImpression(request.advertisingId(), authentication, request.sessionId(),
|
||||
request.token());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/click")
|
||||
public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) {
|
||||
log.info("registerClick");
|
||||
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId());
|
||||
log.debug("registerClick");
|
||||
advertisingTrackingService.recordClick(request.advertisingId(), authentication, request.sessionId(),
|
||||
request.token());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,12 @@ package com.krylov.refound.controller.advertising;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -23,9 +26,10 @@ public class AdvertisingMediaController {
|
||||
private final AdvertisingMediaService mediaService;
|
||||
|
||||
@GetMapping("/{*key}")
|
||||
public ResponseEntity<byte[]> getMedia(@PathVariable String key) {
|
||||
public ResponseEntity<Resource> getMedia(@PathVariable String key,
|
||||
@RequestHeader(value = HttpHeaders.RANGE, required = false) String range) {
|
||||
String mediaKey = key.startsWith("/") ? key.substring(1) : key;
|
||||
log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey);
|
||||
return mediaService.downloadMedia(mediaKey);
|
||||
log.debug("GET ads-media: key={} -> mediaKey={}, range={}", key, mediaKey, range);
|
||||
return mediaService.downloadMedia(mediaKey, range);
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,16 @@ import com.krylov.refound.dto.advertising.CampaignCreateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignResponseDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignUpdateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatsDto;
|
||||
import com.krylov.refound.service.advertising.CampaignService;
|
||||
import com.krylov.refound.service.advertising.CampaignStatsService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.validation.Valid;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@@ -30,6 +35,19 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class CampaignAdminController {
|
||||
|
||||
private final CampaignService campaignService;
|
||||
private final CampaignStatsService campaignStatsService;
|
||||
|
||||
/**
|
||||
* Показы, клики и CTR кампании по объявлениям. from/to — дни (yyyy-MM-dd)
|
||||
* включительно в часовом поясе рекламы; по умолчанию последние 30 дней.
|
||||
*/
|
||||
@GetMapping("/{campaignId}/stats")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<CampaignStatsDto> getStats(@PathVariable Long campaignId,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to) {
|
||||
return ResponseEntity.ok(campaignStatsService.getStats(campaignId, from, to));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import com.krylov.refound.util.AdTargetUrl;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -43,7 +44,9 @@ public class FullscreenAdAdminController {
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<FullscreenAdAdminResponseDto> create(@RequestBody FullscreenAdCreateRequestDto request) {
|
||||
FullscreenAdvertising ad = new FullscreenAdvertising();
|
||||
ad.setTargetUrl(request.targetUrl());
|
||||
// Ссылка у полноэкранного ролика необязательна, но если есть — только http(s)
|
||||
ad.setTargetUrl(request.targetUrl() == null || request.targetUrl().isBlank()
|
||||
? null : AdTargetUrl.requireValid(request.targetUrl()));
|
||||
FullscreenAdvertising saved = repository.save(ad);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved));
|
||||
}
|
||||
@@ -60,8 +63,7 @@ public class FullscreenAdAdminController {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String sourceKey = "fullscreen-sources/%d/%s%s".formatted(
|
||||
id, UUID.randomUUID(), extensionFor(request.contentType()));
|
||||
String sourceKey = sourcePrefix(id) + UUID.randomUUID() + extensionFor(request.contentType());
|
||||
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
|
||||
|
||||
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
|
||||
@@ -75,6 +77,12 @@ public class FullscreenAdAdminController {
|
||||
|
||||
FullscreenAdvertising ad = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
// Транскодер удаляет исходник после работы — чужой ключ сюда подставлять нельзя
|
||||
String sourceKey = request.sourceKey();
|
||||
if (sourceKey == null || !sourceKey.startsWith(sourcePrefix(id)) || sourceKey.contains("..")) {
|
||||
log.warn("confirmUpload: foreign sourceKey {} for fullscreen ad {}", sourceKey, id);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
ad.setTranscodingStatus(TranscodingStatus.PROCESSING);
|
||||
repository.save(ad);
|
||||
@@ -108,7 +116,13 @@ public class FullscreenAdAdminController {
|
||||
}
|
||||
|
||||
repository.findByStatus(FullscreenAdStatus.ACTIVE)
|
||||
.ifPresent(current -> current.setStatus(FullscreenAdStatus.INACTIVE));
|
||||
.filter(current -> !current.getId().equals(target.getId()))
|
||||
.ifPresent(current -> {
|
||||
current.setStatus(FullscreenAdStatus.INACTIVE);
|
||||
// Hibernate не гарантирует порядок UPDATE при flush: если target обновится
|
||||
// первым, две строки ACTIVE нарушат uq_fullscreen_ad_single_active
|
||||
repository.saveAndFlush(current);
|
||||
});
|
||||
|
||||
target.setStatus(FullscreenAdStatus.ACTIVE);
|
||||
return ResponseEntity.ok(toDto(target));
|
||||
@@ -124,6 +138,10 @@ public class FullscreenAdAdminController {
|
||||
return ResponseEntity.ok(toDto(ad));
|
||||
}
|
||||
|
||||
private static String sourcePrefix(Long id) {
|
||||
return "fullscreen-sources/%d/".formatted(id);
|
||||
}
|
||||
|
||||
private boolean isAllowedContentType(String contentType) {
|
||||
return contentType != null && (contentType.equals("video/mp4")
|
||||
|| contentType.equals("video/quicktime") || contentType.equals("video/webm"));
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CachedMapMarkers {
|
||||
|
||||
private List<MapMarkerDto> content;
|
||||
}
|
||||
@@ -1,12 +1,21 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
/** Краткая информация об объявлении для списка чатов. */
|
||||
/**
|
||||
* Краткая информация об объявлении для списка чатов: достаточно, чтобы отличить
|
||||
* чаты по похожим объявлениям (тип, город, закрыто ли). Полное объявление
|
||||
* фронт догружает по клику через GET /api/v1/posts/{id}.
|
||||
*/
|
||||
@Data
|
||||
public class ChatPostDto {
|
||||
private Long id;
|
||||
private String title;
|
||||
private List<String> images;
|
||||
private PostType type;
|
||||
private PostStatus status;
|
||||
private String city;
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class DialogResponse {
|
||||
private Long userId;
|
||||
private String userEmail;
|
||||
private String lastMessage;
|
||||
private LocalDateTime lastMessageTime;
|
||||
private Long unreadCount;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
/** Решение proof-of-work задачи из GET /api/v1/posts/{id}/phone/challenge. */
|
||||
public record PhoneRevealRequest(String salt, Long number, String signature) {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
/** Номер автора объявления (POST /api/v1/posts/{id}/phone). */
|
||||
public record PhoneRevealResponse(String phone) {
|
||||
}
|
||||
@@ -14,6 +14,8 @@ public class PostRequest {
|
||||
private String description;
|
||||
private String category;
|
||||
private String phone;
|
||||
/** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */
|
||||
private Boolean phoneVisible;
|
||||
private String imageUrl;
|
||||
private Double latitude;
|
||||
private Double longitude;
|
||||
|
||||
@@ -16,6 +16,7 @@ public class PostResponse {
|
||||
private String category;
|
||||
private String city;
|
||||
private String district;
|
||||
private String address;
|
||||
// Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку
|
||||
// объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал
|
||||
// null, и MapView падал на дефолтный центр.
|
||||
@@ -24,8 +25,18 @@ public class PostResponse {
|
||||
private PostType type;
|
||||
private PostStatus status;
|
||||
private LocalDateTime createdAt;
|
||||
private String userEmail;
|
||||
/** Когда пост закрыт (status = CLOSED); фронт показывает дату «найдено». */
|
||||
private LocalDateTime closedAt;
|
||||
/** Логин автора. */
|
||||
private String userLogin;
|
||||
/**
|
||||
* Номер автора — только в ответах самому автору (свои объявления, правка).
|
||||
* Остальные получают номер через POST /api/v1/posts/{id}/phone с решённой
|
||||
* proof-of-work задачей, чтобы его нельзя было собрать из ленты.
|
||||
*/
|
||||
private String phone;
|
||||
/** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */
|
||||
private boolean phoneVisible;
|
||||
private List<String> images;
|
||||
private Long userId;
|
||||
private Role userRole;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** Первое сообщение, с которым создаётся чат. */
|
||||
@Data
|
||||
public class StartChatRequest {
|
||||
private String content;
|
||||
}
|
||||
@@ -27,9 +27,12 @@ public class AdminPostResponse {
|
||||
private String category;
|
||||
private String city;
|
||||
private String district;
|
||||
private String address;
|
||||
private Double latitude;
|
||||
private Double longitude;
|
||||
private String phone;
|
||||
/** Автор согласился на показ номера; без согласия phone = null. */
|
||||
private boolean phoneVisible;
|
||||
private Boolean reward;
|
||||
private String rewardText;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record AdvertisingCreateRequestDto(
|
||||
Long campaignId,
|
||||
AdvertisingType type,
|
||||
@NotNull Long campaignId,
|
||||
@NotNull AdvertisingType type,
|
||||
String mediaKey, // обязателен только для IMAGE, для VIDEO — null
|
||||
String targetUrl,
|
||||
int weight
|
||||
|
||||
@@ -4,7 +4,9 @@ public record AdvertisingResponseDto(
|
||||
Long advertisingId,
|
||||
String type,
|
||||
String mediaUrl,
|
||||
String targetUrl
|
||||
String targetUrl,
|
||||
/** Подписанный токен показа: вернуть в /api/ads/impression и /api/ads/click. */
|
||||
String impressionToken
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
/** Показы, клики и CTR (в процентах) одного объявления за период отчёта. */
|
||||
public record AdvertisingStatsDto(
|
||||
Long advertisingId,
|
||||
long impressions,
|
||||
long clicks,
|
||||
double ctr
|
||||
) {
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record CampaignCreateRequestDto(
|
||||
String name,
|
||||
LocalDateTime startDate,
|
||||
LocalDateTime endDate,
|
||||
@NotBlank @Size(max = 255) String name,
|
||||
@NotNull LocalDateTime startDate,
|
||||
@NotNull LocalDateTime endDate,
|
||||
int dailyImpressionCap
|
||||
) {
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/** Отчёт по кампании за период [from, to] (оба дня включительно). CTR — в процентах. */
|
||||
public record CampaignStatsDto(
|
||||
Long campaignId,
|
||||
LocalDate from,
|
||||
LocalDate to,
|
||||
long impressions,
|
||||
long clicks,
|
||||
double ctr,
|
||||
List<AdvertisingStatsDto> advertisings
|
||||
) {
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CampaignStatusUpdateRequestDto(
|
||||
CampaignStatus status
|
||||
@NotNull CampaignStatus status
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record CampaignUpdateRequestDto(
|
||||
String name,
|
||||
LocalDateTime startDate,
|
||||
LocalDateTime endDate,
|
||||
@NotBlank @Size(max = 255) String name,
|
||||
@NotNull LocalDateTime startDate,
|
||||
@NotNull LocalDateTime endDate,
|
||||
int dailyImpressionCap
|
||||
) {
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record ClickRequestDto(
|
||||
Long advertisingId,
|
||||
String sessionId
|
||||
String sessionId,
|
||||
/** Тот же токен показа, что и для /api/ads/impression. */
|
||||
String token
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
|
||||
/**
|
||||
* Объявление, которое сейчас можно показывать, вместе с нужными для выбора
|
||||
* полями кампании. Неизменяемый снимок — его можно держать в кэше без сессии JPA.
|
||||
*/
|
||||
public record EligibleAdvertising(
|
||||
Long advertisingId,
|
||||
Long campaignId,
|
||||
AdvertisingType type,
|
||||
String mediaKey,
|
||||
String targetUrl,
|
||||
Integer weight,
|
||||
Integer dailyImpressionCap
|
||||
) {
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record FullscreenAdActivateRequestDto(boolean active) {
|
||||
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record ImpressionRequestDto(
|
||||
Long advertisingId,
|
||||
String sessionId
|
||||
String sessionId,
|
||||
/** Токен показа из GET /api/ads/next; без него — устаревший путь без защиты от повторов. */
|
||||
String token
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ public record SelectedAdvertisingDto(
|
||||
Long advertisingId,
|
||||
String type,
|
||||
String mediaKey,
|
||||
String targetUrl
|
||||
String targetUrl,
|
||||
String impressionToken
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.dto.user;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.krylov.refound.enums.Role;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -15,4 +16,13 @@ public class UserResponseDto {
|
||||
private String email;
|
||||
private String avatar;
|
||||
private Role role;
|
||||
|
||||
/**
|
||||
* Новая пара токенов — только в ответе PUT /api/v1/users/{id}, когда пользователь
|
||||
* сменил свой логин (логин — subject JWT, прежние токены больше не подходят).
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String token;
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String refreshToken;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.entity;
|
||||
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
@@ -18,7 +19,7 @@ import lombok.ToString;
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
|
||||
@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
|
||||
@Setter
|
||||
@ToString
|
||||
@@ -42,7 +43,7 @@ public class Chat {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.entity;
|
||||
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
@@ -38,6 +39,6 @@ public class Message {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
@@ -37,10 +38,21 @@ public class Post {
|
||||
private PostCategory category;
|
||||
private String city;
|
||||
private String district;
|
||||
// Полный адрес из формы; city/district — нормализованные данные геокодера
|
||||
@Column(length = 500)
|
||||
private String address;
|
||||
private Double latitude;
|
||||
private Double longitude;
|
||||
private LocalDateTime createdAt;
|
||||
// Хранится только при согласии на показ (phoneVisible); без него — null
|
||||
private String phone;
|
||||
// Согласие автора на показ номера другим пользователям (152-ФЗ).
|
||||
// false — режим «только чат», по умолчанию. Ведётся в PostService.applyPhone
|
||||
@Column(name = "phone_visible", nullable = false)
|
||||
private boolean phoneVisible = false;
|
||||
// Когда дано согласие на показ номера; сбрасывается при отзыве
|
||||
@Column(name = "phone_consent_at")
|
||||
private LocalDateTime phoneConsentAt;
|
||||
// В БД колонка boolean NOT NULL (changelog 013). Строка была рассинхронизирована
|
||||
// со схемой и ломала ddl-auto: validate.
|
||||
@Column(name = "rules_accepted", nullable = false)
|
||||
@@ -54,11 +66,33 @@ public class Post {
|
||||
@Enumerated(EnumType.STRING)
|
||||
private PostStatus status;
|
||||
|
||||
// Когда пост перешёл в CLOSED; по нему SchedulerService удаляет закрытые
|
||||
// больше недели назад. Ведётся в setStatus — менять напрямую не нужно.
|
||||
@Setter(lombok.AccessLevel.NONE)
|
||||
private LocalDateTime closedAt;
|
||||
|
||||
@ManyToOne
|
||||
@JsonIgnore
|
||||
private User user;
|
||||
|
||||
// Порядок загрузки: первая картинка (обложка в ленте, чатах, на карте) должна быть стабильной
|
||||
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OrderBy("id ASC")
|
||||
private List<Image> images = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Меняет статус и ведёт closedAt: переход в CLOSED ставит время закрытия,
|
||||
* уход из CLOSED (переоткрытие, правка с повторной модерацией) его сбрасывает.
|
||||
* Повторный CLOSED у уже закрытого поста время не сдвигает.
|
||||
*/
|
||||
public void setStatus(PostStatus status) {
|
||||
if (status == PostStatus.CLOSED) {
|
||||
if (this.status != PostStatus.CLOSED || closedAt == null) {
|
||||
closedAt = LocalDateTime.now();
|
||||
}
|
||||
} else {
|
||||
closedAt = null;
|
||||
}
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.entity;
|
||||
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
@@ -34,6 +35,6 @@ public class Review {
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.entity;
|
||||
|
||||
import com.krylov.refound.enums.Role;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
@@ -36,6 +37,6 @@ public class User {
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
this.createdAt = LocalDateTime.now();
|
||||
this.createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,12 @@ package com.krylov.refound.entity.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "advertising")
|
||||
@@ -27,7 +26,8 @@ public class Advertising {
|
||||
@Column(name = "type", nullable = false, length = 10)
|
||||
private AdvertisingType type;
|
||||
|
||||
@Column(name = "media_key", nullable = false, length = 512)
|
||||
// У видео ключ появляется только после транскодинга (changelog 012 снял NOT NULL)
|
||||
@Column(name = "media_key", length = 512)
|
||||
private String mediaKey;
|
||||
|
||||
@Column(name = "target_url", nullable = false, length = 1024)
|
||||
@@ -43,24 +43,10 @@ public class Advertising {
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "advertising",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Impression> impressions = new ArrayList<>();
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "advertising",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Click> clicks = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
package com.krylov.refound.entity.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "campaign")
|
||||
@@ -38,17 +37,10 @@ public class Campaign {
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "campaign",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Advertising> ads = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.entity.advertising;
|
||||
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -32,7 +33,7 @@ public class Click {
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (clickedAt == null) {
|
||||
clickedAt = LocalDateTime.now();
|
||||
clickedAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -38,7 +39,7 @@ public class FullscreenAdvertising {
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
createdAt = LocalDateTime.now();
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.entity.advertising;
|
||||
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -32,7 +33,7 @@ public class Impression {
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (shownAt == null) {
|
||||
shownAt = LocalDateTime.now();
|
||||
shownAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,6 @@ public enum ErrorCode {
|
||||
UNAUTHORIZED,
|
||||
FORBIDDEN,
|
||||
CONTENT_BLOCKED,
|
||||
INVALID_STATUS_TRANSITION
|
||||
INVALID_STATUS_TRANSITION,
|
||||
TOO_MANY_REQUESTS
|
||||
}
|
||||
|
||||
@@ -9,10 +9,17 @@ public class ApiException extends RuntimeException {
|
||||
|
||||
private final ErrorCode errorCode;
|
||||
private final HttpStatus status;
|
||||
/** Для 429: через сколько секунд повторить (заголовок Retry-After); null — не указывать. */
|
||||
private final Long retryAfterSeconds;
|
||||
|
||||
public ApiException(ErrorCode errorCode, String message, HttpStatus status) {
|
||||
this(errorCode, message, status, null);
|
||||
}
|
||||
|
||||
public ApiException(ErrorCode errorCode, String message, HttpStatus status, Long retryAfterSeconds) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
this.status = status;
|
||||
this.retryAfterSeconds = retryAfterSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,24 @@ package com.krylov.refound.exception;
|
||||
import com.krylov.refound.ai.exception.ContentBlockedException;
|
||||
import com.krylov.refound.dto.ModerationErrorDetails;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
|
||||
@RestControllerAdvice
|
||||
@Slf4j
|
||||
@@ -29,7 +38,13 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ApiException.class)
|
||||
public ResponseEntity<ErrorResponse> handleApiException(ApiException ex, HttpServletRequest request) {
|
||||
return buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request);
|
||||
ResponseEntity<ErrorResponse> response = buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request);
|
||||
if (ex.getRetryAfterSeconds() == null) {
|
||||
return response;
|
||||
}
|
||||
return ResponseEntity.status(response.getStatusCode())
|
||||
.header(HttpHeaders.RETRY_AFTER, Long.toString(ex.getRetryAfterSeconds()))
|
||||
.body(response.getBody());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@@ -44,8 +59,74 @@ public class GlobalExceptionHandler {
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ошибки привязки параметров (@Valid на @ModelAttribute, неверный тип в query/path).
|
||||
* MethodArgumentNotValidException обрабатывается выше и сюда не попадает.
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBind(BindException ex, HttpServletRequest request) {
|
||||
String message = ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(e -> e.getField() + " " + e.getDefaultMessage())
|
||||
.orElse("Validation error");
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<ErrorResponse> handleBadInput(Exception ex, HttpServletRequest request) {
|
||||
log.debug("Bad request {}: {}", request.getRequestURI(), ex.getMessage());
|
||||
String message = ex instanceof MethodArgumentTypeMismatchException mismatch
|
||||
? "Некорректное значение параметра " + mismatch.getName()
|
||||
: "Некорректное тело запроса";
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMaxUploadSize(MaxUploadSizeExceededException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.PAYLOAD_TOO_LARGE, ErrorCode.VALIDATION_ERROR,
|
||||
"Файл или запрос слишком большой", request);
|
||||
}
|
||||
|
||||
/**
|
||||
* @PreAuthorize бросает AccessDeniedException внутри контроллера — без этого
|
||||
* обработчика её перехватывал handleUnknown и отвечал 500 вместо 403.
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.FORBIDDEN, ErrorCode.FORBIDDEN, "Forbidden", request);
|
||||
}
|
||||
|
||||
/** BadCredentialsException из /auth/refresh и т.п. — это 401, а не 500. */
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAuthentication(AuthenticationException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHORIZED, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(EntityNotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleEntityNotFound(EntityNotFoundException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.NOT_FOUND, ErrorCode.NOT_FOUND, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
/** Гонка на уникальных ключах (повторная регистрация, двойной клик «в избранное»). */
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(DataIntegrityViolationException ex, HttpServletRequest request) {
|
||||
log.warn("Data integrity violation on {}: {}", request.getRequestURI(), ex.getMostSpecificCause().getMessage());
|
||||
return buildResponse(HttpStatus.CONFLICT, ErrorCode.BAD_REQUEST, "Конфликт данных, повторите запрос", request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnknown(Exception ex, HttpServletRequest request) {
|
||||
// Исключения Spring MVC (404 без маршрута, 405, 415, пропущенный параметр и т.п.)
|
||||
// сами знают свой HTTP-статус — без этой ветки они превращались в 500
|
||||
if (ex instanceof org.springframework.web.ErrorResponse springError) {
|
||||
HttpStatus status = HttpStatus.resolve(springError.getStatusCode().value());
|
||||
if (status != null && !status.is5xxServerError()) {
|
||||
return buildResponse(status, status == HttpStatus.NOT_FOUND ? ErrorCode.NOT_FOUND : ErrorCode.BAD_REQUEST,
|
||||
springError.getBody().getDetail(), request);
|
||||
}
|
||||
}
|
||||
log.error("Unexpected error", ex);
|
||||
|
||||
return buildResponse(
|
||||
|
||||
@@ -29,6 +29,9 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class StorageStructureService {
|
||||
|
||||
/** Сколько хранится удалённый (неактуальный) вариант файла — шанс восстановить ошибочно удалённое. */
|
||||
private static final int NONCURRENT_VERSION_DAYS = 30;
|
||||
|
||||
private final S3Client s3Client;
|
||||
private final MinioProperties properties;
|
||||
|
||||
@@ -70,12 +73,17 @@ public class StorageStructureService {
|
||||
try {
|
||||
log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket);
|
||||
|
||||
// Текущие версии файлов не истекают: правило "удалять всё старше 180 дней"
|
||||
// стирало аватары и картинки живых объявлений. Файлы удаляет само приложение
|
||||
// (удаление поста/аватара, ночная чистка постов); при версионировании от них
|
||||
// остаются неактуальные версии — их и убирает это правило. Id прежний, чтобы
|
||||
// конфигурация бакета перезаписалась при старте.
|
||||
LifecycleRule rule = LifecycleRule.builder()
|
||||
.id("delete-after-180-days-rule")
|
||||
.status(ExpirationStatus.ENABLED)
|
||||
.filter(f -> f.prefix(""))
|
||||
.expiration(exp -> exp.days(180))
|
||||
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(180))
|
||||
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(NONCURRENT_VERSION_DAYS))
|
||||
.expiration(exp -> exp.expiredObjectDeleteMarker(true))
|
||||
.build();
|
||||
|
||||
BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder()
|
||||
|
||||
@@ -16,15 +16,23 @@ public interface PostMapper {
|
||||
@Mapping(source = "category", target = "category", qualifiedByName = "stringToPostCategory")
|
||||
@Mapping(source = "rewardText", target = "reward")
|
||||
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "stringToBoolean")
|
||||
// Номер и согласие на его показ ставит PostService.applyPhone
|
||||
@Mapping(target = "phone", ignore = true)
|
||||
@Mapping(target = "phoneVisible", ignore = true)
|
||||
@Mapping(target = "phoneConsentAt", ignore = true)
|
||||
Post toEntity(PostRequest request);
|
||||
|
||||
@Mapping(source = "user.id", target = "userId")
|
||||
@Mapping(source = "user.login", target = "userEmail")
|
||||
@Mapping(source = "user.login", target = "userLogin")
|
||||
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
|
||||
@Mapping(target = "category", expression = "java(post.getCategory().getDisplayName())")
|
||||
// Категория необязательна: без проверки на null пост без категории ронял ленту с 500
|
||||
@Mapping(target = "category", expression = "java(post.getCategory() == null ? null : post.getCategory().getDisplayName())")
|
||||
@Mapping(source = "isReward", target = "reward")
|
||||
@Mapping(source = "reward", target = "rewardText")
|
||||
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
|
||||
// Номер в публичном ответе (лента, кэш ленты, избранное) не отдаётся:
|
||||
// владельцу его добавляет PostService.toOwnerResponse
|
||||
@Mapping(target = "phone", ignore = true)
|
||||
PostResponse toResponse(Post post);
|
||||
|
||||
/** Фронт присылает правила как строку ("true"), в БД колонка boolean. */
|
||||
|
||||
105
src/main/java/com/krylov/refound/ratelimit/RateLimitFilter.java
Normal file
105
src/main/java/com/krylov/refound/ratelimit/RateLimitFilter.java
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.PathContainer;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
import org.springframework.web.util.pattern.PathPatternParser;
|
||||
|
||||
/**
|
||||
* Ограничение частоты запросов по IP для уязвимых маршрутов: вход и регистрация
|
||||
* (перебор паролей, спам аккаунтами), публичный трекинг рекламы (накрутка),
|
||||
* загрузка файлов и создание объявлений. Правила — {@code rate-limit.rules}.
|
||||
*
|
||||
* <p>IP берётся из {@code request.getRemoteAddr()}; за обратным прокси он
|
||||
* восстанавливается из X-Forwarded-For (server.forward-headers-strategy=native).
|
||||
* При превышении — 429 с заголовком Retry-After в формате ErrorResponse.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
|
||||
private final RedisRateLimiter rateLimiter;
|
||||
private final RateLimitProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final List<CompiledRule> rules;
|
||||
|
||||
record CompiledRule(RateLimitProperties.Rule rule, List<PathPattern> patterns) {
|
||||
|
||||
boolean matches(HttpServletRequest request, PathContainer path) {
|
||||
String method = rule.getMethod();
|
||||
if (method != null && !method.isBlank() && !method.equalsIgnoreCase(request.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
return patterns.stream().anyMatch(pattern -> pattern.matches(path));
|
||||
}
|
||||
}
|
||||
|
||||
public RateLimitFilter(RedisRateLimiter rateLimiter, RateLimitProperties properties, ObjectMapper objectMapper) {
|
||||
this.rateLimiter = rateLimiter;
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
PathPatternParser parser = new PathPatternParser();
|
||||
this.rules = properties.getRules().stream()
|
||||
.map(rule -> new CompiledRule(rule, rule.getPaths().stream().map(parser::parse).toList()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !properties.isEnabled() || rules.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
PathContainer path = PathContainer.parsePath(request.getRequestURI().substring(request.getContextPath().length()));
|
||||
String clientIp = request.getRemoteAddr();
|
||||
|
||||
for (CompiledRule compiled : rules) {
|
||||
if (!compiled.matches(request, path)) {
|
||||
continue;
|
||||
}
|
||||
RateLimitProperties.Rule rule = compiled.rule();
|
||||
RedisRateLimiter.Decision decision = rateLimiter.hit(rule.getName(), clientIp, rule.getLimit(), rule.getWindow());
|
||||
if (!decision.allowed()) {
|
||||
log.warn("Rate limit '{}' превышен: ip={}, {} {}", rule.getName(), clientIp, request.getMethod(),
|
||||
request.getRequestURI());
|
||||
writeTooManyRequests(request, response, decision.retryAfterSeconds());
|
||||
return;
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void writeTooManyRequests(HttpServletRequest request, HttpServletResponse response, long retryAfter)
|
||||
throws IOException {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("timestamp", LocalDateTime.now());
|
||||
body.put("status", HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
body.put("error", ErrorCode.TOO_MANY_REQUESTS.name());
|
||||
body.put("message", "Слишком много запросов, повторите позже");
|
||||
body.put("path", request.getRequestURI());
|
||||
|
||||
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
response.setHeader(HttpHeaders.RETRY_AFTER, Long.toString(retryAfter));
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
objectMapper.writeValue(response.getWriter(), body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Лимиты запросов ({@code rate-limit.*} в application.yaml). Счётчики лежат в
|
||||
* Redis, поэтому лимит общий для всех экземпляров приложения.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "rate-limit")
|
||||
public class RateLimitProperties {
|
||||
|
||||
/** Выключатель всех лимитов (например, для нагрузочных тестов). */
|
||||
private boolean enabled = true;
|
||||
|
||||
/** Правила по маршрутам; ключ лимита — IP клиента. */
|
||||
private List<Rule> rules = new ArrayList<>();
|
||||
|
||||
/** Защита конкретного аккаунта от перебора пароля с разных IP. */
|
||||
private Login login = new Login();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Rule {
|
||||
/** Имя правила — часть ключа в Redis. */
|
||||
private String name;
|
||||
/** HTTP-метод; пусто — любой. */
|
||||
private String method;
|
||||
/** Шаблоны путей в стиле Spring MVC ({@code /api/v1/auth/login}, {@code /api/ads/**}). */
|
||||
private List<String> paths = new ArrayList<>();
|
||||
/** Сколько запросов разрешено за окно. */
|
||||
private int limit;
|
||||
private Duration window = Duration.ofMinutes(1);
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Login {
|
||||
/** Сколько неудачных входов в один аккаунт допускается за окно. */
|
||||
private int maxFailures = 10;
|
||||
private Duration window = Duration.ofMinutes(15);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.data.redis.core.script.RedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Счётчик с фиксированным окном в Redis: ключ {@code rl:<правило>:<субъект>:<номер окна>},
|
||||
* INCR и EXPIRE выполняются одним Lua-скриптом (атомарно, без «вечных» ключей).
|
||||
*
|
||||
* <p>Лимиты — защитный слой, а не бизнес-логика: при недоступном Redis запрос
|
||||
* пропускается (fail-open), чтобы сбой кэша не положил весь API.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RedisRateLimiter {
|
||||
|
||||
private static final RedisScript<Long> INCREMENT = new DefaultRedisScript<>("""
|
||||
local count = redis.call('INCR', KEYS[1])
|
||||
if count == 1 then
|
||||
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||
end
|
||||
return count
|
||||
""", Long.class);
|
||||
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
public RedisRateLimiter(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/** Результат проверки: разрешён ли запрос и через сколько секунд откроется окно. */
|
||||
public record Decision(boolean allowed, long count, long retryAfterSeconds) {
|
||||
|
||||
static Decision allow() {
|
||||
return new Decision(true, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Учитывает запрос и решает, укладывается ли он в лимит. */
|
||||
public Decision hit(String rule, String subject, int limit, Duration window) {
|
||||
long windowMillis = window.toMillis();
|
||||
long now = System.currentTimeMillis();
|
||||
long windowIndex = now / windowMillis;
|
||||
String key = "rl:" + rule + ":" + subject + ":" + windowIndex;
|
||||
try {
|
||||
Long count = redisTemplate.execute(INCREMENT, List.of(key), Long.toString(windowMillis));
|
||||
if (count == null) {
|
||||
return Decision.allow();
|
||||
}
|
||||
long retryAfter = Math.max(1, ((windowIndex + 1) * windowMillis - now + 999) / 1000);
|
||||
return new Decision(count <= limit, count, retryAfter);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Rate limit '{}' не проверен, Redis недоступен: {}", rule, e.getMessage());
|
||||
return Decision.allow();
|
||||
}
|
||||
}
|
||||
|
||||
/** Сбрасывает текущее окно (например, после успешного входа). */
|
||||
public void reset(String rule, String subject, Duration window) {
|
||||
long windowIndex = System.currentTimeMillis() / window.toMillis();
|
||||
try {
|
||||
redisTemplate.delete("rl:" + rule + ":" + subject + ":" + windowIndex);
|
||||
} catch (RuntimeException e) {
|
||||
log.debug("Rate limit '{}' не сброшен: {}", rule, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Текущее значение счётчика без увеличения (0, если ключа нет или Redis недоступен). */
|
||||
public long current(String rule, String subject, Duration window) {
|
||||
long windowIndex = System.currentTimeMillis() / window.toMillis();
|
||||
try {
|
||||
String value = redisTemplate.opsForValue().get("rl:" + rule + ":" + subject + ":" + windowIndex);
|
||||
return value == null ? 0 : Long.parseLong(value);
|
||||
} catch (RuntimeException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
@@ -10,22 +11,26 @@ import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface ChatRepository extends JpaRepository<Chat, Long> {
|
||||
|
||||
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2")
|
||||
Optional<Chat> findByUsers(Long u1, Long u2);
|
||||
/** Чат пары пользователей по конкретному объявлению (postId == null — чат без объявления). */
|
||||
@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, потому что запрос задан явно. */
|
||||
@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)")
|
||||
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);
|
||||
|
||||
/**
|
||||
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.
|
||||
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
|
||||
*/
|
||||
@Modifying
|
||||
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId = :postId")
|
||||
int clearPostReference(@Param("postId") Long postId);
|
||||
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId IN :postIds")
|
||||
int clearPostReferences(@Param("postIds") Collection<Long> postIds);
|
||||
}
|
||||
|
||||
@@ -15,4 +15,8 @@ public interface ImageRepository extends JpaRepository<Image, Long> {
|
||||
/** Один запрос вместо N+1 при сборке админской страницы объявлений. */
|
||||
@Query("select i from Image i where i.post.id in :postIds order by i.id asc")
|
||||
List<Image> findByPostIdIn(@Param("postIds") Collection<Long> postIds);
|
||||
|
||||
/** Все ключи картинок объявлений — для чистки файлов-сирот. */
|
||||
@Query("select i.url from Image i where i.url is not null")
|
||||
List<String> findAllUrls();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Message;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -14,7 +15,18 @@ public interface MessageRepository extends JpaRepository<Message, Long> {
|
||||
|
||||
Page<Message> findByChatIdOrderByCreatedAtDesc(Long chatId, Pageable pageable);
|
||||
|
||||
Optional<Message> findFirstByChatIdOrderByCreatedAtDesc(Long chatId);
|
||||
/**
|
||||
* Последнее сообщение каждого чата. «Последнее» — по id: createdAt пишется в
|
||||
* часовом поясе отправителя, и у собеседников из разных поясов не монотонен.
|
||||
*/
|
||||
@Query("SELECT m FROM Message m WHERE m.id IN "
|
||||
+ "(SELECT MAX(m2.id) FROM Message m2 WHERE m2.chatId IN :chatIds GROUP BY m2.chatId)")
|
||||
List<Message> findLastMessages(@Param("chatIds") Collection<Long> chatIds);
|
||||
|
||||
/** Непрочитанные сообщения от собеседника по каждому чату: строки (chatId, count). */
|
||||
@Query("SELECT m.chatId, COUNT(m) FROM Message m WHERE m.chatId IN :chatIds "
|
||||
+ "AND m.isRead = false AND m.senderId <> :userId GROUP BY m.chatId")
|
||||
List<Object[]> countUnreadByChat(@Param("chatIds") Collection<Long> chatIds, @Param("userId") Long userId);
|
||||
|
||||
long countByChatIdAndIsReadFalseAndSenderIdNot(Long chatId, Long userId);
|
||||
|
||||
|
||||
@@ -10,27 +10,24 @@ import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
|
||||
|
||||
List<Post> findByUserId(Long userId);
|
||||
Page<Post> findByUserId(Long userId, Pageable pageable);
|
||||
|
||||
List<Post> findByStatus(PostStatus status);
|
||||
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);
|
||||
|
||||
List<Post> findByStatusAndClosedAtBefore(PostStatus status, LocalDateTime closedBefore);
|
||||
|
||||
List<Post> findByCreatedAtBefore(LocalDateTime date);
|
||||
|
||||
@Query("select p.id from Post p where p.status = :status")
|
||||
List<Long> findIdsByStatus(@Param("status") PostStatus status);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("update Post p set p.status = :status where p.id = :id")
|
||||
void updateStatus(@Param("id") Long id, @Param("status") PostStatus status);
|
||||
|
||||
@Query("select distinct p.city from Post p where p.city is not null and p.status in :statuses order by p.city")
|
||||
List<String> findDistinctCities(@Param("statuses") Collection<PostStatus> statuses);
|
||||
|
||||
|
||||
@@ -2,7 +2,18 @@ package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Statistics;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface StatisticsRepository extends JpaRepository<Statistics, Long> {
|
||||
|
||||
/** Атомарный инкремент: read-modify-write в Java терял обновления при параллельных запросах. */
|
||||
@Modifying
|
||||
@Query("update Statistics s set s.postsCreated = s.postsCreated + 1 where s.id = :id")
|
||||
int incrementCreated(@Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Statistics s set s.postsFound = s.postsFound + 1 where s.id = :id")
|
||||
int incrementFound(@Param("id") Long id);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.User;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -13,4 +14,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
@Query("SELECT u.id FROM User u WHERE u.login = :login")
|
||||
Optional<Long> findUserByLogin(@Param("login") String login);
|
||||
|
||||
/** Все ключи аватаров — для чистки файлов-сирот. */
|
||||
@Query("SELECT u.avatarUrl FROM User u WHERE u.avatarUrl IS NOT NULL")
|
||||
List<String> findAllAvatarUrls();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.EligibleAdvertising;
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
@@ -9,16 +10,24 @@ import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface AdvertisingRepository extends JpaRepository<Advertising, Long> {
|
||||
|
||||
/** Объявления, которые можно показывать сейчас: активная кампания в окне дат и готовое медиа. */
|
||||
@Query("""
|
||||
SELECT a FROM Advertising a JOIN FETCH a.campaign c
|
||||
SELECT new com.krylov.refound.dto.advertising.EligibleAdvertising(
|
||||
a.id, c.id, a.type, a.mediaKey, a.targetUrl, a.weight, c.dailyImpressionCap)
|
||||
FROM Advertising a JOIN a.campaign c
|
||||
WHERE c.status = 'ACTIVE'
|
||||
AND a.transcodingStatus = 'READY'
|
||||
AND a.mediaKey IS NOT NULL
|
||||
AND :now BETWEEN c.startDate AND c.endDate
|
||||
""")
|
||||
List<Advertising> findEligibleAds(@Param("now") LocalDateTime now);
|
||||
List<EligibleAdvertising> findEligible(@Param("now") LocalDateTime now);
|
||||
|
||||
@Query("SELECT a.campaign.id FROM Advertising a WHERE a.id = :id")
|
||||
Optional<Long> findCampaignIdById(@Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
|
||||
@@ -2,22 +2,22 @@ package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Campaign;
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface CampaignRepository extends JpaRepository<Campaign, Long> {
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
UPDATE Campaign c
|
||||
SET c.status = :status
|
||||
WHERE c.id = :campaignId
|
||||
""")
|
||||
void updateStatus(@Param("campaignId") Long campaignId, @Param("status") CampaignStatus status);
|
||||
|
||||
List<Campaign> findAllByOrderByCreatedAtDesc();
|
||||
|
||||
/** Завершает кампании, у которых закончилось окно показа. */
|
||||
@Modifying
|
||||
@Query("UPDATE Campaign c SET c.status = :finished WHERE c.status IN :running AND c.endDate < :now")
|
||||
int finishExpired(@Param("now") LocalDateTime now, @Param("running") Collection<CampaignStatus> running,
|
||||
@Param("finished") CampaignStatus finished);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Click;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface ClickRepository extends JpaRepository<Click, Long> {
|
||||
|
||||
/** Число событий по объявлениям кампании за период [from, to): строки (advertisingId, count). */
|
||||
@Query("""
|
||||
SELECT e.advertising.id, COUNT(e) FROM Click e
|
||||
WHERE e.advertising.campaign.id = :campaignId AND e.clickedAt >= :from AND e.clickedAt < :to
|
||||
GROUP BY e.advertising.id
|
||||
""")
|
||||
List<Object[]> countByAdvertising(@Param("campaignId") Long campaignId, @Param("from") LocalDateTime from,
|
||||
@Param("to") LocalDateTime to);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface ImpressionRepository extends JpaRepository<Impression, Long> {
|
||||
|
||||
/** Число событий по объявлениям кампании за период [from, to): строки (advertisingId, count). */
|
||||
@Query("""
|
||||
SELECT e.advertising.id, COUNT(e) FROM Impression e
|
||||
WHERE e.advertising.campaign.id = :campaignId AND e.shownAt >= :from AND e.shownAt < :to
|
||||
GROUP BY e.advertising.id
|
||||
""")
|
||||
List<Object[]> countByAdvertising(@Param("campaignId") Long campaignId, @Param("from") LocalDateTime from,
|
||||
@Param("to") LocalDateTime to);
|
||||
}
|
||||
|
||||
77
src/main/java/com/krylov/refound/search/PostFeedFilter.java
Normal file
77
src/main/java/com/krylov/refound/search/PostFeedFilter.java
Normal 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();
|
||||
}
|
||||
}
|
||||
@@ -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 не
|
||||
* действует на следующий запрос. Оператор <% использует 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();
|
||||
}
|
||||
}
|
||||
158
src/main/java/com/krylov/refound/search/PostSearchService.java
Normal file
158
src/main/java/com/krylov/refound/search/PostSearchService.java
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
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 net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
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}")
|
||||
// Словарь общий (таблица search_words) — пересобирает один экземпляр
|
||||
@SchedulerLock(name = "rebuildSearchDictionary", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
|
||||
@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('ё', 'е');
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
85
src/main/java/com/krylov/refound/search/SynonymExpander.java
Normal file
85
src/main/java/com/krylov/refound/search/SynonymExpander.java
Normal 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("'", "''") + "'";
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,7 +36,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
final String token = authHeader.substring(7);
|
||||
|
||||
try {
|
||||
if (jwtService.isTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
if (jwtService.isAccessTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String login = jwtService.extractLogin(token);
|
||||
String role = jwtService.extractRole(token);
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ import org.springframework.stereotype.Service;
|
||||
public class JwtService {
|
||||
|
||||
private static final String ROLE_CLAIM = "role";
|
||||
/**
|
||||
* Тип токена. Access- и refresh-токены подписаны одним ключом, поэтому без
|
||||
* этого claim долгоживущий refresh-токен принимался бы как access-токен.
|
||||
*/
|
||||
private static final String TYPE_CLAIM = "typ";
|
||||
private static final String ACCESS_TYPE = "access";
|
||||
private static final String REFRESH_TYPE = "refresh";
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
@@ -29,6 +36,7 @@ public class JwtService {
|
||||
public String generateAccessToken(String login, String role) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(ROLE_CLAIM, role);
|
||||
claims.put(TYPE_CLAIM, ACCESS_TYPE);
|
||||
return buildToken(claims, login, accessExpiration);
|
||||
}
|
||||
|
||||
@@ -37,7 +45,9 @@ public class JwtService {
|
||||
* чтобы получить новый access-токен, а не для прямого доступа к API.
|
||||
*/
|
||||
public String generateRefreshToken(String login) {
|
||||
return buildToken(new HashMap<>(), login, refreshExpiration);
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(TYPE_CLAIM, REFRESH_TYPE);
|
||||
return buildToken(claims, login, refreshExpiration);
|
||||
}
|
||||
|
||||
public long getRefreshExpirationMillis() {
|
||||
@@ -62,21 +72,35 @@ public class JwtService {
|
||||
return extractClaim(token, claims -> claims.get(ROLE_CLAIM, String.class));
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
/**
|
||||
* Токен годится для доступа к API (HTTP и WebSocket). Токены, выданные до
|
||||
* появления claim "typ", различаем по роли: она есть только у access-токена.
|
||||
*/
|
||||
public boolean isAccessTokenValid(String token) {
|
||||
try {
|
||||
String login = extractLogin(token);
|
||||
return login != null && !isTokenExpired(token);
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) != null : ACCESS_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
/** Токен годится только для обмена на новую пару в /auth/refresh. */
|
||||
public boolean isRefreshTokenValid(String token) {
|
||||
try {
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) == null : REFRESH_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
|
||||
@@ -49,11 +49,13 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// публичные эндпоинты
|
||||
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||
// health-пробы балансировщика/оркестратора (без деталей состояния)
|
||||
.requestMatchers(HttpMethod.GET, "/actuator/health", "/actuator/health/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/users/*/posts").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
|
||||
.requestMatchers("/files/**", "/uploads/**").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
|
||||
|
||||
// изменяющие операции — только для авторизованных
|
||||
@@ -62,6 +64,8 @@ public class SecurityConfig {
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated()
|
||||
.requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated()
|
||||
.requestMatchers(HttpMethod.DELETE, "/api/v1/reviews/**").authenticated()
|
||||
// показ номера — без регистрации, защищён proof-of-work и лимитами (PhoneRevealService)
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/posts/*/phone").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/posts/**").authenticated()
|
||||
.requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated()
|
||||
.requestMatchers(HttpMethod.DELETE, "/api/v1/posts/**").authenticated()
|
||||
@@ -69,7 +73,6 @@ public class SecurityConfig {
|
||||
// реклама
|
||||
.requestMatchers(HttpMethod.GET, "/api/ads/next").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/impression").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/impression/beacon").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/click").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll()
|
||||
|
||||
@@ -115,6 +118,10 @@ public class SecurityConfig {
|
||||
config.setAllowedOrigins(origins);
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
// Без expose браузер прячет эти заголовки от кросс-доменного фронта:
|
||||
// Retry-After нужен для сообщения «повторите через N мин» на 429,
|
||||
// Location — ссылка на созданный ресурс (201 у POST /api/v1/posts)
|
||||
config.setExposedHeaders(List.of("Retry-After", "Location"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
|
||||
@@ -8,27 +8,43 @@ import com.krylov.refound.dto.RegisterRequest;
|
||||
import com.krylov.refound.dto.user.UserDto;
|
||||
import com.krylov.refound.dto.user.UserRegisterDto;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.exception.InvalidCredentialsException;
|
||||
import com.krylov.refound.exception.LoginAlreadyExistsException;
|
||||
import com.krylov.refound.ratelimit.RateLimitProperties;
|
||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
|
||||
private static final int MAX_LOGIN_LENGTH = 255;
|
||||
/** Минимум по рекомендациям NIST SP 800-63B для паролей, выбранных пользователем. */
|
||||
private static final int MIN_PASSWORD_LENGTH = 8;
|
||||
private static final String LOGIN_FAILURES_RULE = "login-failures";
|
||||
private static final int MAX_PASSWORD_BYTES = 72;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
private final RedisRateLimiter rateLimiter;
|
||||
private final RateLimitProperties rateLimitProperties;
|
||||
|
||||
public UserRegisterDto registerUser(RegisterRequest request) {
|
||||
validateRegistration(request);
|
||||
if (userRepository.findByLogin(request.getLogin()).isPresent()) {
|
||||
log.warn("registration failed: login {} already taken", request.getLogin());
|
||||
throw new LoginAlreadyExistsException("Логин уже занят");
|
||||
@@ -42,23 +58,35 @@ public class AuthService {
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
}
|
||||
|
||||
public UserRegisterDto loginUser(AuthRequest request) {
|
||||
User user = userRepository.findByLogin(request.getLogin()).orElse(null);
|
||||
String login = request.getLogin();
|
||||
// Перебор пароля одного аккаунта с разных IP: лимит по IP (RateLimitFilter) тут не спасает
|
||||
RateLimitProperties.Login loginLimit = rateLimitProperties.getLogin();
|
||||
if (login != null && rateLimitProperties.isEnabled()
|
||||
&& rateLimiter.current(LOGIN_FAILURES_RULE, login, loginLimit.getWindow()) >= loginLimit.getMaxFailures()) {
|
||||
log.warn("login blocked: too many failed attempts for {}", login);
|
||||
throw new ApiException(ErrorCode.TOO_MANY_REQUESTS,
|
||||
"Слишком много неудачных попыток входа, повторите позже", HttpStatus.TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
log.warn("login failed: login or password incorrect for {}", request.getLogin());
|
||||
User user = login == null ? null : userRepository.findByLogin(login).orElse(null);
|
||||
|
||||
if (user == null || request.getPassword() == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
log.warn("login failed: login or password incorrect for {}", login);
|
||||
if (login != null) {
|
||||
rateLimiter.hit(LOGIN_FAILURES_RULE, login, loginLimit.getMaxFailures(), loginLimit.getWindow());
|
||||
}
|
||||
throw new InvalidCredentialsException("Неверный логин или пароль");
|
||||
}
|
||||
rateLimiter.reset(LOGIN_FAILURES_RULE, login, loginLimit.getWindow());
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
@@ -69,18 +97,15 @@ public class AuthService {
|
||||
}
|
||||
|
||||
public AuthResponse refresh(RefreshRequest request) {
|
||||
String login = refreshTokenService.validateAndGetLogin(request.getRefreshToken())
|
||||
// ротация: consume отзывает старый refresh-токен, выдаём новую пару
|
||||
String login = refreshTokenService.consume(request.getRefreshToken())
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired refresh token"));
|
||||
|
||||
User user = userRepository.findByLogin(login)
|
||||
.orElseThrow(() -> new BadCredentialsException("User not found"));
|
||||
|
||||
// ротация: старый refresh-токен отзываем, выдаём новую пару
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
|
||||
String newAccessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String newRefreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", newRefreshToken);
|
||||
return new AuthResponse(newAccessToken, newRefreshToken, getUserDto(user));
|
||||
}
|
||||
|
||||
@@ -88,6 +113,23 @@ public class AuthService {
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* Без проверки пустой логин сохранялся в БД, а null-пароль ронял BCrypt с 500.
|
||||
* Ответ при ошибке — тот же формат {"message"}, что и у занятого логина.
|
||||
*/
|
||||
private static void validateRegistration(RegisterRequest request) {
|
||||
if (!StringUtils.hasText(request.getLogin()) || request.getLogin().length() > MAX_LOGIN_LENGTH) {
|
||||
throw new InvalidCredentialsException("Логин не может быть пустым или длиннее " + MAX_LOGIN_LENGTH + " символов");
|
||||
}
|
||||
String password = request.getPassword();
|
||||
// BCrypt учитывает только первые 72 байта пароля
|
||||
if (password == null || password.length() < MIN_PASSWORD_LENGTH
|
||||
|| password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
|
||||
throw new InvalidCredentialsException("Пароль должен быть не короче " + MIN_PASSWORD_LENGTH
|
||||
+ " символов и не длиннее " + MAX_PASSWORD_BYTES + " байт");
|
||||
}
|
||||
}
|
||||
|
||||
private static UserDto getUserDto(User user) {
|
||||
return new UserDto(
|
||||
user.getId(),
|
||||
|
||||
@@ -1,48 +1,96 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.ChatPostDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
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.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatService {
|
||||
|
||||
/** Максимальная длина сообщения в символах. */
|
||||
public static final int MAX_MESSAGE_LENGTH = 4000;
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final MessageRepository messageRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Рассылка через Redis во все экземпляры: получатель может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
private final UserRepository userRepository;
|
||||
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
|
||||
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)) {
|
||||
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 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();
|
||||
newChat.setUserOneId(userId1);
|
||||
newChat.setUserTwoId(userId2);
|
||||
@@ -50,14 +98,25 @@ public class ChatService {
|
||||
return chatRepository.save(newChat);
|
||||
});
|
||||
|
||||
saveAndBroadcast(chat, currentUserId, content);
|
||||
return toDto(chat, currentUserId);
|
||||
}
|
||||
|
||||
// Все чаты пользователя
|
||||
// Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
|
||||
@Transactional(readOnly = true)
|
||||
public List<ChatDto> getUserChats(Long userId) {
|
||||
return chatRepository.findAllByUserId(userId).stream()
|
||||
.map(c -> toDto(c, userId))
|
||||
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||||
}
|
||||
|
||||
List<Chat> chats = chatRepository.findAllByUserId(userId);
|
||||
Map<Long, Chat> byId = chats.stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
|
||||
return toDtos(chats, userId).stream()
|
||||
.map(dto -> {
|
||||
LocalDateTime created = byId.get(dto.getId()).getCreatedAt();
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : created);
|
||||
})
|
||||
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.map(ChatWithActivity::dto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -73,9 +132,26 @@ public class ChatService {
|
||||
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||||
@Transactional
|
||||
public void sendMessage(Long senderId, Long chatId, String content) {
|
||||
validateContent(content);
|
||||
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
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.setChatId(chatId);
|
||||
message.setSenderId(senderId);
|
||||
@@ -84,8 +160,6 @@ public class ChatService {
|
||||
|
||||
MessageDto dto = toMessageDto(message);
|
||||
|
||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
|
||||
// Уведомляем получателя об непрочитанных
|
||||
Long recipientId = chat.getUserOneId().equals(senderId)
|
||||
? chat.getUserTwoId()
|
||||
@@ -93,11 +167,28 @@ public class ChatService {
|
||||
|
||||
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
|
||||
|
||||
messagingTemplate.convertAndSend(
|
||||
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||||
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||||
afterCommit(() -> {
|
||||
messaging.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messaging.convertAndSend(
|
||||
"/topic/user/" + recipientId + "/unread",
|
||||
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
|
||||
@@ -128,50 +219,79 @@ public class ChatService {
|
||||
}
|
||||
|
||||
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) {
|
||||
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
||||
throw new SecurityException("Вы не участник этого чата");
|
||||
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
private ChatDto toDto(Chat chat, Long currentUserId) {
|
||||
Long otherUserId = chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
return toDtos(List.of(chat), currentUserId).get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Собирает ChatDto для списка чатов фиксированным числом запросов (собеседники,
|
||||
* объявления, последние сообщения, непрочитанные), а не пятью запросами на чат.
|
||||
*/
|
||||
private List<ChatDto> toDtos(List<Chat> chats, Long currentUserId) {
|
||||
if (chats.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
|
||||
Map<Long, User> users = userRepository.findAllById(chats.stream()
|
||||
.map(chat -> otherUserId(chat, currentUserId)).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(User::getId, Function.identity()));
|
||||
Map<Long, Post> posts = postRepository.findAllById(chats.stream()
|
||||
.map(Chat::getPostId).filter(Objects::nonNull).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(Post::getId, Function.identity()));
|
||||
Map<Long, Message> lastMessages = messageRepository.findLastMessages(chatIds).stream()
|
||||
.collect(Collectors.toMap(Message::getChatId, Function.identity()));
|
||||
Map<Long, Long> unread = new HashMap<>();
|
||||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||
}
|
||||
|
||||
return chats.stream().map(chat -> {
|
||||
Long otherUserId = otherUserId(chat, currentUserId);
|
||||
ChatDto dto = new ChatDto();
|
||||
dto.setId(chat.getId());
|
||||
dto.setOtherUserId(otherUserId);
|
||||
dto.setPostId(chat.getPostId());
|
||||
|
||||
userRepository.findById(otherUserId).ifPresent(user -> {
|
||||
dto.setOtherUserName(user.getName() + " " + user.getLastName());
|
||||
dto.setOtherUserAvatar(user.getAvatarUrl());
|
||||
});
|
||||
User other = users.get(otherUserId);
|
||||
if (other != null) {
|
||||
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
||||
dto.setOtherUserAvatar(other.getAvatarUrl());
|
||||
}
|
||||
|
||||
if (chat.getPostId() != null) {
|
||||
postRepository.findById(chat.getPostId()).ifPresent(post -> {
|
||||
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
||||
if (post != null) {
|
||||
ChatPostDto postDto = new ChatPostDto();
|
||||
postDto.setId(post.getId());
|
||||
postDto.setTitle(post.getTitle());
|
||||
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
|
||||
postDto.setType(post.getType());
|
||||
postDto.setStatus(post.getStatus());
|
||||
postDto.setCity(post.getCity());
|
||||
dto.setPost(postDto);
|
||||
});
|
||||
}
|
||||
|
||||
// без N+1: берём только последнее сообщение, а не всю историю
|
||||
messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId())
|
||||
.ifPresent(last -> {
|
||||
Message last = lastMessages.get(chat.getId());
|
||||
if (last != null) {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
});
|
||||
|
||||
dto.setUnreadCount(
|
||||
messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId)
|
||||
);
|
||||
|
||||
}
|
||||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||||
return dto;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private static Long otherUserId(Chat chat, Long currentUserId) {
|
||||
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
}
|
||||
|
||||
private MessageDto toMessageDto(Message m) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user