added advertising

This commit is contained in:
SlimusMinus
2026-09-23 23:34:05 +03:00
parent 05d93d6b0a
commit 942cd09585
83 changed files with 2546 additions and 46 deletions

View File

@@ -5,8 +5,8 @@ import com.krylov.refound.dto.AuthResponse;
import com.krylov.refound.dto.CheckLoginDto;
import com.krylov.refound.dto.RefreshRequest;
import com.krylov.refound.dto.RegisterRequest;
import com.krylov.refound.dto.UserDto;
import com.krylov.refound.dto.UserRegisterDto;
import com.krylov.refound.dto.user.UserDto;
import com.krylov.refound.dto.user.UserRegisterDto;
import com.krylov.refound.entity.User;
import com.krylov.refound.exception.InvalidCredentialsException;
import com.krylov.refound.exception.LoginAlreadyExistsException;

View File

@@ -1,7 +1,7 @@
package com.krylov.refound.service;
import com.krylov.refound.dto.UserResponseDto;
import com.krylov.refound.dto.UserUpdateDto;
import com.krylov.refound.dto.user.UserResponseDto;
import com.krylov.refound.dto.user.UserUpdateDto;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
@@ -104,6 +104,7 @@ public class UserService {
.email(user.getEmail())
.lastName(user.getLastName())
.avatar(user.getAvatarUrl())
.role(user.getRole())
.build();
}

View File

@@ -0,0 +1,102 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.AdvertisingAdminResponseDto;
import com.krylov.refound.dto.advertising.AdvertisingCreateRequestDto;
import com.krylov.refound.dto.advertising.AdvertisingUpdateRequestDto;
import com.krylov.refound.dto.advertising.PresignUploadRequestDto;
import com.krylov.refound.entity.advertising.Advertising;
import com.krylov.refound.entity.advertising.Campaign;
import com.krylov.refound.enums.advertising.AdvertisingType;
import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.repository.advertising.AdvertisingRepository;
import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingAdminService {
private final AdvertisingRepository advertisingRepository;
public Advertising createAdvertising(Campaign campaign, AdvertisingCreateRequestDto request){
Advertising advertising = new Advertising();
advertising.setCampaign(campaign);
advertising.setType(request.type());
advertising.setTargetUrl(request.targetUrl());
advertising.setWeight(request.weight());
if (request.type() == AdvertisingType.IMAGE) {
advertising.setMediaKey(request.mediaKey());
advertising.setTranscodingStatus(TranscodingStatus.READY);
} else {
// VIDEO — media_key появится только после presign-upload → confirm-upload → транскодинга
advertising.setMediaKey(null);
advertising.setTranscodingStatus(TranscodingStatus.PENDING);
}
log.info("Advertising {} created", advertising);
return advertising;
}
public void updateTranscodingStatus(Long advertisingId){
advertisingRepository.updateTranscodingStatus(advertisingId, TranscodingStatus.PROCESSING);
}
public String getSourceKey(Long advertisingId,PresignUploadRequestDto request){
String extensionFor = extensionFor(request.contentType());
return "sources/%d/%s%s".formatted(advertisingId, UUID.randomUUID(), extensionFor);
}
public String extensionFor(String contentType) {
return switch (contentType) {
case "video/quicktime" -> ".mov";
case "video/webm" -> ".webm";
default -> ".mp4";
};
}
public boolean isAllowedContentType(String contentType) {
return contentType != null && (contentType.equals("video/mp4")
|| contentType.equals("video/quicktime")
|| contentType.equals("video/webm"));
}
public AdvertisingAdminResponseDto toAdminDto(Advertising advertising) {
Advertising saved = advertisingRepository.save(advertising);
return mapToAdminDto(saved);
}
public List<AdvertisingAdminResponseDto> getAdvertisingsByCampaign(Long campaignId) {
return advertisingRepository.findAllByCampaignIdOrderByCreatedAtDesc(campaignId)
.stream()
.map(this::mapToAdminDto)
.toList();
}
public AdvertisingAdminResponseDto updateAdvertising(Long advertisingId, AdvertisingUpdateRequestDto request) {
Advertising advertising = advertisingRepository.findById(advertisingId)
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
advertising.setTargetUrl(request.targetUrl());
advertising.setWeight(request.weight());
Advertising saved = advertisingRepository.save(advertising);
log.info("Advertising {} updated", saved.getId());
return mapToAdminDto(saved);
}
private AdvertisingAdminResponseDto mapToAdminDto(Advertising advertising) {
return new AdvertisingAdminResponseDto(
advertising.getId(),
advertising.getCampaign().getId(),
advertising.getType(),
advertising.getTargetUrl(),
advertising.getWeight(),
advertising.getTranscodingStatus());
}
}

