Files
nahodka-back/src/main/java/com/krylov/refound/controller/advertising/FullscreenAdAdminController.java
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

161 lines
6.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 com.krylov.refound.util.AdTargetUrl;
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();
// Ссылка у полноэкранного ролика необязательна, но если есть — только http(s)
ad.setTargetUrl(request.targetUrl() == null || request.targetUrl().isBlank()
? null : AdTargetUrl.requireValid(request.targetUrl()));
FullscreenAdvertising saved = repository.save(ad);
return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved));
}
@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 = sourcePrefix(id) + UUID.randomUUID() + extensionFor(request.contentType());
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
}
@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));
// Транскодер удаляет исходник после работы — чужой ключ сюда подставлять нельзя
String sourceKey = request.sourceKey();
if (sourceKey == null || !sourceKey.startsWith(sourcePrefix(id)) || sourceKey.contains("..")) {
log.warn("confirmUpload: foreign sourceKey {} for fullscreen ad {}", sourceKey, id);
return ResponseEntity.badRequest().build();
}
ad.setTranscodingStatus(TranscodingStatus.PROCESSING);
repository.save(ad);
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)
.filter(current -> !current.getId().equals(target.getId()))
.ifPresent(current -> {
current.setStatus(FullscreenAdStatus.INACTIVE);
// Hibernate не гарантирует порядок UPDATE при flush: если target обновится
// первым, две строки ACTIVE нарушат uq_fullscreen_ad_single_active
repository.saveAndFlush(current);
});
target.setStatus(FullscreenAdStatus.ACTIVE);
return ResponseEntity.ok(toDto(target));
}
@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 static String sourcePrefix(Long id) {
return "fullscreen-sources/%d/".formatted(id);
}
private boolean isAllowedContentType(String contentType) {
return contentType != null && (contentType.equals("video/mp4")
|| contentType.equals("video/quicktime") || contentType.equals("video/webm"));
}
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());
}
}