Compare commits

..

60 Commits

Author SHA1 Message Date
SlimusMinus
3eab2f30e0 Merge pull request #63 from SlimusMinus/feat-chat_post_info
All checks were successful
deploy-backend / deploy (push) Successful in 2m1s
Add type, status and city to chat post summary
2026-10-28 21:20:05 +03:00
SlimusMinus
45854ef2bd Add type, status and city to chat post summary
Lets the chat list tell apart chats about similar listings and mark
closed ones. The full listing is still loaded on demand via GET /posts/{id}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:17:39 +03:00
SlimusMinus
1a3be8e3ee Merge pull request #62 from SlimusMinus/fix-show_phone
All checks were successful
deploy-backend / deploy (push) Successful in 2m18s
fixed show phone number
2026-10-27 22:53:17 +03:00
SlimusMinus
1cd72fbec4 fixed show phone number 2026-10-27 22:49:16 +03:00
SlimusMinus
aa7c9f25f0 Merge pull request #61 from SlimusMinus/feat-closed_posts_ttl
All checks were successful
deploy-backend / deploy (push) Successful in 1m32s
Delete CLOSED posts only a week after closing; track closedAt
2026-10-26 23:52:55 +03:00
SlimusMinus
bbc9079502 Delete CLOSED posts only a week after closing; track closedAt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:44:17 +03:00
SlimusMinus
838e4aa6d5 Merge pull request #60 from SlimusMinus/ci-github_actions
All checks were successful
deploy-backend / deploy (push) Successful in 1m22s
Add GitHub Actions CI: run gradle tests on PRs to master
2026-10-21 22:36:51 +03:00
SlimusMinus
d6c88f9e57 Add GitHub Actions CI: run gradle tests on PRs to master
Runs ./gradlew test (Temurin 25, Gradle cache, Testcontainers on the
runner's Docker) on every pull request to master and on push to master,
uploading build/reports/tests when tests fail. gradlew gets the
executable bit in git. The gitea deploy workflow is unchanged. README
describes the check and recommends making it required for master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:27:59 +03:00
SlimusMinus
f660e6828b Merge pull request #59 from SlimusMinus/add_tests
All checks were successful
deploy-backend / deploy (push) Successful in 1m14s
added tests
2026-10-21 00:17:25 +03:00
SlimusMinus
0dba36f3aa added tests 2026-10-21 00:15:54 +03:00
SlimusMinus
7766fb0b07 Merge pull request #58 from SlimusMinus/fix-posts_api_stage2
All checks were successful
deploy-backend / deploy (push) Successful in 1m25s
Posts API stage 2: /posts/{id} is one post, drop userEmail and /posts…
2026-10-21 00:10:42 +03:00
SlimusMinus
d782bee645 Posts API stage 2: /posts/{id} is one post, drop userEmail and /posts/search
- GET /api/v1/posts/{id} returns a single post (owner-only for unpublished);
  /detail/{id} stays as an alias; user posts live at /api/v1/users/{userId}/posts
- POST /api/v1/posts Location points to /api/v1/posts/{id}
- PostResponse.userEmail removed (use userLogin); unused DialogResponse removed
- GET /api/v1/posts/search?city= removed (same filter: GET /api/v1/posts?city=)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 00:03:39 +03:00
SlimusMinus
13d09d0073 Merge pull request #57 from SlimusMinus/fix-posts_api_contract
All checks were successful
deploy-backend / deploy (push) Successful in 1m32s
Posts API: user posts page, 201 on create, userLogin, deprecate old r…
2026-10-20 22:58:32 +03:00
SlimusMinus
ee5fb4e0e0 Posts API: user posts page, 201 on create, userLogin, deprecate old routes
- GET /api/v1/users/{userId}/posts returns Page<PostResponse> (owner sees unpublished)
- POST /api/v1/posts returns 201 with the created PostResponse and Location
- PostResponse.userLogin; userEmail kept with the same value as deprecated
- GET /api/v1/posts/{userId} and /search?city= marked deprecated; search is paged
- CORS exposes Retry-After and Location to the frontend

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:50:05 +03:00
SlimusMinus
248b4de752 Merge pull request #56 from SlimusMinus/claude/backend-review-80c5df
Claude/backend review 80c5df
2026-10-20 01:50:51 +03:00
SlimusMinus
ba6935bb1f Document multi-instance setup, rate limits and the new ad flow
README: new environment variables, ShedLock jobs and the multi-instance
section, rate limits and login lockout, profile privacy and token reissue,
WebSocket fan-out, 429 errors, tests and the updated limitations.
docs/advertising.md: serve -> impression -> click with signed tokens,
per-campaign daily caps, stats endpoint, campaign auto-finish, ads.* settings.
docs/redis.md: all new keys, pub/sub, locks, rate limiting, failure modes.
docs/images-storage.md: uploads outside transactions and orphan cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:46:18 +03:00
SlimusMinus
4ff61d8eda Delete orphan files from the image bucket nightly
OrphanFileCleanupService (03:30, ShedLock) lists the bucket and deletes objects
older than 24 hours that no images.url or users.avatar_url points to (full
URLs in legacy rows are normalised to keys), at most 5000 per run. Such files
appear when an upload via POST /api/v1/files is never attached or a request
fails between upload and save. Deleted files stay recoverable for 30 days as
noncurrent versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:42:39 +03:00
SlimusMinus
3dcd27d08a Keep network calls out of post transactions; cache and throttle geocoding
- PostService.create/update geocode and upload photos before opening the DB
  transaction (TransactionTemplate); uploaded files are removed if the
  transaction fails, so a DB connection is no longer held while waiting for
  Nominatim or MinIO.
- GeocodingService: configurable URL and User-Agent (geocoding.*), results
  cached in Redis for 30 days by coordinates rounded to ~11 m, and a
  cluster-wide 1 request/s slot (geo:throttle) as the public Nominatim policy
  requires; city/district are cut to the column sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:41:03 +03:00
SlimusMinus
85a2773f60 Build the chat list with batch queries instead of five queries per chat
Interlocutors, posts, last messages (one subquery by max id) and unread counts
(one GROUP BY) are loaded per list. The last message is now picked by id:
createdAt is written in the sender's time zone and is not monotonic between
users in different zones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:38:33 +03:00
SlimusMinus
2f52e6df70 Rework ad serving: signed impression tokens, per-campaign daily caps, stats
Follows the usual ad-server flow (serve -> impression -> click):
- GET /api/ads/next returns an impressionToken: HMAC-signed (ads.tracking.secret,
  defaults to jwt.secret) ad id, campaign id, subject and nonce, valid 1 hour.
  /impression and /click accept it, verify the signature, count each nonce once
  (Redis SET NX) and take the user/session from the token, so impressions
  cannot be forged or replayed. Requests without a token keep working until
  ads.tracking.require-token is switched on after the frontend update.
- The frequency cap is per campaign and calendar day (ads.timezone) and grows
  on real impressions, not on serving: ad:cap:<subject>:<campaign>:<yyyyMMdd>.
- Selection reads a 30-second in-memory snapshot of eligible ads (projection,
  invalidated locally on admin changes), filters capped campaigns with one
  MGET, picks by weight and then sets the cooldown atomically. The weighted
  sort drew random numbers inside the comparator, breaking its contract.
- Campaigns past endDate are finished every 10 minutes (ShedLock).
- GET /api/v1/admin/campaigns/{id}/stats: impressions, clicks and CTR per ad
  for a date range; composite indexes on impression/click (changelog 021).
- Removed unused cascade collections on Campaign/Advertising, the unused
  FullscreenAdActivateRequestDto and the /api/ads/impression/beacon rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:37:32 +03:00
SlimusMinus
477737c161 Hide private profile data and reissue tokens when users change their login
- GET /api/v1/users/{id} returns email and phone only to the user themself
  and to admins.
- When a user changes their own login, the PUT response carries a new token
  pair (login is the JWT subject, so the old tokens stop matching); old
  refresh tokens fail on their own because the stored login differs.
- The old avatar is deleted only after the profile is saved; login length is
  checked against the column size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:32:13 +03:00
SlimusMinus
48351398b5 Add Redis rate limiting, login lockout, password policy and health probes
- RateLimitFilter: fixed-window counters in Redis (Lua INCR+PEXPIRE) per
  client IP for login, registration, refresh, check-login, post creation,
  uploads, chat start and public ad endpoints; 429 with Retry-After; fails
  open when Redis is down. Rules live in rate-limit.* in application.yaml.
- Login is blocked for an account after 10 failed attempts in 15 minutes,
  independent of the client IP.
- Registration requires a password of at least 8 characters.
- server.forward-headers-strategy=native so the client IP survives a reverse
  proxy; graceful shutdown.
- /actuator/health with liveness/readiness probes is public (no details).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:31:12 +03:00
SlimusMinus
a696a21a1f Run safely with several instances: ShedLock jobs, Redis WebSocket fan-out
- Scheduled jobs (nightly cleanup, moderation, search dictionary rebuild) take
  a ShedLock lock in Redis, so only one instance runs each; the moderation run
  stops before its lock can expire.
- STOMP events (chat messages, unread counters, transcoding status) are
  published to the Redis channel ws:broadcast and every instance hands them to
  its local simple broker, so subscribers on other instances receive them.
  Falls back to local delivery if Redis is down; app.websocket.cluster-broadcast
  switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:31:12 +03:00
SlimusMinus
83270a8ece Rewrite README and add docs for advertising, Redis and image storage
README described Spring Boot 3.2.5/Java 21, an open /api/v1/test, the removed
MapCacheService and a single smoke test. It now matches the code: setup,
environment variables, architecture, packages, security rules, API, WebSocket
topics, post lifecycle, errors, tests, deploy and known limitations.

docs/advertising.md, docs/redis.md and docs/images-storage.md describe the
subsystems with references to the classes. .env.example lists the remaining
optional variables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:15:37 +03:00
SlimusMinus
7b81c18614 Give STOMP sessions a principal so /user/queue/errors is delivered
ChatWebSocketController reports send errors with convertAndSendToUser, but
CONNECT never set a user on the session, so those messages had no recipient.
The interceptor now sets a principal named after the user id on the message's
own accessor and allows subscriptions to /user/queue/** (resolved per session
by Spring, so it cannot reach another user's queue).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:09:57 +03:00
SlimusMinus
6b647e0bbf Add tests for the review fixes and make the context test runnable
- ReFoundApplicationTests runs on PostgreSQL via Testcontainers with a test
  profile holding test-only JWT/Redis/MinIO values; it previously failed
  without JWT_SECRET. The test also checks Liquibase + ddl validate.
- Unit tests: JWT access/refresh separation, refresh rotation, admin
  authority, exception mapping, image signature checks, ad media Range
  responses, post deletion after commit, moderation races, campaign status,
  ad selection without HttpSession and with Redis down, target URL rules.
- resolveRange rejects ranges that start past the end of the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:08:29 +03:00
SlimusMinus
3fd045131c Use ai.retry settings, add AI connect timeout, stop logging post text
AiRetryProperties was bound but @Retryable had hard-coded values, so
ai.retry.* in application.yaml had no effect. WebClient had no connect
timeout (Netty default 30 s per attempt). TextModerationProcessor logged the
whole moderation context, including post text, at INFO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:04:30 +03:00
SlimusMinus
a909b1f08b Fix advertising admin flows, tracking endpoints and ffmpeg timeout
- createAdvertising saved an IMAGE ad without mediaKey and only then answered
  400; validation now happens first. Target URLs must be absolute http(s)
  (they end up in href on the client), DTOs get @NotNull/@NotBlank.
- confirm-upload accepted any sourceKey; the transcoder deletes the source
  afterwards, so another ad's finished video could be deleted. Keys must now
  belong to the ad's own sources/ prefix.
- Activating a fullscreen ad could hit uq_fullscreen_ad_single_active because
  Hibernate may flush the new ACTIVE row first; the old one is flushed first.
- Campaign status change answered with the previous status (bulk UPDATE vs
  stale entity).
- Impression/click used getReferenceById, so unknown ids failed with 500 on
  the FK at commit; session ids are trimmed to the 64-char column.
- /api/ads/next created a Tomcat HttpSession for every client without
  X-Session-Id and failed with 500 when Redis was down; it now falls back to
  the client IP and returns 204 on Redis errors.
- ffmpeg output was read before waitFor, so the 5-minute timeout never fired;
  output goes to a temp log and its tail is logged on failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:04:10 +03:00
SlimusMinus
6e001fbc41 Fix post deletion, moderation races and cache leftovers
- PostService.delete did not remove favorites (FK without cascade -> 500 once a
  post was favorited) or chat links; owner, admin and nightly cleanup now share
  PostDeletionService, which deletes MinIO files only after commit. The nightly
  job also removes the images of expired posts.
- Moderation reads a snapshot in a short transaction, calls AI outside of it and
  applies the verdict only if the post is still in MODERATION and unchanged, so
  an edit made during a check can no longer go live unmoderated. Storage/AI
  outages keep the post in MODERATION instead of rejecting it.
- Posts without a category broke PostMapper with an NPE; title/phone/reward and
  address are checked against column sizes; a long address no longer overflows
  posts.city; Nominatim outages fall back to the address instead of 503.
- Favorites list hides posts that are back in moderation or rejected.
- Statistics counters use atomic UPDATEs instead of read-modify-write.
- Removed MapCacheService: its version key was bumped but never read.
- hibernate.default_batch_fetch_size=50 removes N+1 on images/users; show-sql
  is off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:02:12 +03:00
SlimusMinus
98e6789b7e Validate image signatures, stream ad media with Range, keep live files in MinIO
- Uploaded images are checked by magic bytes; the key extension and stored
  Content-Type come from the detected format, not from the client's filename
  (an .html file sent as image/png was stored as <uuid>.html).
- /api/v1/ads-media streams from MinIO instead of loading whole videos into
  the heap, answers Range requests with 206 (iOS Safari needs it for video)
  and sets a long public Cache-Control for immutable keys.
- The bucket lifecycle rule expired every object after 180 days, including
  avatars and images of live posts; now only noncurrent versions expire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:58:56 +03:00
SlimusMinus
5cd60b6318 Harden auth: separate access/refresh JWT, atomic refresh rotation, admin checks
- Refresh JWT carried no role but was accepted by JwtAuthenticationFilter and
  the STOMP CONNECT as an access token; tokens now carry a typ claim and the
  filters accept only access tokens (legacy tokens are told apart by role).
- Refresh rotation uses GETDEL, so one refresh token cannot be spent twice;
  refresh tokens are no longer written to logs.
- isCurrentUserAdmin and file deletion compared authorities with "ADMIN"
  instead of "ROLE_ADMIN", so admins were never recognised.
- getCurrentUser answers 401 for anonymous requests; profile update keeps the
  login when the field is not sent; registration rejects empty login/password.
- GlobalExceptionHandler turned AccessDenied, BadCredentials, EntityNotFound,
  Spring MVC 4xx errors and upload limits into 500.
- Presigned URL TTL is capped at 7 days.

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

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

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

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

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

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

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

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

5
.dockerignore Normal file
View File

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

60
.env.example Normal file
View 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=

View File

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

41
.github/workflows/ci.yml vendored Normal file
View 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
View File

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

2112
README.MD

File diff suppressed because it is too large Load Diff

View File

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

389
docs/advertising.md Normal file
View 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
View 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
View 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
View 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 не вешает
запросы надолго.

0
gradlew vendored Normal file → Executable file
View File

View File

@@ -3,6 +3,10 @@ package com.krylov.refound;
import com.krylov.refound.ai.config.AiProperties; import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.AiRetryProperties; import com.krylov.refound.ai.config.AiRetryProperties;
import com.krylov.refound.config.MinioProperties; import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.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 io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -15,7 +19,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
scanBasePackages = "com.krylov.refound", scanBasePackages = "com.krylov.refound",
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class } exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
)@EnableScheduling )@EnableScheduling
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class}) @EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class})
@EnableRetry @EnableRetry
public class ReFoundApplication { public class ReFoundApplication {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.config; package com.krylov.refound.ai.config;
import io.netty.channel.ChannelOption;
import java.time.Duration; import java.time.Duration;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import reactor.netty.http.client.HttpClient; import reactor.netty.http.client.HttpClient;
@@ -14,11 +15,15 @@ import org.springframework.web.reactive.function.client.WebClient;
@EnableConfigurationProperties(AiProperties.class) @EnableConfigurationProperties(AiProperties.class)
public class WebClientConfig { public class WebClientConfig {
private static final int CONNECT_TIMEOUT_MILLIS = 3_000;
@Bean @Bean
public WebClient aiWebClient(AiProperties properties) { public WebClient aiWebClient(AiProperties properties) {
log.info("aiWebClient get for properties {}", properties); log.info("aiWebClient get for properties {}", properties);
HttpClient httpClient = HttpClient httpClient =
HttpClient.create() HttpClient.create()
// Без явного таймаута соединения недоступный хост держал поток модерации ~30 с на попытку
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
.responseTimeout( .responseTimeout(
Duration.ofSeconds(properties.getTimeout()) Duration.ofSeconds(properties.getTimeout())
); );

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,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;
}
}

View File

@@ -2,14 +2,16 @@ package com.krylov.refound.config;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.krylov.refound.dto.CachedMapMarkers;
import com.krylov.refound.dto.CachedPostPage; import com.krylov.refound.dto.CachedPostPage;
import com.krylov.refound.dto.MapMarkerDto; import com.krylov.refound.dto.MapMarkerDto;
import java.util.List; import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate; 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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
@@ -21,11 +23,6 @@ public class RedisConfig {
return buildTemplate(connectionFactory, objectMapper, CachedPostPage.class); 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) { private static <T> RedisTemplate<String, T> buildTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper, Class<T> type) {
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша, // Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
// а неизвестные поля в старых записях не должны валить десериализацию // а неизвестные поля в старых записях не должны валить десериализацию
@@ -60,4 +57,15 @@ public class RedisConfig {
template.setValueSerializer(valueSerializer); template.setValueSerializer(valueSerializer);
return template; 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;
}
} }

View File

@@ -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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -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;
}
}
}

View File

@@ -3,7 +3,12 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.PostRequest; import com.krylov.refound.dto.PostRequest;
import com.krylov.refound.dto.PostResponse; import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.dto.StatusUpdateRequest; import com.krylov.refound.dto.StatusUpdateRequest;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.PostService; import com.krylov.refound.service.PostService;
import jakarta.validation.Valid;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; 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.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import 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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
@@ -32,33 +41,62 @@ import org.springframework.web.multipart.MultipartFile;
public class PostController { public class PostController {
private final PostService service; private final PostService service;
private final SearchSuggestService searchSuggestService;
/** 201 с созданным объявлением и Location на него (раньше — эхо PostRequest). */
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) { public ResponseEntity<PostResponse> create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post {}", request.toString()); log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
return service.create(request, images); PostResponse created = service.create(request, images);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.getId()).toUri();
return ResponseEntity.created(location).body(created);
} }
@GetMapping @GetMapping
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) { public Page<PostResponse> getFeed(@RequestParam(required = false) String search,
log.info("get all feed"); @RequestParam(required = false) String type,
return service.getFeed(search, pageable); @RequestParam(name = "category", required = false) List<String> categories,
@RequestParam(name = "city", required = false) List<String> cities,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get feed: search='{}', type={}, categories={}, cities={}", search, type, categories, cities);
PostFeedFilter filter;
try {
filter = PostFeedFilter.of(type, categories, cities);
} catch (IllegalArgumentException e) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Некорректный фильтр ленты: " + e.getMessage(),
HttpStatus.BAD_REQUEST);
}
return service.getFeed(search, filter, pageable);
} }
/** Подсказки для последнего слова строки поиска: «потерян барс» → [барсетка, барсик]. */
@GetMapping("/search/suggest")
public List<String> suggest(@RequestParam(name = "q", defaultValue = "") String query) {
return searchSuggestService.suggest(query);
}
/**
* Одно объявление. Неопубликованное (MODERATION, REJECTED) видит только
* владелец, остальным — 404. Объявления пользователя —
* GET /api/v1/users/{userId}/posts.
*/
@GetMapping("/{id:\\d+}") @GetMapping("/{id:\\d+}")
public List<PostResponse> getById(@PathVariable Long id) { public PostResponse getById(@PathVariable Long id) {
log.info("get feed by id {}", id); log.info("get post by id {}", id);
return service.getPostsByUserId(id); return service.getPostById(id);
} }
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @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, 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) 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(required = false) String rewardText,
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) { @RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) {
log.info("update post {}", id); 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}") @DeleteMapping("/{id}")
@@ -73,22 +111,17 @@ public class PostController {
return service.updateStatus(id, request.getStatus()); 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") @GetMapping("/cities")
public List<String> getCities() { public List<String> getCities() {
log.info("get distinct cities"); log.info("get distinct cities");
return service.getCities(); return service.getCities();
} }
/** Прежний адрес одного объявления — алиас GET /api/v1/posts/{id}. */
@GetMapping("/detail/{postId}") @GetMapping("/detail/{postId}")
public PostResponse getPostOnMapById(@PathVariable Long postId) { public PostResponse getPostDetail(@PathVariable Long postId) {
log.info("get post on map by id {}", postId); log.info("get post detail {}", postId);
return service.getPostOnMapById(postId); return service.getPostById(postId);
} }
} }