View File

@@ -0,0 +1,54 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.entity.advertising.Advertising;
import com.krylov.refound.entity.advertising.Click;
import com.krylov.refound.repository.advertising.AdvertisingRepository;
import com.krylov.refound.repository.advertising.ClickRepository;
import com.krylov.refound.service.UserService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingClickService {
private final UserService userService;
private final ClickRepository clickRepository;
private final AdvertisingRepository advertisingRepository;
@Transactional
public void recordClick(Long advertisingId, Authentication authentication, String sessionId) {
Long userId = extractUserId(authentication);
try {
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
Click click = new Click();
click.setAdvertising(advertising);
click.setUserId(userId);
click.setSessionId(sessionId);
click.setAdvertising(advertising);
Click save = clickRepository.save(click);
log.info("click by advertising {}", save.getId());
} catch (EntityNotFoundException e) {
log.warn("Click skipped: advertisingId={} no longer exists", advertisingId);
}
}
private Long extractUserId(Authentication authentication) {
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
return null;
}
String login = authentication.getName();
log.info("extractUserId by login {}", login);
return userService.getUserIdByLogin(login);
}
}

View File

@@ -0,0 +1,68 @@
package com.krylov.refound.service.advertising;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
@Service
@RequiredArgsConstructor
public class AdvertisingFrequencyService {
private static final Duration FREQ_TTL = Duration.ofHours(24);
private static final Duration SESSION_COOLDOWN = Duration.ofSeconds(30);
private final StringRedisTemplate redisTemplate;
/**
* Проверяет и атомарно увеличивает счётчик показов объявления пользователю
* (или анонимной сессии, если userId отсутствует).
* Возвращает true, если показ укладывается в dailyCap.
*/
public boolean tryRegisterImpression(Long userId, String sessionId, Long adId, int dailyCap) {
String key = freqKey(userId, sessionId, adId);
Long count = redisTemplate.opsForValue().increment(key);
if (count == null) {
// Redis недоступен — не блокируем показ, решение остаётся за вызывающим кодом
return true;
}
if (count == 1L) {
redisTemplate.expire(key, FREQ_TTL);
}
return count <= dailyCap;
}
/**
* Откатывает счётчик, если после инкремента показ всё же не состоялся
* (например, объявление не прошло другие проверки в AdSelectionService).
*/
public void rollback(Long userId, String sessionId, Long adId) {
String key = freqKey(userId, sessionId, adId);
Long count = redisTemplate.opsForValue().decrement(key);
if (count != null && count <= 0) {
redisTemplate.delete(key);
}
}
/**
* Минимальный интервал между показами любой рекламы в рамках одной сессии,
* независимо от дневного капа конкретного объявления.
*/
public boolean isSessionCooldownPassed(String sessionId) {
String key = sessionCooldownKey(sessionId);
Boolean wasAbsent = redisTemplate.opsForValue()
.setIfAbsent(key, Instant.now().toString(), SESSION_COOLDOWN);
return Boolean.TRUE.equals(wasAbsent);
}
private String freqKey(Long userId, String sessionId, Long adId) {
String subject = userId != null ? "u" + userId : "s" + sessionId;
return "ad:freq:%s:%d".formatted(subject, adId);
}
private String sessionCooldownKey(String sessionId) {
return "ad:session:%s:cooldown".formatted(sessionId);
}
}

