added advertising
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
package com.krylov.refound.controller.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.AdImageUploadResponseDto;
|
||||
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.ConfirmUploadRequestDto;
|
||||
import com.krylov.refound.dto.advertising.PresignUploadRequestDto;
|
||||
import com.krylov.refound.dto.advertising.PresignUploadResponseDto;
|
||||
import com.krylov.refound.dto.advertising.TranscodingStatusDto;
|
||||
import com.krylov.refound.dto.advertising.VideoUploadConfirmedEvent;
|
||||
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.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.CampaignRepository;
|
||||
import com.krylov.refound.service.advertising.AdvertisingAdminService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
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.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/ads")
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingAdminController {
|
||||
|
||||
private static final int PRESIGN_URL_EXPIRY_MINUTES = 30;
|
||||
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final AdvertisingMediaService mediaService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final AdvertisingAdminService advertisingAdminService;
|
||||
|
||||
/**
|
||||
* Шаг 1: фронтенд запрашивает ссылку для прямой загрузки в MinIO.
|
||||
* Файл ещё не передан — только резервируем ключ и отдаём подписанный URL.
|
||||
*/
|
||||
@PostMapping("/{advertisingId}/video/presign-upload")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<PresignUploadResponseDto> presignUpload(@PathVariable Long advertisingId, @RequestBody PresignUploadRequestDto request) {
|
||||
log.info("presignUpload advertisingId {}", advertisingId);
|
||||
if (!advertisingRepository.existsById(advertisingId)) {
|
||||
log.warn("Advertising not found: {}", advertisingId);
|
||||
throw new EntityNotFoundException("Advertising not found: " + advertisingId);
|
||||
}
|
||||
boolean allowedContentType = advertisingAdminService.isAllowedContentType(request.contentType());
|
||||
if (!allowedContentType) {
|
||||
log.warn("allowedContentType for advertisingId {}", advertisingId);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String sourceKey = advertisingAdminService.getSourceKey(advertisingId, request);
|
||||
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
|
||||
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
|
||||
}
|
||||
|
||||
/**
|
||||
* Шаг 2: фронтенд сам сделал PUT на presigned URL, теперь сообщает,
|
||||
* что файл загружен — только после этого бэкенд узнаёт про файл и
|
||||
* запускает транскодинг.
|
||||
*/
|
||||
@PostMapping("/{advertisingId}/video/confirm-upload")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> confirmUpload(@PathVariable Long advertisingId, @RequestBody ConfirmUploadRequestDto request) {
|
||||
log.info("confirmUpload for advertisingId {}", advertisingId);
|
||||
Advertising advertising = advertisingRepository.findById(advertisingId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
|
||||
|
||||
advertisingAdminService.updateTranscodingStatus(advertising.getId());
|
||||
eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey()));
|
||||
return ResponseEntity.status(HttpStatus.ACCEPTED).build();
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<List<AdvertisingAdminResponseDto>> getAdvertisingsByCampaign(@RequestParam Long campaignId) {
|
||||
log.info("getAdvertisingsByCampaign {}", campaignId);
|
||||
List<AdvertisingAdminResponseDto> advertisings = advertisingAdminService.getAdvertisingsByCampaign(campaignId);
|
||||
return ResponseEntity.ok(advertisings);
|
||||
}
|
||||
|
||||
@GetMapping("/{advertisingId}/status")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<TranscodingStatusDto> getStatus(@PathVariable Long advertisingId) {
|
||||
log.info("getStatus for advertising {}", advertisingId);
|
||||
Advertising advertising = advertisingRepository.findById(advertisingId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
|
||||
|
||||
return ResponseEntity.ok(new TranscodingStatusDto(advertising.getId(), advertising.getTranscodingStatus()));
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/v1/admin/ads/{advertisingId} — обновление полей объявления
|
||||
* (targetUrl, weight). Тип/медиа/статус транскодинга не меняются.
|
||||
* Ответ 200: AdvertisingAdminResponseDto. 400 — невалидные данные.
|
||||
*/
|
||||
@PutMapping("/{advertisingId}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<AdvertisingAdminResponseDto> updateAdvertising(
|
||||
@PathVariable Long advertisingId,
|
||||
@Valid @RequestBody AdvertisingUpdateRequestDto request) {
|
||||
log.info("updateAdvertising {}", advertisingId);
|
||||
if (request.weight() <= 0) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
AdvertisingAdminResponseDto dto = advertisingAdminService.updateAdvertising(advertisingId, request);
|
||||
return ResponseEntity.ok(dto);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<AdvertisingAdminResponseDto> createAdvertising(@Valid @RequestBody AdvertisingCreateRequestDto request) {
|
||||
log.info("createAdvertising {}", request);
|
||||
Campaign campaign = campaignRepository.findById(request.campaignId())
|
||||
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + request.campaignId()));
|
||||
|
||||
if (request.weight() <= 0) {
|
||||
log.warn("weight AdvertisingCreateRequestDto {} <= 0", request);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
||||
if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) {
|
||||
log.warn("advertising image has bad mediaKey() or mediaKey isBlank");
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(adminDto);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<AdImageUploadResponseDto> uploadAdImage(@RequestParam("file") MultipartFile file) {
|
||||
String mediaKey = mediaService.uploadImage(file);
|
||||
return ResponseEntity.ok(new AdImageUploadResponseDto(mediaKey));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.krylov.refound.controller.advertising;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.dto.advertising.AdvertisingResponseDto;
|
||||
import com.krylov.refound.dto.advertising.ClickRequestDto;
|
||||
import com.krylov.refound.dto.advertising.ImpressionRequestDto;
|
||||
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
|
||||
import com.krylov.refound.service.advertising.AdvertisingClickService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingImpressionService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingSelectionService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingController {
|
||||
|
||||
private final AdvertisingSelectionService advertisingSelectionService;
|
||||
private final AdvertisingMediaService advertisingMediaService;
|
||||
private final AdvertisingImpressionService advertisingImpressionService;
|
||||
private final AdvertisingClickService advertisingClickService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@GetMapping("/api/ads/next")
|
||||
public ResponseEntity<AdvertisingResponseDto> getNextAdvertising(Authentication authentication, @RequestHeader(value = "X-Session-Id", required = false) String sessionId, HttpServletRequest request) {
|
||||
log.info("getNextAdvertising");
|
||||
Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request);
|
||||
if (selected.isEmpty()) {
|
||||
log.warn("failed get advertising");
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
SelectedAdvertisingDto advertising = selected.get();
|
||||
String mediaUrl = advertisingMediaService.getMediaUrl(advertising.mediaKey());
|
||||
|
||||
return ResponseEntity.ok(new AdvertisingResponseDto(advertising.advertisingId(), advertising.type(), mediaUrl, advertising.targetUrl()));
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/impression")
|
||||
public ResponseEntity<Void> registerImpression(@RequestBody String body, Authentication authentication) throws JsonProcessingException {
|
||||
log.info("registerImpression for body {}", body);
|
||||
ImpressionRequestDto request = objectMapper.readValue(body, ImpressionRequestDto.class);
|
||||
advertisingImpressionService.recordImpression(request.advertisingId(), authentication, request.sessionId());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/click")
|
||||
public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) {
|
||||
log.info("registerClick");
|
||||
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.krylov.refound.controller.advertising;
|
||||
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Публичный прокси-эндпоинт медиа рекламы. Ключи объектов содержат слэши
|
||||
* (например "images/<uuid>.jpg"), поэтому используем wildcard {*key},
|
||||
* как в FileStorageController для картинок постов.
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/ads-media")
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingMediaController {
|
||||
|
||||
private final AdvertisingMediaService mediaService;
|
||||
|
||||
@GetMapping("/{*key}")
|
||||
public ResponseEntity<byte[]> getMedia(@PathVariable String key) {
|
||||
String mediaKey = key.startsWith("/") ? key.substring(1) : key;
|
||||
log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey);
|
||||
return mediaService.downloadMedia(mediaKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.krylov.refound.controller.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.service.advertising.CampaignService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/campaigns")
|
||||
@RequiredArgsConstructor
|
||||
public class CampaignAdminController {
|
||||
|
||||
private final CampaignService campaignService;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<List<CampaignResponseDto>> getAllCampaigns() {
|
||||
List<CampaignResponseDto> campaigns = campaignService.getCampaign();
|
||||
return ResponseEntity .ok(campaigns);
|
||||
}
|
||||
|
||||
@GetMapping("/{campaignId}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<CampaignResponseDto> getCampaignById(@PathVariable Long campaignId) {
|
||||
log.info("getCampaignById {}", campaignId);
|
||||
CampaignResponseDto campaign = campaignService.getCampaignById(campaignId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + campaignId));
|
||||
return ResponseEntity.ok(campaign);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<CampaignResponseDto> createCampaign(@Valid @RequestBody CampaignCreateRequestDto request) {
|
||||
log.info("createCampaign {}", request);
|
||||
if (!request.startDate().isBefore(request.endDate())) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
if (request.dailyImpressionCap() <= 0) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
CampaignResponseDto campaign = campaignService.createCampaign(request);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(campaign);
|
||||
}
|
||||
|
||||
@PutMapping("/{campaignId}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<CampaignResponseDto> updateCampaign(@PathVariable Long campaignId, @Valid @RequestBody CampaignUpdateRequestDto request) {
|
||||
log.info("updateCampaign {}", campaignId);
|
||||
CampaignResponseDto campaign = campaignService.updateCampaign(campaignId, request);
|
||||
return ResponseEntity.ok(campaign);
|
||||
}
|
||||
|
||||
@PatchMapping("/{campaignId}/status")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Transactional
|
||||
public ResponseEntity<CampaignResponseDto> updateStatus(@PathVariable Long campaignId, @Valid @RequestBody CampaignStatusUpdateRequestDto request) {
|
||||
log.info("updateStatus company {}", campaignId);
|
||||
CampaignResponseDto campaign = campaignService.updateCampaignStatus(campaignId, request);
|
||||
return ResponseEntity.ok(campaign);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.krylov.refound.controller.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.*;
|
||||
import com.krylov.refound.entity.advertising.FullscreenAdvertising;
|
||||
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/fullscreen-ads")
|
||||
@RequiredArgsConstructor
|
||||
public class FullscreenAdAdminController {
|
||||
|
||||
private static final int PRESIGN_URL_EXPIRY_MINUTES = 30;
|
||||
|
||||
private final FullscreenAdvertisingRepository repository;
|
||||
private final AdvertisingMediaService mediaService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<List<FullscreenAdAdminResponseDto>> getAll() {
|
||||
List<FullscreenAdAdminResponseDto> ads = repository.findAllByOrderByCreatedAtDesc()
|
||||
.stream().map(this::toDto).toList();
|
||||
return ResponseEntity.ok(ads);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<FullscreenAdAdminResponseDto> create(@RequestBody FullscreenAdCreateRequestDto request) {
|
||||
FullscreenAdvertising ad = new FullscreenAdvertising();
|
||||
ad.setTargetUrl(request.targetUrl());
|
||||
FullscreenAdvertising saved = repository.save(ad);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/video/presign-upload")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<PresignUploadResponseDto> presignUpload(
|
||||
@PathVariable Long id, @RequestBody PresignUploadRequestDto request) {
|
||||
|
||||
if (!repository.existsById(id)) {
|
||||
throw new EntityNotFoundException("Fullscreen ad not found: " + id);
|
||||
}
|
||||
if (!isAllowedContentType(request.contentType())) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String sourceKey = "fullscreen-sources/%d/%s%s".formatted(
|
||||
id, UUID.randomUUID(), extensionFor(request.contentType()));
|
||||
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
|
||||
|
||||
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/video/confirm-upload")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Transactional
|
||||
public ResponseEntity<Void> confirmUpload(
|
||||
@PathVariable Long id, @RequestBody ConfirmUploadRequestDto request) {
|
||||
|
||||
FullscreenAdvertising ad = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
|
||||
ad.setTranscodingStatus(TranscodingStatus.PROCESSING);
|
||||
repository.save(ad);
|
||||
|
||||
eventPublisher.publishEvent(new FullscreenAdVideoUploadConfirmedEvent(id, request.sourceKey()));
|
||||
return ResponseEntity.status(HttpStatus.ACCEPTED).build();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/status")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<TranscodingStatusDto> getStatus(@PathVariable Long id) {
|
||||
FullscreenAdvertising ad = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
return ResponseEntity.ok(new TranscodingStatusDto(ad.getId(), ad.getTranscodingStatus()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Делает указанный ролик единственным активным. Все остальные ACTIVE
|
||||
* переводятся в INACTIVE — партиционный уникальный индекс в БД гарантирует
|
||||
* это ограничение даже при гонке параллельных запросов.
|
||||
*/
|
||||
@PatchMapping("/{id}/activate")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Transactional
|
||||
public ResponseEntity<FullscreenAdAdminResponseDto> activate(@PathVariable Long id) {
|
||||
FullscreenAdvertising target = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
|
||||
if (target.getTranscodingStatus() != TranscodingStatus.READY) {
|
||||
return ResponseEntity.unprocessableEntity().build();
|
||||
}
|
||||
|
||||
repository.findByStatus(FullscreenAdStatus.ACTIVE)
|
||||
.ifPresent(current -> current.setStatus(FullscreenAdStatus.INACTIVE));
|
||||
|
||||
target.setStatus(FullscreenAdStatus.ACTIVE);
|
||||
return ResponseEntity.ok(toDto(target));
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}/deactivate")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Transactional
|
||||
public ResponseEntity<FullscreenAdAdminResponseDto> deactivate(@PathVariable Long id) {
|
||||
FullscreenAdvertising ad = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
ad.setStatus(FullscreenAdStatus.INACTIVE);
|
||||
return ResponseEntity.ok(toDto(ad));
|
||||
}
|
||||
|
||||
private boolean isAllowedContentType(String contentType) {
|
||||
return contentType != null && (contentType.equals("video/mp4")
|
||||
|| contentType.equals("video/quicktime") || contentType.equals("video/webm"));
|
||||
}
|
||||
|
||||
private String extensionFor(String contentType) {
|
||||
return switch (contentType) {
|
||||
case "video/quicktime" -> ".mov";
|
||||
case "video/webm" -> ".webm";
|
||||
default -> ".mp4";
|
||||
};
|
||||
}
|
||||
|
||||
private FullscreenAdAdminResponseDto toDto(FullscreenAdvertising ad) {
|
||||
return new FullscreenAdAdminResponseDto(ad.getId(), ad.getTargetUrl(), ad.getStatus(), ad.getTranscodingStatus());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.krylov.refound.controller.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.FullscreenAdPublicResponseDto;
|
||||
import com.krylov.refound.entity.advertising.FullscreenAdvertising;
|
||||
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class FullscreenAdController {
|
||||
|
||||
private final FullscreenAdvertisingRepository repository;
|
||||
private final AdvertisingMediaService mediaService;
|
||||
|
||||
@GetMapping("/api/fullscreen-ad")
|
||||
public ResponseEntity<FullscreenAdPublicResponseDto> getCurrent() {
|
||||
log.info("GET /api/fullscreen-ad called");
|
||||
|
||||
Optional<FullscreenAdvertising> active = repository.findByStatus(FullscreenAdStatus.ACTIVE);
|
||||
if (active.isEmpty()) {
|
||||
// Реклама не настроена (нет ACTIVE) — фронт помечает сессию и больше не запрашивает
|
||||
log.info("fullscreen-ad: no ACTIVE record, returning 204");
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
FullscreenAdvertising ad = active.get();
|
||||
log.info("fullscreen-ad: ACTIVE id={}, transcodeStatus={}, mediaKey={}",
|
||||
ad.getId(), ad.getTranscodingStatus(), ad.getMediaKey());
|
||||
|
||||
if (ad.getMediaKey() == null || ad.getMediaKey().isBlank()) {
|
||||
log.warn("fullscreen-ad: ACTIVE id={} has empty mediaKey, returning 204", ad.getId());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
String mediaUrl = mediaService.getMediaUrl(ad.getMediaKey());
|
||||
log.info("fullscreen-ad: response mediaUrl={}, targetUrl={}", mediaUrl, ad.getTargetUrl());
|
||||
return ResponseEntity.ok(new FullscreenAdPublicResponseDto(mediaUrl, ad.getTargetUrl()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user