View File

@@ -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);
}
}

View File

@@ -86,6 +86,10 @@ public class AdvertisingAdminController {
log.info("confirmUpload for advertisingId {}", advertisingId); log.info("confirmUpload for advertisingId {}", advertisingId);
Advertising advertising = advertisingRepository.findById(advertisingId) Advertising advertising = advertisingRepository.findById(advertisingId)
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + 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()); advertisingAdminService.updateTranscodingStatus(advertising.getId());
eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey())); eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey()));
@@ -139,13 +143,14 @@ public class AdvertisingAdminController {
log.warn("weight AdvertisingCreateRequestDto {} <= 0", request); log.warn("weight AdvertisingCreateRequestDto {} <= 0", request);
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }
// Проверка до создания: раньше объявление создавалось и только потом отвечали 400
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) { if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) {
log.warn("advertising image has bad mediaKey() or mediaKey isBlank"); log.warn("advertising image has bad mediaKey() or mediaKey isBlank");
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising); AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising);
return ResponseEntity.status(HttpStatus.CREATED).body(adminDto); return ResponseEntity.status(HttpStatus.CREATED).body(adminDto);
} }

View File

@@ -6,10 +6,9 @@ import com.krylov.refound.dto.advertising.AdvertisingResponseDto;
import com.krylov.refound.dto.advertising.ClickRequestDto; import com.krylov.refound.dto.advertising.ClickRequestDto;
import com.krylov.refound.dto.advertising.ImpressionRequestDto; import com.krylov.refound.dto.advertising.ImpressionRequestDto;
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto; 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.AdvertisingMediaService;
import com.krylov.refound.service.advertising.AdvertisingSelectionService; import com.krylov.refound.service.advertising.AdvertisingSelectionService;
import com.krylov.refound.service.advertising.AdvertisingTrackingService;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional; import java.util.Optional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -30,37 +29,40 @@ public class AdvertisingController {
private final AdvertisingSelectionService advertisingSelectionService; private final AdvertisingSelectionService advertisingSelectionService;
private final AdvertisingMediaService advertisingMediaService; private final AdvertisingMediaService advertisingMediaService;
private final AdvertisingImpressionService advertisingImpressionService; private final AdvertisingTrackingService advertisingTrackingService;
private final AdvertisingClickService advertisingClickService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@GetMapping("/api/ads/next") @GetMapping("/api/ads/next")
public ResponseEntity<AdvertisingResponseDto> getNextAdvertising(Authentication authentication, @RequestHeader(value = "X-Session-Id", required = false) String sessionId, HttpServletRequest request) { 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); Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request);
if (selected.isEmpty()) { if (selected.isEmpty()) {
log.warn("failed get advertising"); // Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
log.debug("No advertising to show, returning 204");
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
SelectedAdvertisingDto advertising = selected.get(); SelectedAdvertisingDto advertising = selected.get();
String mediaUrl = advertisingMediaService.getMediaUrl(advertising.mediaKey()); 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") @PostMapping("/api/ads/impression")
public ResponseEntity<Void> registerImpression(@RequestBody String body, Authentication authentication) throws JsonProcessingException { 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); 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(); return ResponseEntity.accepted().build();
} }
@PostMapping("/api/ads/click") @PostMapping("/api/ads/click")
public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) { public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) {
log.info("registerClick"); log.debug("registerClick");
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId()); advertisingTrackingService.recordClick(request.advertisingId(), authentication, request.sessionId(),
request.token());
return ResponseEntity.accepted().build(); return ResponseEntity.accepted().build();
} }