View File

@@ -0,0 +1,52 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.entity.advertising.Advertising;
import com.krylov.refound.entity.advertising.Impression;
import com.krylov.refound.repository.advertising.AdvertisingRepository;
import com.krylov.refound.repository.advertising.ImpressionRepository;
import com.krylov.refound.service.UserService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingImpressionService {
private final UserService userService;
private final ImpressionRepository impressionRepository;
private final AdvertisingRepository advertisingRepository;
@Transactional
public void recordImpression(Long advertisingId, Authentication authentication, String sessionId) {
Long userId = extractUserId(authentication);
try {
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
Impression impression = new Impression();
impression.setAdvertising(advertising);
impression.setUserId(userId);
impression.setSessionId(sessionId);
Impression save = impressionRepository.save(impression);
log.info("impression is {}", save);
} catch (EntityNotFoundException e) {
// advertisingId мог устареть (кампания удалена между показом и трекингом) —
// не роняем запрос трекинга из-за гонки данных
log.warn("Impression skipped: advertisingId={} no longer exists", advertisingId);
}
}
private Long extractUserId(Authentication authentication) {
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
return null;
}
String login = authentication.getName();
log.info("extractUserId by login {}", login);
return userService.getUserIdByLogin(login);
}
}

View File

@@ -0,0 +1,186 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingMediaService {
private final S3Presigner s3Presigner;
private final S3Client s3Client;
@Value("${minio.ads-bucket}")
private String adsBucket;
private static final long MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10 MB
private static final Set<String> ALLOWED_IMAGE_TYPES = Set.of("image/jpeg", "image/png", "image/webp");
/**
* Загружает изображение рекламного объявления в ads-media.
* Валидация полностью повторяет FileStorageService (10MB, jpeg/png/webp) —
* но целевой бакет другой, поэтому логика не переиспользуется напрямую.
*/
public String uploadImage(MultipartFile file) {
validateImage(file);
String extension = extractExtension(file.getOriginalFilename());
String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), extension);
try {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(adsBucket)
.key(mediaKey)
.contentType(file.getContentType())
.build();
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
log.info("Ad image uploaded: {}", mediaKey);
return mediaKey;
} catch (IOException e) {
log.error("Failed to read image file for upload: {}", e.getMessage(), e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при обработке файла.", HttpStatus.INTERNAL_SERVER_ERROR);
} catch (S3Exception | SdkClientException e) {
log.error("Failed to upload ad image to S3/MinIO: {}", e.getMessage(), e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при загрузке файла.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private void validateImage(MultipartFile file) {
if (file.isEmpty()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Файл не может быть пустым.", HttpStatus.BAD_REQUEST);
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || originalFilename.isBlank()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Имя файла отсутствует.", HttpStatus.BAD_REQUEST);
}
if (file.getSize() > MAX_IMAGE_SIZE) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Файл слишком большой (максимум 10 МБ).", HttpStatus.BAD_REQUEST);
}
String contentType = file.getContentType();
if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST);
}
}
private String extractExtension(String originalFilename) {
if (originalFilename != null && originalFilename.contains(".")) {
return originalFilename.substring(originalFilename.lastIndexOf("."));
}
return "";
}
/**
* URL, по которому фронтенд сможет получить медиа на любом устройстве.
* Presigned URL непригоден: он подписан под host MinIO (localhost:9010),
* который на клиенте из другой сети не резолвится (а правка host ломает
* подпись). Поэтому отдаём относительный путь на прокси-эндпоинт бэкенда
* (тот же подход, что и для картинок постов через /api/v1/files).
*/
public String getMediaUrl(String mediaKey) {
return "/api/v1/ads-media/" + mediaKey;
}
/**
* Отдаёт медиа рекламы из ads-media потоком/байтами через бэкенд —
* без presigned URL, доступно с любого устройства.
*/
public ResponseEntity<byte[]> downloadMedia(String mediaKey) {
try {
HeadObjectResponse head = s3Client.headObject(
HeadObjectRequest.builder().bucket(adsBucket).key(mediaKey).build());
String contentType = head.contentType() != null
? head.contentType()
: MediaType.APPLICATION_OCTET_STREAM_VALUE;
byte[] content = s3Client.getObjectAsBytes(
GetObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()).asByteArray();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline");
log.info("downloadMedia: served mediaKey={}, contentType={}, {} bytes", mediaKey, contentType, content.length);
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.parseMediaType(contentType))
.body(content);
} catch (NoSuchKeyException e) {
log.warn("Ad media not found: {}", mediaKey);
throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND);
} catch (S3Exception | SdkClientException e) {
log.error("Failed to download ad media mediaKey={}", mediaKey, e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Presigned URL для прямой загрузки исходника с фронтенда в обход бэкенда.
* TTL длиннее, чем у GET — загрузка большого видео может занять время
* на медленном интернете у рекламодателя.
*/
public String getPresignedUploadUrl(String mediaKey, String contentType) {
log.info("PresignedUploadUrl {}", mediaKey);
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(adsBucket)
.key(mediaKey)
.contentType(contentType)
.build();
PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(30))
.putObjectRequest(putObjectRequest)
.build();
return s3Presigner.presignPutObject(presignRequest).url().toString();
}
/**
* Скачивает исходник из MinIO во временный поток для последующего
* транскодинга — вызывается уже на бэкенде, после подтверждения загрузки.
*/
public InputStream downloadSource(String mediaKey) {
return s3Client.getObject(GetObjectRequest.builder()
.bucket(adsBucket)
.key(mediaKey)
.build());
}
public void deleteObject(String mediaKey) {
try {
s3Client.deleteObject(builder -> builder.bucket(adsBucket).key(mediaKey));
} catch (Exception e) {
log.warn("Failed to delete object mediaKey={}", mediaKey, e);
}
}
}

