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>
120 lines
4.7 KiB
Java
120 lines
4.7 KiB
Java
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 com.krylov.refound.util.AdTargetUrl;
|
||
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;
|
||
private final AdvertisingSelectionService selectionService;
|
||
|
||
public Advertising createAdvertising(Campaign campaign, AdvertisingCreateRequestDto request){
|
||
Advertising advertising = new Advertising();
|
||
advertising.setCampaign(campaign);
|
||
advertising.setType(request.type());
|
||
advertising.setTargetUrl(AdTargetUrl.requireValid(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 sourcePrefix(advertisingId) + UUID.randomUUID() + extensionFor;
|
||
}
|
||
|
||
/**
|
||
* sourceKey в confirm-upload приходит от клиента, а транскодер после работы
|
||
* удаляет исходник. Без проверки можно было подставить ключ готового ролика
|
||
* другого объявления — и он бы удалился.
|
||
*/
|
||
public boolean isOwnSourceKey(Long advertisingId, String sourceKey) {
|
||
return sourceKey != null && sourceKey.startsWith(sourcePrefix(advertisingId)) && !sourceKey.contains("..");
|
||
}
|
||
|
||
private static String sourcePrefix(Long advertisingId) {
|
||
return "sources/%d/".formatted(advertisingId);
|
||
}
|
||
|
||
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);
|
||
selectionService.invalidateCache();
|
||
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(AdTargetUrl.requireValid(request.targetUrl()));
|
||
advertising.setWeight(request.weight());
|
||
Advertising saved = advertisingRepository.save(advertising);
|
||
log.info("Advertising {} updated", saved.getId());
|
||
selectionService.invalidateCache();
|
||
return mapToAdminDto(saved);
|
||
}
|
||
|
||
private AdvertisingAdminResponseDto mapToAdminDto(Advertising advertising) {
|
||
return new AdvertisingAdminResponseDto(
|
||
advertising.getId(),
|
||
advertising.getCampaign().getId(),
|
||
advertising.getType(),
|
||
advertising.getTargetUrl(),
|
||
advertising.getWeight(),
|
||
advertising.getTranscodingStatus());
|
||
}
|
||
|
||
|
||
}
|