View File

@@ -3,9 +3,12 @@ package com.krylov.refound.controller.advertising;
import com.krylov.refound.service.advertising.AdvertisingMediaService; import com.krylov.refound.service.advertising.AdvertisingMediaService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -23,9 +26,10 @@ public class AdvertisingMediaController {
private final AdvertisingMediaService mediaService; private final AdvertisingMediaService mediaService;
@GetMapping("/{*key}") @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; String mediaKey = key.startsWith("/") ? key.substring(1) : key;
log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey); log.debug("GET ads-media: key={} -> mediaKey={}, range={}", key, mediaKey, range);
return mediaService.downloadMedia(mediaKey); return mediaService.downloadMedia(mediaKey, range);
} }
} }

View File

@@ -4,12 +4,16 @@ import com.krylov.refound.dto.advertising.CampaignCreateRequestDto;
import com.krylov.refound.dto.advertising.CampaignResponseDto; import com.krylov.refound.dto.advertising.CampaignResponseDto;
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto; import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
import com.krylov.refound.dto.advertising.CampaignUpdateRequestDto; 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.CampaignService;
import com.krylov.refound.service.advertising.CampaignStatsService;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import java.time.LocalDate;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; 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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Slf4j @Slf4j
@@ -30,6 +35,19 @@ import org.springframework.web.bind.annotation.RestController;
public class CampaignAdminController { public class CampaignAdminController {
private final CampaignService campaignService; 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 @GetMapping
@PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasRole('ADMIN')")

View File

@@ -6,6 +6,7 @@ import com.krylov.refound.enums.advertising.FullscreenAdStatus;
import com.krylov.refound.enums.advertising.TranscodingStatus; import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository; import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
import com.krylov.refound.service.advertising.AdvertisingMediaService; import com.krylov.refound.service.advertising.AdvertisingMediaService;
import com.krylov.refound.util.AdTargetUrl;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -43,7 +44,9 @@ public class FullscreenAdAdminController {
@PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<FullscreenAdAdminResponseDto> create(@RequestBody FullscreenAdCreateRequestDto request) { public ResponseEntity<FullscreenAdAdminResponseDto> create(@RequestBody FullscreenAdCreateRequestDto request) {
FullscreenAdvertising ad = new FullscreenAdvertising(); 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); FullscreenAdvertising saved = repository.save(ad);
return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved)); return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved));
} }
@@ -60,8 +63,7 @@ public class FullscreenAdAdminController {
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }
String sourceKey = "fullscreen-sources/%d/%s%s".formatted( String sourceKey = sourcePrefix(id) + UUID.randomUUID() + extensionFor(request.contentType());
id, UUID.randomUUID(), extensionFor(request.contentType()));
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType()); String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES)); return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
@@ -75,6 +77,12 @@ public class FullscreenAdAdminController {
FullscreenAdvertising ad = repository.findById(id) FullscreenAdvertising ad = repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + 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); ad.setTranscodingStatus(TranscodingStatus.PROCESSING);
repository.save(ad); repository.save(ad);
@@ -108,7 +116,13 @@ public class FullscreenAdAdminController {
} }
repository.findByStatus(FullscreenAdStatus.ACTIVE) 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); target.setStatus(FullscreenAdStatus.ACTIVE);
return ResponseEntity.ok(toDto(target)); return ResponseEntity.ok(toDto(target));
@@ -124,6 +138,10 @@ public class FullscreenAdAdminController {
return ResponseEntity.ok(toDto(ad)); return ResponseEntity.ok(toDto(ad));
} }
private static String sourcePrefix(Long id) {
return "fullscreen-sources/%d/".formatted(id);
}
private boolean isAllowedContentType(String contentType) { private boolean isAllowedContentType(String contentType) {
return contentType != null && (contentType.equals("video/mp4") return contentType != null && (contentType.equals("video/mp4")
|| contentType.equals("video/quicktime") || contentType.equals("video/webm")); || contentType.equals("video/quicktime") || contentType.equals("video/webm"));

View File

@@ -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;
}

View File

@@ -1,12 +1,21 @@
package com.krylov.refound.dto; package com.krylov.refound.dto;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.enums.PostType;
import java.util.List; import java.util.List;
import lombok.Data; import lombok.Data;
/** Краткая информация об объявлении для списка чатов. */ /**
* Краткая информация об объявлении для списка чатов: достаточно, чтобы отличить
* чаты по похожим объявлениям (тип, город, закрыто ли). Полное объявление
* фронт догружает по клику через GET /api/v1/posts/{id}.
*/
@Data @Data
public class ChatPostDto { public class ChatPostDto {
private Long id; private Long id;
private String title; private String title;
private List<String> images; private List<String> images;
private PostType type;
private PostStatus status;
private String city;
} }

View File

@@ -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;
}