View File

@@ -0,0 +1,97 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
import com.krylov.refound.entity.advertising.Advertising;
import com.krylov.refound.repository.advertising.AdvertisingRepository;
import com.krylov.refound.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingSelectionService {
private final UserService userService;
private final AdvertisingRepository adRepository;
private final AdvertisingFrequencyService frequencyService;
/**
* Выбирает одно объявление для показа пользователю/сессии с учётом
* частотного капа и весов кампаний. Перебирает кандидатов в случайном
* порядке, взвешенном по weight, пока не найдёт первое разрешённое.
*/
public Optional<SelectedAdvertisingDto> selectAdvertising(Authentication authentication, String sessionId, HttpServletRequest request) {
Long userId = extractUserId(authentication);
String resolvedSessionId = sessionId != null ? sessionId : request.getSession(true).getId();
if (!frequencyService.isSessionCooldownPassed(resolvedSessionId)) {
log.warn("isSessionCooldownPassed by {} resolvedSessionId is empty", resolvedSessionId);
return Optional.empty();
}
List<Advertising> eligible = adRepository.findEligibleAds(LocalDateTime.now());
if (eligible.isEmpty()) {
log.warn("findEligibleAds is empty");
return Optional.empty();
}
for (Advertising candidate : weightedOrder(eligible)) {
int dailyCap = candidate.getCampaign().getDailyImpressionCap();
boolean allowed = frequencyService.tryRegisterImpression(userId, resolvedSessionId, candidate.getId(), dailyCap);
if (allowed) {
log.info("advertising candidate {}", candidate);
return Optional.of(toDto(candidate));
}
log.info("rollback dailyCap for candidate {}", candidate.getId());
frequencyService.rollback(userId, resolvedSessionId, candidate.getId());
}
log.info("No ad passed frequency cap for userId={}, sessionId={}", userId, resolvedSessionId);
return Optional.empty();
}
private Long extractUserId(Authentication authentication) {
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
return null;
}
String login = authentication.getName();
log.info("extractUserId by login {}", login);
return userService.getUserIdByLogin(login);
}
/**
* Взвешенная выборка без повторов (алгоритм Ефраимидиса-Спиракиса):
* каждому объявлению присваивается ключ u^(1/weight), сортировка по
* убыванию ключа даёт порядок, эквивалентный последовательному
* взвешенному семплированию без возврата.
*/
private List<Advertising> weightedOrder(List<Advertising> ads) {
ThreadLocalRandom random = ThreadLocalRandom.current();
return ads.stream()
.sorted(Comparator.comparingDouble(
(Advertising ad) -> Math.pow(random.nextDouble(), 1.0 / Math.max(ad.getWeight(), 1)))
.reversed())
.toList();
}
private SelectedAdvertisingDto toDto(Advertising ad) {
return new SelectedAdvertisingDto(
ad.getId(),
ad.getType().name(),
ad.getMediaKey(),
ad.getTargetUrl());
}
}

