- 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>
166 lines
8.4 KiB
Java
166 lines
8.4 KiB
Java
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));
|
|
if (!advertisingAdminService.isOwnSourceKey(advertisingId, request.sourceKey())) {
|
|
log.warn("confirmUpload: foreign sourceKey {} for advertisingId {}", request.sourceKey(), advertisingId);
|
|
return ResponseEntity.badRequest().build();
|
|
}
|
|
|
|
advertisingAdminService.updateTranscodingStatus(advertising.getId());
|
|
eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey()));
|
|
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();
|
|
}
|
|
// Проверка до создания: раньше объявление создавалось и только потом отвечали 400
|
|
if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) {
|
|
log.warn("advertising image has bad mediaKey() or mediaKey isBlank");
|
|
return ResponseEntity.badRequest().build();
|
|
}
|
|
|
|
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
|
|
|
AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising);
|
|
return ResponseEntity.status(HttpStatus.CREATED).body(adminDto);
|
|
}
|
|
|
|
@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));
|
|
}
|
|
|
|
}
|