View File

@@ -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) {
}

View File

@@ -0,0 +1,5 @@
package com.krylov.refound.dto;
/** Номер автора объявления (POST /api/v1/posts/{id}/phone). */
public record PhoneRevealResponse(String phone) {
}

View File

@@ -14,6 +14,8 @@ public class PostRequest {
private String description; private String description;
private String category; private String category;
private String phone; private String phone;
/** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */
private Boolean phoneVisible;
private String imageUrl; private String imageUrl;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;

View File

@@ -16,6 +16,7 @@ public class PostResponse {
private String category; private String category;
private String city; private String city;
private String district; private String district;
private String address;
// Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку // Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку
// объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал // объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал
// null, и MapView падал на дефолтный центр. // null, и MapView падал на дефолтный центр.
@@ -24,8 +25,18 @@ public class PostResponse {
private PostType type; private PostType type;
private PostStatus status; private PostStatus status;
private LocalDateTime createdAt; 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 String phone;
/** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */
private boolean phoneVisible;
private List<String> images; private List<String> images;
private Long userId; private Long userId;
private Role userRole; private Role userRole;

View File

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

View File

@@ -27,9 +27,12 @@ public class AdminPostResponse {
private String category; private String category;
private String city; private String city;
private String district; private String district;
private String address;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
private String phone; private String phone;
/** Автор согласился на показ номера; без согласия phone = null. */
private boolean phoneVisible;
private Boolean reward; private Boolean reward;
private String rewardText; private String rewardText;
private LocalDateTime createdAt; private LocalDateTime createdAt;

View File

@@ -1,10 +1,11 @@
package com.krylov.refound.dto.advertising; package com.krylov.refound.dto.advertising;
import com.krylov.refound.enums.advertising.AdvertisingType; import com.krylov.refound.enums.advertising.AdvertisingType;
import jakarta.validation.constraints.NotNull;
public record AdvertisingCreateRequestDto( public record AdvertisingCreateRequestDto(
Long campaignId, @NotNull Long campaignId,
AdvertisingType type, @NotNull AdvertisingType type,
String mediaKey, // обязателен только для IMAGE, для VIDEO — null String mediaKey, // обязателен только для IMAGE, для VIDEO — null
String targetUrl, String targetUrl,
int weight int weight

View File

@@ -4,7 +4,9 @@ public record AdvertisingResponseDto(
Long advertisingId, Long advertisingId,
String type, String type,
String mediaUrl, String mediaUrl,
String targetUrl String targetUrl,
/** Подписанный токен показа: вернуть в /api/ads/impression и /api/ads/click. */
String impressionToken
) { ) {
} }

View File

@@ -0,0 +1,10 @@
package com.krylov.refound.dto.advertising;
/** Показы, клики и CTR (в процентах) одного объявления за период отчёта. */
public record AdvertisingStatsDto(
Long advertisingId,
long impressions,
long clicks,
double ctr
) {
}

View File

@@ -1,11 +1,14 @@
package com.krylov.refound.dto.advertising; 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; import java.time.LocalDateTime;
public record CampaignCreateRequestDto( public record CampaignCreateRequestDto(
String name, @NotBlank @Size(max = 255) String name,
LocalDateTime startDate, @NotNull LocalDateTime startDate,
LocalDateTime endDate, @NotNull LocalDateTime endDate,
int dailyImpressionCap int dailyImpressionCap
) { ) {

View File

@@ -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
) {
}

View File

@@ -1,9 +1,10 @@
package com.krylov.refound.dto.advertising; package com.krylov.refound.dto.advertising;
import com.krylov.refound.enums.advertising.CampaignStatus; import com.krylov.refound.enums.advertising.CampaignStatus;
import jakarta.validation.constraints.NotNull;
public record CampaignStatusUpdateRequestDto( public record CampaignStatusUpdateRequestDto(
CampaignStatus status @NotNull CampaignStatus status
) { ) {
} }

View File

@@ -1,11 +1,14 @@
package com.krylov.refound.dto.advertising; 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; import java.time.LocalDateTime;
public record CampaignUpdateRequestDto( public record CampaignUpdateRequestDto(
String name, @NotBlank @Size(max = 255) String name,
LocalDateTime startDate, @NotNull LocalDateTime startDate,
LocalDateTime endDate, @NotNull LocalDateTime endDate,
int dailyImpressionCap int dailyImpressionCap
) { ) {
} }

View File

@@ -2,7 +2,9 @@ package com.krylov.refound.dto.advertising;
public record ClickRequestDto( public record ClickRequestDto(
Long advertisingId, Long advertisingId,
String sessionId String sessionId,
/** Тот же токен показа, что и для /api/ads/impression. */
String token
) { ) {
} }

View File

@@ -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
) {
}

View File

@@ -1,5 +0,0 @@
package com.krylov.refound.dto.advertising;
public record FullscreenAdActivateRequestDto(boolean active) {
}

View File

@@ -2,6 +2,8 @@ package com.krylov.refound.dto.advertising;
public record ImpressionRequestDto( public record ImpressionRequestDto(
Long advertisingId, Long advertisingId,
String sessionId String sessionId,
/** Токен показа из GET /api/ads/next; без него — устаревший путь без защиты от повторов. */
String token
) { ) {
} }

View File

@@ -4,7 +4,8 @@ public record SelectedAdvertisingDto(
Long advertisingId, Long advertisingId,
String type, String type,
String mediaKey, String mediaKey,
String targetUrl String targetUrl,
String impressionToken
) { ) {
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.dto.user; package com.krylov.refound.dto.user;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.krylov.refound.enums.Role; import com.krylov.refound.enums.Role;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
@@ -15,4 +16,13 @@ public class UserResponseDto {
private String email; private String email;
private String avatar; private String avatar;
private Role role; 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;
} }

View File

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

View File

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

View File

@@ -14,6 +14,7 @@ import jakarta.persistence.GenerationType;
import jakarta.persistence.Id; import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
@@ -37,10 +38,21 @@ public class Post {
private PostCategory category; private PostCategory category;
private String city; private String city;
private String district; private String district;
// Полный адрес из формы; city/district — нормализованные данные геокодера
@Column(length = 500)
private String address;
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
private LocalDateTime createdAt; private LocalDateTime createdAt;
// Хранится только при согласии на показ (phoneVisible); без него — null
private String phone; 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). Строка была рассинхронизирована // В БД колонка boolean NOT NULL (changelog 013). Строка была рассинхронизирована
// со схемой и ломала ddl-auto: validate. // со схемой и ломала ddl-auto: validate.
@Column(name = "rules_accepted", nullable = false) @Column(name = "rules_accepted", nullable = false)
@@ -54,11 +66,33 @@ public class Post {
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private PostStatus status; private PostStatus status;
// Когда пост перешёл в CLOSED; по нему SchedulerService удаляет закрытые
// больше недели назад. Ведётся в setStatus — менять напрямую не нужно.
@Setter(lombok.AccessLevel.NONE)
private LocalDateTime closedAt;
@ManyToOne @ManyToOne
@JsonIgnore @JsonIgnore
private User user; private User user;
// Порядок загрузки: первая картинка (обложка в ленте, чатах, на карте) должна быть стабильной
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private List<Image> images = new ArrayList<>(); private List<Image> images = new ArrayList<>();
/**
* Меняет статус и ведёт 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;
}
} }

View File

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

View File

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

View File

@@ -2,13 +2,12 @@ package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.AdvertisingType; import com.krylov.refound.enums.advertising.AdvertisingType;
import com.krylov.refound.enums.advertising.TranscodingStatus; import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity @Entity
@Table(name = "advertising") @Table(name = "advertising")
@@ -27,7 +26,8 @@ public class Advertising {
@Column(name = "type", nullable = false, length = 10) @Column(name = "type", nullable = false, length = 10)
private AdvertisingType type; private AdvertisingType type;
@Column(name = "media_key", nullable = false, length = 512) // У видео ключ появляется только после транскодинга (changelog 012 снял NOT NULL)
@Column(name = "media_key", length = 512)
private String mediaKey; private String mediaKey;
@Column(name = "target_url", nullable = false, length = 1024) @Column(name = "target_url", nullable = false, length = 1024)
@@ -43,24 +43,10 @@ public class Advertising {
@Column(name = "created_at", nullable = false) @Column(name = "created_at", nullable = false)
private LocalDateTime createdAt; 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 @PrePersist
protected void onCreate() { protected void onCreate() {
if (createdAt == null) { if (createdAt == null) {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }
} }

View File

@@ -1,13 +1,12 @@
package com.krylov.refound.entity.advertising; package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.CampaignStatus; import com.krylov.refound.enums.advertising.CampaignStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity @Entity
@Table(name = "campaign") @Table(name = "campaign")
@@ -38,17 +37,10 @@ public class Campaign {
@Column(name = "created_at", nullable = false) @Column(name = "created_at", nullable = false)
private LocalDateTime createdAt; private LocalDateTime createdAt;
@OneToMany(
mappedBy = "campaign",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Advertising> ads = new ArrayList<>();
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if (createdAt == null) { if (createdAt == null) {
createdAt = LocalDateTime.now(); createdAt = TimeZoneContext.now();
} }
} }
} }

View File

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

View File

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

View File

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

View File

@@ -8,5 +8,6 @@ public enum ErrorCode {
UNAUTHORIZED, UNAUTHORIZED,
FORBIDDEN, FORBIDDEN,
CONTENT_BLOCKED, CONTENT_BLOCKED,
INVALID_STATUS_TRANSITION INVALID_STATUS_TRANSITION,
TOO_MANY_REQUESTS
} }

View File

@@ -9,10 +9,17 @@ public class ApiException extends RuntimeException {
private final ErrorCode errorCode; private final ErrorCode errorCode;
private final HttpStatus status; private final HttpStatus status;
/** Для 429: через сколько секунд повторить (заголовок Retry-After); null — не указывать. */
private final Long retryAfterSeconds;
public ApiException(ErrorCode errorCode, String message, HttpStatus status) { 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); super(message);
this.errorCode = errorCode; this.errorCode = errorCode;
this.status = status; this.status = status;
this.retryAfterSeconds = retryAfterSeconds;
} }
} }

View File

@@ -3,15 +3,24 @@ package com.krylov.refound.exception;
import com.krylov.refound.ai.exception.ContentBlockedException; import com.krylov.refound.ai.exception.ContentBlockedException;
import com.krylov.refound.dto.ModerationErrorDetails; import com.krylov.refound.dto.ModerationErrorDetails;
import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.enums.ErrorCode;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Map; import java.util.Map;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; 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.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@RestControllerAdvice @RestControllerAdvice
@Slf4j @Slf4j
@@ -29,7 +38,13 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class) @ExceptionHandler(ApiException.class)
public ResponseEntity<ErrorResponse> handleApiException(ApiException ex, HttpServletRequest request) { 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) @ExceptionHandler(MethodArgumentNotValidException.class)
@@ -44,8 +59,74 @@ public class GlobalExceptionHandler {
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request); 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) @ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnknown(Exception ex, HttpServletRequest request) { 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); log.error("Unexpected error", ex);
return buildResponse( return buildResponse(

View File

@@ -29,6 +29,9 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class StorageStructureService { public class StorageStructureService {
/** Сколько хранится удалённый (неактуальный) вариант файла — шанс восстановить ошибочно удалённое. */
private static final int NONCURRENT_VERSION_DAYS = 30;
private final S3Client s3Client; private final S3Client s3Client;
private final MinioProperties properties; private final MinioProperties properties;
@@ -70,12 +73,17 @@ public class StorageStructureService {
try { try {
log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket); log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket);
// Текущие версии файлов не истекают: правило "удалять всё старше 180 дней"
// стирало аватары и картинки живых объявлений. Файлы удаляет само приложение
// (удаление поста/аватара, ночная чистка постов); при версионировании от них
// остаются неактуальные версии — их и убирает это правило. Id прежний, чтобы
// конфигурация бакета перезаписалась при старте.
LifecycleRule rule = LifecycleRule.builder() LifecycleRule rule = LifecycleRule.builder()
.id("delete-after-180-days-rule") .id("delete-after-180-days-rule")
.status(ExpirationStatus.ENABLED) .status(ExpirationStatus.ENABLED)
.filter(f -> f.prefix("")) .filter(f -> f.prefix(""))
.expiration(exp -> exp.days(180)) .noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(NONCURRENT_VERSION_DAYS))
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(180)) .expiration(exp -> exp.expiredObjectDeleteMarker(true))
.build(); .build();
BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder() BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder()

View File

@@ -16,15 +16,23 @@ public interface PostMapper {
@Mapping(source = "category", target = "category", qualifiedByName = "stringToPostCategory") @Mapping(source = "category", target = "category", qualifiedByName = "stringToPostCategory")
@Mapping(source = "rewardText", target = "reward") @Mapping(source = "rewardText", target = "reward")
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "stringToBoolean") @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); Post toEntity(PostRequest request);
@Mapping(source = "user.id", target = "userId") @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(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 = "isReward", target = "reward")
@Mapping(source = "reward", target = "rewardText") @Mapping(source = "reward", target = "rewardText")
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString") @Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
// Номер в публичном ответе (лента, кэш ленты, избранное) не отдаётся:
// владельцу его добавляет PostService.toOwnerResponse
@Mapping(target = "phone", ignore = true)
PostResponse toResponse(Post post); PostResponse toResponse(Post post);
/** Фронт присылает правила как строку ("true"), в БД колонка boolean. */ /** Фронт присылает правила как строку ("true"), в БД колонка boolean. */

View 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);
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}
}

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.repository; package com.krylov.refound.repository;
import com.krylov.refound.entity.Chat; import com.krylov.refound.entity.Chat;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; 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> { public interface ChatRepository extends JpaRepository<Chat, Long> {
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2") /** Чат пары пользователей по конкретному объявлению (postId == null — чат без объявления). */
Optional<Chat> findByUsers(Long u1, Long u2); @Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2 "
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */ /** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c " @Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)") + "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
boolean isParticipantOfChat(Long chatId, Long userId); boolean isParticipantOfChat(Long chatId, Long userId);
@Query("SELECT c FROM Chat c WHERE c.userOneId = :userId OR c.userTwoId = :userId ORDER BY c.createdAt DESC") /** Чаты пользователя, в которых есть хотя бы одно сообщение (пустые в списке не показываем). */
List<Chat> findAllByUserId(Long userId); // Changed from Optional to List @Query("SELECT c FROM Chat c WHERE (c.userOneId = :userId OR c.userTwoId = :userId) "
+ "AND EXISTS (SELECT 1 FROM Message m WHERE m.chatId = c.id) ORDER BY c.createdAt DESC")
List<Chat> findAllByUserId(Long userId);
/** /**
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась. * Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500. * У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
*/ */
@Modifying @Modifying
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId = :postId") @Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId IN :postIds")
int clearPostReference(@Param("postId") Long postId); int clearPostReferences(@Param("postIds") Collection<Long> postIds);
} }