View File

@@ -0,0 +1,39 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.TranscodingStatusDto;
import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.repository.advertising.AdvertisingRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class AdvertisingStatusService {
private final AdvertisingRepository advertisingRepository;
private final SimpMessagingTemplate messagingTemplate;
@Transactional
public void markReady(Long advertisingId, String mediaKey) {
advertisingRepository.findById(advertisingId).ifPresent(ad -> {
ad.setMediaKey(mediaKey);
ad.setTranscodingStatus(TranscodingStatus.READY);
});
notifyStatusChange(advertisingId, TranscodingStatus.READY);
}
@Transactional
public void markFailed(Long advertisingId) {
advertisingRepository.findById(advertisingId).ifPresent(ad ->
ad.setTranscodingStatus(TranscodingStatus.FAILED));
notifyStatusChange(advertisingId, TranscodingStatus.FAILED);
}
private void notifyStatusChange(Long advertisingId, TranscodingStatus status) {
messagingTemplate.convertAndSend(
"/topic/ads/%d/status".formatted(advertisingId),
new TranscodingStatusDto(advertisingId, status));
}
}

View File

@@ -0,0 +1,27 @@
package com.krylov.refound.service.advertising;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class AdvertisingTranscodingService {
private final VideoTranscoderService videoTranscoderService;
private final AdvertisingStatusService statusService;
@Async("ffmpegExecutor")
public void transcodeFromStorage(Long advertisingId, String sourceKey) {
try {
String mediaKey = videoTranscoderService.transcode(sourceKey, "videos");
statusService.markReady(advertisingId, mediaKey);
log.info("Transcoding finished for advertisingId={}, mediaKey={}", advertisingId, mediaKey);
} catch (Exception e) {
log.error("Transcoding failed for advertisingId={}", advertisingId, e);
statusService.markFailed(advertisingId);
}
}
}

View File

@@ -0,0 +1,114 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.CampaignCreateRequestDto;
import com.krylov.refound.dto.advertising.CampaignResponseDto;
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
import com.krylov.refound.dto.advertising.CampaignUpdateRequestDto;
import com.krylov.refound.entity.advertising.Campaign;
import com.krylov.refound.enums.advertising.CampaignStatus;
import com.krylov.refound.exception.InvalidCampaignStatusTransitionException;
import com.krylov.refound.repository.advertising.CampaignRepository;
import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class CampaignService {
private final CampaignRepository campaignRepository;
public List<CampaignResponseDto> getCampaign() {
return campaignRepository.findAllByOrderByCreatedAtDesc()
.stream()
.map(this::toDto)
.toList();
}
public Optional<CampaignResponseDto> getCampaignById(Long campaignId) {
return campaignRepository.findById(campaignId).map(this::toDto);
}
public CampaignResponseDto createCampaign(CampaignCreateRequestDto request){
Campaign campaign = new Campaign();
campaign.setName(request.name());
campaign.setStatus(CampaignStatus.DRAFT);
campaign.setStartDate(request.startDate());
campaign.setEndDate(request.endDate());
campaign.setDailyImpressionCap(request.dailyImpressionCap());
campaignRepository.save(campaign);
log.info("campaign {} created", campaign);
return toDto(campaign);
}
@Transactional
public CampaignResponseDto updateCampaign(Long campaignId, CampaignUpdateRequestDto request) {
Campaign campaign = campaignRepository.findById(campaignId)
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + campaignId));
if (!request.startDate().isBefore(request.endDate())) {
throw new IllegalArgumentException("startDate must be before endDate");
}
if (request.dailyImpressionCap() <= 0) {
throw new IllegalArgumentException("dailyImpressionCap must be positive");
}
campaign.setName(request.name());
campaign.setStartDate(request.startDate());
campaign.setEndDate(request.endDate());
campaign.setDailyImpressionCap(request.dailyImpressionCap());
log.info("campaign {} updated", campaignId);
return toDto(campaign);
}
@Transactional
public CampaignResponseDto updateCampaignStatus(Long campaignId, CampaignStatusUpdateRequestDto request) {
Campaign campaign = campaignRepository.findById(campaignId)
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + campaignId));
if (!isValidTransition(campaign.getStatus(), request.status())) {
throw new InvalidCampaignStatusTransitionException(
"Invalid status transition: "
+ campaign.getStatus()
+ " -> "
+ request.status()
);
}
campaignRepository.updateStatus(campaignId, request.status());
return toDto(campaign);
}
/**
* Разрешённые переходы статуса кампании. Не даёт, например, воскресить
* FINISHED обратно в ACTIVE или перепрыгнуть из DRAFT сразу в FINISHED.
*/
private boolean isValidTransition(CampaignStatus from, CampaignStatus to) {
if (from == to) {
return false;
}
return switch (from) {
case DRAFT -> to == CampaignStatus.ACTIVE;
case ACTIVE -> to == CampaignStatus.PAUSED || to == CampaignStatus.FINISHED;
case PAUSED -> to == CampaignStatus.ACTIVE || to == CampaignStatus.FINISHED;
case FINISHED -> false;
};
}
private CampaignResponseDto toDto(Campaign campaign) {
return new CampaignResponseDto(
campaign.getId(),
campaign.getName(),
campaign.getStatus(),
campaign.getStartDate(),
campaign.getEndDate(),
campaign.getDailyImpressionCap());
}
}

View File

@@ -0,0 +1,37 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class FullscreenAdStatusService {
private final FullscreenAdvertisingRepository repository;
private final SimpMessagingTemplate messagingTemplate;
@Transactional
public void markReady(Long id, String mediaKey) {
repository.findById(id).ifPresent(ad -> {
ad.setMediaKey(mediaKey);
ad.setTranscodingStatus(TranscodingStatus.READY);
});
notifyStatusChange(id, TranscodingStatus.READY);
}
@Transactional
public void markFailed(Long id) {
repository.findById(id).ifPresent(ad -> ad.setTranscodingStatus(TranscodingStatus.FAILED));
notifyStatusChange(id, TranscodingStatus.FAILED);
}
private void notifyStatusChange(Long id, TranscodingStatus status) {
messagingTemplate.convertAndSend(
"/topic/fullscreen-ads/%d/status".formatted(id),
new com.krylov.refound.dto.advertising.TranscodingStatusDto(id, status));
}
}

View File

@@ -0,0 +1,27 @@
package com.krylov.refound.service.advertising;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class FullscreenAdTranscodingService {
private final VideoTranscoderService videoTranscoderService;
private final FullscreenAdStatusService statusService;
@Async("ffmpegExecutor")
public void transcodeFromStorage(Long fullscreenAdId, String sourceKey) {
try {
String mediaKey = videoTranscoderService.transcode(sourceKey, "fullscreen");
statusService.markReady(fullscreenAdId, mediaKey);
log.info("Fullscreen ad transcoding finished for id={}, mediaKey={}", fullscreenAdId, mediaKey);
} catch (Exception e) {
log.error("Fullscreen ad transcoding failed for id={}", fullscreenAdId, e);
statusService.markFailed(fullscreenAdId);
}
}
}

View File