View File

@@ -15,4 +15,8 @@ public interface ImageRepository extends JpaRepository<Image, Long> {
/** Один запрос вместо N+1 при сборке админской страницы объявлений. */ /** Один запрос вместо N+1 при сборке админской страницы объявлений. */
@Query("select i from Image i where i.post.id in :postIds order by i.id asc") @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); List<Image> findByPostIdIn(@Param("postIds") Collection<Long> postIds);
/** Все ключи картинок объявлений — для чистки файлов-сирот. */
@Query("select i.url from Image i where i.url is not null")
List<String> findAllUrls();
} }

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.repository; package com.krylov.refound.repository;
import com.krylov.refound.entity.Message; import com.krylov.refound.entity.Message;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
@@ -14,7 +15,18 @@ public interface MessageRepository extends JpaRepository<Message, Long> {
Page<Message> findByChatIdOrderByCreatedAtDesc(Long chatId, Pageable pageable); 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); long countByChatIdAndIsReadFalseAndSenderIdNot(Long chatId, Long userId);

View File

@@ -10,27 +10,24 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 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.jpa.repository.Query;
import org.springframework.data.repository.query.Param; 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> { 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); List<Post> findByCreatedAtBefore(LocalDateTime date);
@Query("select p.id from Post p where p.status = :status") @Query("select p.id from Post p where p.status = :status")
List<Long> findIdsByStatus(@Param("status") PostStatus 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") @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); List<String> findDistinctCities(@Param("statuses") Collection<PostStatus> statuses);

View File

@@ -2,7 +2,18 @@ package com.krylov.refound.repository;
import com.krylov.refound.entity.Statistics; import com.krylov.refound.entity.Statistics;
import org.springframework.data.jpa.repository.JpaRepository; 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> { 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);
} }

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.repository; package com.krylov.refound.repository;
import com.krylov.refound.entity.User; import com.krylov.refound.entity.User;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; 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") @Query("SELECT u.id FROM User u WHERE u.login = :login")
Optional<Long> findUserByLogin(@Param("login") String login); Optional<Long> findUserByLogin(@Param("login") String login);
/** Все ключи аватаров — для чистки файлов-сирот. */
@Query("SELECT u.avatarUrl FROM User u WHERE u.avatarUrl IS NOT NULL")
List<String> findAllAvatarUrls();
} }

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.repository.advertising; package com.krylov.refound.repository.advertising;
import com.krylov.refound.dto.advertising.EligibleAdvertising;
import com.krylov.refound.entity.advertising.Advertising; import com.krylov.refound.entity.advertising.Advertising;
import com.krylov.refound.enums.advertising.TranscodingStatus; import com.krylov.refound.enums.advertising.TranscodingStatus;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
@@ -9,16 +10,24 @@ import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Optional;
public interface AdvertisingRepository extends JpaRepository<Advertising, Long> { public interface AdvertisingRepository extends JpaRepository<Advertising, Long> {
/** Объявления, которые можно показывать сейчас: активная кампания в окне дат и готовое медиа. */
@Query(""" @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' WHERE c.status = 'ACTIVE'
AND a.transcodingStatus = 'READY' AND a.transcodingStatus = 'READY'
AND a.mediaKey IS NOT NULL
AND :now BETWEEN c.startDate AND c.endDate 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 @Modifying
@Query(""" @Query("""

View File

@@ -2,22 +2,22 @@ package com.krylov.refound.repository.advertising;
import com.krylov.refound.entity.advertising.Campaign; import com.krylov.refound.entity.advertising.Campaign;
import com.krylov.refound.enums.advertising.CampaignStatus; import com.krylov.refound.enums.advertising.CampaignStatus;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List; import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CampaignRepository extends JpaRepository<Campaign, Long> { 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(); 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);
} }

View File

@@ -1,7 +1,20 @@
package com.krylov.refound.repository.advertising; package com.krylov.refound.repository.advertising;
import com.krylov.refound.entity.advertising.Click; 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.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface ClickRepository extends JpaRepository<Click, Long> { 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);
} }

View File

@@ -1,7 +1,20 @@
package com.krylov.refound.repository.advertising; package com.krylov.refound.repository.advertising;
import com.krylov.refound.entity.advertising.Impression; 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.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface ImpressionRepository extends JpaRepository<Impression, Long> { 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);
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,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('ё', 'е');
}
}

View File

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

View File

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

View File

@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -37,7 +36,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
final String token = authHeader.substring(7); final String token = authHeader.substring(7);
try { try {
if (jwtService.isTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) { if (jwtService.isAccessTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
String login = jwtService.extractLogin(token); String login = jwtService.extractLogin(token);
String role = jwtService.extractRole(token); String role = jwtService.extractRole(token);

View File

@@ -16,6 +16,13 @@ import org.springframework.stereotype.Service;
public class JwtService { public class JwtService {
private static final String ROLE_CLAIM = "role"; 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}") @Value("${jwt.secret}")
private String secret; private String secret;
@@ -29,6 +36,7 @@ public class JwtService {
public String generateAccessToken(String login, String role) { public String generateAccessToken(String login, String role) {
Map<String, Object> claims = new HashMap<>(); Map<String, Object> claims = new HashMap<>();
claims.put(ROLE_CLAIM, role); claims.put(ROLE_CLAIM, role);
claims.put(TYPE_CLAIM, ACCESS_TYPE);
return buildToken(claims, login, accessExpiration); return buildToken(claims, login, accessExpiration);
} }
@@ -37,7 +45,9 @@ public class JwtService {
* чтобы получить новый access-токен, а не для прямого доступа к API. * чтобы получить новый access-токен, а не для прямого доступа к API.
*/ */
public String generateRefreshToken(String login) { 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() { public long getRefreshExpirationMillis() {
@@ -62,21 +72,35 @@ public class JwtService {
return extractClaim(token, claims -> claims.get(ROLE_CLAIM, String.class)); 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 { try {
String login = extractLogin(token); Claims claims = extractAllClaims(token);
return login != null && !isTokenExpired(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) { } catch (Exception e) {
return false; return false;
} }
} }
private boolean isTokenExpired(String token) { /** Токен годится только для обмена на новую пару в /auth/refresh. */
return extractExpiration(token).before(new Date()); 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) { private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {

View File

@@ -49,11 +49,13 @@ public class SecurityConfig {
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
// публичные эндпоинты // публичные эндпоинты
.requestMatchers("/api/v1/auth/**").permitAll() .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/files/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/users/*/posts").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
.requestMatchers("/files/**", "/uploads/**").permitAll()
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже .requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
// изменяющие операции — только для авторизованных // изменяющие операции — только для авторизованных
@@ -62,6 +64,8 @@ public class SecurityConfig {
.requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated() .requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated() .requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/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.POST, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated() .requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/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.GET, "/api/ads/next").permitAll()
.requestMatchers(HttpMethod.POST, "/api/ads/impression").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.POST, "/api/ads/click").permitAll()
.requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll() .requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll()
@@ -115,6 +118,10 @@ public class SecurityConfig {
config.setAllowedOrigins(origins); config.setAllowedOrigins(origins);
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
config.setAllowedHeaders(List.of("*")); 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.setAllowCredentials(true);
config.setMaxAge(3600L); config.setMaxAge(3600L);

View File

@@ -8,27 +8,43 @@ import com.krylov.refound.dto.RegisterRequest;
import com.krylov.refound.dto.user.UserDto; import com.krylov.refound.dto.user.UserDto;
import com.krylov.refound.dto.user.UserRegisterDto; import com.krylov.refound.dto.user.UserRegisterDto;
import com.krylov.refound.entity.User; 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.InvalidCredentialsException;
import com.krylov.refound.exception.LoginAlreadyExistsException; 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.repository.UserRepository;
import com.krylov.refound.security.JwtService; import com.krylov.refound.security.JwtService;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class AuthService { 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 UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final JwtService jwtService; private final JwtService jwtService;
private final RefreshTokenService refreshTokenService; private final RefreshTokenService refreshTokenService;
private final RedisRateLimiter rateLimiter;
private final RateLimitProperties rateLimitProperties;
public UserRegisterDto registerUser(RegisterRequest request) { public UserRegisterDto registerUser(RegisterRequest request) {
validateRegistration(request);
if (userRepository.findByLogin(request.getLogin()).isPresent()) { if (userRepository.findByLogin(request.getLogin()).isPresent()) {
log.warn("registration failed: login {} already taken", request.getLogin()); log.warn("registration failed: login {} already taken", request.getLogin());
throw new LoginAlreadyExistsException("Логин уже занят"); throw new LoginAlreadyExistsException("Логин уже занят");
@@ -42,23 +58,35 @@ public class AuthService {
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name()); String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
String refreshToken = refreshTokenService.issue(user.getLogin()); String refreshToken = refreshTokenService.issue(user.getLogin());
log.info("Refresh token returned = {}", refreshToken);
UserDto userDto = getUserDto(user); UserDto userDto = getUserDto(user);
return new UserRegisterDto(userDto, accessToken, refreshToken); return new UserRegisterDto(userDto, accessToken, refreshToken);
} }
public UserRegisterDto loginUser(AuthRequest request) { 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())) { User user = login == null ? null : userRepository.findByLogin(login).orElse(null);
log.warn("login failed: login or password incorrect for {}", request.getLogin());
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("Неверный логин или пароль"); throw new InvalidCredentialsException("Неверный логин или пароль");
} }
rateLimiter.reset(LOGIN_FAILURES_RULE, login, loginLimit.getWindow());
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name()); String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
String refreshToken = refreshTokenService.issue(user.getLogin()); String refreshToken = refreshTokenService.issue(user.getLogin());
log.info("Refresh token returned = {}", refreshToken);
UserDto userDto = getUserDto(user); UserDto userDto = getUserDto(user);
return new UserRegisterDto(userDto, accessToken, refreshToken); return new UserRegisterDto(userDto, accessToken, refreshToken);
@@ -69,18 +97,15 @@ public class AuthService {
} }
public AuthResponse refresh(RefreshRequest request) { 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")); .orElseThrow(() -> new BadCredentialsException("Invalid or expired refresh token"));
User user = userRepository.findByLogin(login) User user = userRepository.findByLogin(login)
.orElseThrow(() -> new BadCredentialsException("User not found")); .orElseThrow(() -> new BadCredentialsException("User not found"));
// ротация: старый refresh-токен отзываем, выдаём новую пару
refreshTokenService.revoke(request.getRefreshToken());
String newAccessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name()); String newAccessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
String newRefreshToken = refreshTokenService.issue(user.getLogin()); String newRefreshToken = refreshTokenService.issue(user.getLogin());
log.info("Refresh token returned = {}", newRefreshToken);
return new AuthResponse(newAccessToken, newRefreshToken, getUserDto(user)); return new AuthResponse(newAccessToken, newRefreshToken, getUserDto(user));
} }
@@ -88,6 +113,23 @@ public class AuthService {
refreshTokenService.revoke(request.getRefreshToken()); 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) { private static UserDto getUserDto(User user) {
return new UserDto( return new UserDto(
user.getId(), user.getId(),

View File

@@ -1,48 +1,96 @@
package com.krylov.refound.service; package com.krylov.refound.service;
import com.krylov.refound.config.ClusterMessaging;
import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.ChatPostDto; import com.krylov.refound.dto.ChatPostDto;
import com.krylov.refound.dto.MessageDto; import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.entity.Chat; import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Image; import com.krylov.refound.entity.Image;
import com.krylov.refound.entity.Message; import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.Post;
import com.krylov.refound.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.ChatRepository;
import com.krylov.refound.repository.MessageRepository; import com.krylov.refound.repository.MessageRepository;
import com.krylov.refound.repository.PostRepository; import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.repository.UserRepository; import com.krylov.refound.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class ChatService { public class ChatService {
/** Максимальная длина сообщения в символах. */
public static final int MAX_MESSAGE_LENGTH = 4000;
private final ChatRepository chatRepository; private final ChatRepository chatRepository;
private final MessageRepository messageRepository; private final MessageRepository messageRepository;
private final SimpMessagingTemplate messagingTemplate; // Рассылка через Redis во все экземпляры: получатель может быть подключён к другому
private final ClusterMessaging messaging;
private final UserRepository userRepository; private final UserRepository userRepository;
private final PostRepository postRepository; private final PostRepository postRepository;
// Создать чат с пользователем (или вернуть существующий) /**
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
*/
@Transactional(readOnly = true)
public Optional<ChatDto> findChat(Long currentUserId, Long otherUserId, Long postId) {
Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId);
return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream()
.findFirst()
.map(chat -> toDto(chat, currentUserId));
}
/**
* Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт
* чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений.
*/
@Transactional @Transactional
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) { public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
validateContent(content);
if (currentUserId.equals(otherUserId)) { if (currentUserId.equals(otherUserId)) {
throw new IllegalArgumentException("Нельзя создать чат с самим собой"); throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
}
if (!userRepository.existsById(otherUserId)) {
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
}
if (postId != null) {
// Иначе клиент мог прикрепить к чату любое чужое объявление
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
Long ownerId = post.getUser().getId();
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
}
} }
Long userId1 = Math.min(currentUserId, otherUserId); Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId); Long userId2 = Math.max(currentUserId, otherUserId);
Chat chat = chatRepository.findByUsers(userId1, userId2).orElseGet(() -> { // Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
Chat newChat = new Chat(); Chat newChat = new Chat();
newChat.setUserOneId(userId1); newChat.setUserOneId(userId1);
newChat.setUserTwoId(userId2); newChat.setUserTwoId(userId2);
@@ -50,14 +98,25 @@ public class ChatService {
return chatRepository.save(newChat); return chatRepository.save(newChat);
}); });
saveAndBroadcast(chat, currentUserId, content);
return toDto(chat, currentUserId); return toDto(chat, currentUserId);
} }
// Все чаты пользователя // Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<ChatDto> getUserChats(Long userId) { public List<ChatDto> getUserChats(Long userId) {
return chatRepository.findAllByUserId(userId).stream() record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
.map(c -> toDto(c, userId)) }
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()); .collect(Collectors.toList());
} }
@@ -73,9 +132,26 @@ public class ChatService {
// Отправка сообщения (вызывается из WebSocket контроллера) // Отправка сообщения (вызывается из WebSocket контроллера)
@Transactional @Transactional
public void sendMessage(Long senderId, Long chatId, String content) { public void sendMessage(Long senderId, Long chatId, String content) {
validateContent(content);
Chat chat = getChatOrThrow(chatId); Chat chat = getChatOrThrow(chatId);
checkParticipant(chat, senderId); checkParticipant(chat, senderId);
saveAndBroadcast(chat, senderId, content);
}
private void validateContent(String content) {
if (content == null || content.isBlank()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
}
if (content.length() > MAX_MESSAGE_LENGTH) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
}
}
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
Long chatId = chat.getId();
Message message = new Message(); Message message = new Message();
message.setChatId(chatId); message.setChatId(chatId);
message.setSenderId(senderId); message.setSenderId(senderId);
@@ -84,8 +160,6 @@ public class ChatService {
MessageDto dto = toMessageDto(message); MessageDto dto = toMessageDto(message);
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
// Уведомляем получателя об непрочитанных // Уведомляем получателя об непрочитанных
Long recipientId = chat.getUserOneId().equals(senderId) Long recipientId = chat.getUserOneId().equals(senderId)
? chat.getUserTwoId() ? chat.getUserTwoId()
@@ -93,11 +167,28 @@ public class ChatService {
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId); long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
messagingTemplate.convertAndSend( // Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
// историю, мог не увидеть ещё не закоммиченное сообщение
afterCommit(() -> {
messaging.convertAndSend("/topic/chat/" + chatId, dto);
messaging.convertAndSend(
"/topic/user/" + recipientId + "/unread", "/topic/user/" + recipientId + "/unread",
Map.of("chatId", chatId, "unreadCount", unreadCount) Map.of("chatId", chatId, "unreadCount", unreadCount)
); );
});
}
private static void afterCommit(Runnable action) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
action.run();
}
});
} else {
action.run();
}
} }
@Transactional @Transactional
@@ -128,50 +219,79 @@ public class ChatService {
} }
private Chat getChatOrThrow(Long chatId) { private Chat getChatOrThrow(Long chatId) {
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден")); return chatRepository.findById(chatId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
} }
private void checkParticipant(Chat chat, Long userId) { private void checkParticipant(Chat chat, Long userId) {
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) { if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
throw new SecurityException("Вы не участник этого чата"); throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
} }
} }
private ChatDto toDto(Chat chat, Long currentUserId) { 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(); ChatDto dto = new ChatDto();
dto.setId(chat.getId()); dto.setId(chat.getId());
dto.setOtherUserId(otherUserId); dto.setOtherUserId(otherUserId);
dto.setPostId(chat.getPostId()); dto.setPostId(chat.getPostId());
userRepository.findById(otherUserId).ifPresent(user -> { User other = users.get(otherUserId);
dto.setOtherUserName(user.getName() + " " + user.getLastName()); if (other != null) {
dto.setOtherUserAvatar(user.getAvatarUrl()); dto.setOtherUserName(other.getName() + " " + other.getLastName());
}); dto.setOtherUserAvatar(other.getAvatarUrl());
}
if (chat.getPostId() != null) { Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
postRepository.findById(chat.getPostId()).ifPresent(post -> { if (post != null) {
ChatPostDto postDto = new ChatPostDto(); ChatPostDto postDto = new ChatPostDto();
postDto.setId(post.getId()); postDto.setId(post.getId());
postDto.setTitle(post.getTitle()); postDto.setTitle(post.getTitle());
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList()); postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
postDto.setType(post.getType());
postDto.setStatus(post.getStatus());
postDto.setCity(post.getCity());
dto.setPost(postDto); dto.setPost(postDto);
});
} }
// без N+1: берём только последнее сообщение, а не всю историю Message last = lastMessages.get(chat.getId());
messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId()) if (last != null) {
.ifPresent(last -> {
dto.setLastMessage(last.getContent()); dto.setLastMessage(last.getContent());
dto.setLastMessageAt(last.getCreatedAt()); dto.setLastMessageAt(last.getCreatedAt());
}); }
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
dto.setUnreadCount(
messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId)
);
return dto; 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) { private MessageDto toMessageDto(Message m) {

Some files were not shown because too many files have changed in this diff Show More