@@ -0,0 +1,19 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.FullscreenAdVideoUploadConfirmedEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
@Component
@RequiredArgsConstructor
public class FullscreenAdVideoUploadEventListener {
private final FullscreenAdTranscodingService transcodingService;
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onVideoUploadConfirmed(FullscreenAdVideoUploadConfirmedEvent event) {
transcodingService.transcodeFromStorage(event.fullscreenAdId(), event.sourceKey());
}
}

View File

@@ -0,0 +1,119 @@
package com.krylov.refound.service.advertising;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Чистая логика транскодинга видео: скачать исходник → прогнать через
* ffmpeg → залить результат. Не знает ничего про Advertising, кампании
* или статусы конкретных сущностей — вызывающий код сам решает, что
* делать с результатом (mediaKey) или с исключением при неудаче.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class VideoTranscoderService {
private final AdvertisingMediaService mediaService;
private final S3Client s3Client;
@Value("${minio.ads-bucket}")
private String adsBucket;
@Value("${ffmpeg.binary-path:ffmpeg}")
private String ffmpegPath;
/**
* @return ключ (mediaKey) готового видео в MinIO
*/
public String transcode(String sourceKey, String outputPrefix) throws IOException, InterruptedException {
Path sourcePath = null;
Path outputPath = null;
try {
sourcePath = downloadToTemp(sourceKey);
outputPath = Files.createTempFile("transcoded-", ".mp4");
boolean success = runFfmpeg(sourcePath, outputPath);
if (!success) {
throw new IOException("ffmpeg exited with non-zero status or timed out");
}
String mediaKey = "%s/%s.mp4".formatted(outputPrefix, UUID.randomUUID());
uploadToStorage(outputPath, mediaKey);
return mediaKey;
} finally {
if (sourcePath != null) cleanup(sourcePath);
if (outputPath != null) cleanup(outputPath);
mediaService.deleteObject(sourceKey);
}
}
private Path downloadToTemp(String sourceKey) throws IOException {
Path tempFile = Files.createTempFile("source-", extractExtension(sourceKey));
try (InputStream in = mediaService.downloadSource(sourceKey)) {
Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
}
return tempFile;
}
private String extractExtension(String key) {
int dot = key.lastIndexOf('.');
return dot >= 0 ? key.substring(dot) : ".tmp";
}
private boolean runFfmpeg(Path input, Path output) throws IOException, InterruptedException {
List<String> command = List.of(
ffmpegPath, "-y", "-i", input.toString(),
"-vf", "scale=-2:720",
"-c:v", "libx264", "-preset", "medium",
"-b:v", "1500k", "-maxrate", "2000k", "-bufsize", "3000k",
"-c:a", "aac", "-b:a", "128k",
"-movflags", "+faststart",
output.toString()
);
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
try (var reader = process.inputReader()) {
reader.lines().forEach(line -> log.debug("[ffmpeg] {}", line));
}
boolean finished = process.waitFor(5, TimeUnit.MINUTES);
if (!finished) {
process.destroyForcibly();
log.error("FFmpeg timed out, killed process");
return false;
}
return process.exitValue() == 0;
}
private void uploadToStorage(Path filePath, String mediaKey) throws IOException {
s3Client.putObject(
PutObjectRequest.builder().bucket(adsBucket).key(mediaKey).contentType("video/mp4").build(),
RequestBody.fromFile(filePath));
}
private void cleanup(Path path) {
try {
Files.deleteIfExists(path);
} catch (IOException e) {
log.warn("Failed to delete temp file: {}", path, e);
}
}
}

View File

@@ -0,0 +1,19 @@
package com.krylov.refound.service.advertising;
import com.krylov.refound.dto.advertising.VideoUploadConfirmedEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
@Component
@RequiredArgsConstructor
public class VideoUploadEventListener {
private final AdvertisingTranscodingService transcodingService;
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onVideoUploadConfirmed(VideoUploadConfirmedEvent event) {
transcodingService.transcodeFromStorage(event.advertisingId(), event.sourceKey());
}
}