Skip to content

Commit

Permalink
Fix : Dc Score spam bug (#29)
Browse files Browse the repository at this point in the history
* Fix : Dc Score spam bug

* fix: display code for codechall and tier fix

* update battleTV for auto-match

* fix: lint

* Revert : iterative recalculation of dcscore

* update: disable registrations and matches after event ends (#30)

* feat: disable registration and matches

* refractor var names

* fix: test errors

* disable oauth registration

* limit no of automatches displayed

* fix: top50 matches in battletv

* fix:make battletv visible

---------

Co-authored-by: Ram-20062003 <[email protected]>
Co-authored-by: Valliammai-SM <[email protected]>
  • Loading branch information
3 people authored Jan 14, 2024
1 parent e2d3dff commit f6b5147
Show file tree
Hide file tree
Showing 16 changed files with 129 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,24 @@ import delta.codecharacter.dtos.CodeTypeDto
import delta.codecharacter.dtos.CreateCodeRevisionRequestDto
import delta.codecharacter.dtos.LanguageDto
import delta.codecharacter.server.code.LanguageEnum
import delta.codecharacter.server.exception.CustomException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.time.Instant
import java.util.UUID

/** Service for code revision. */
@Service
class CodeRevisionService(@Autowired private val codeRevisionRepository: CodeRevisionRepository) {
@Value("\${environment.is-event-open}") private val isEventOpen = true

fun createCodeRevision(userId: UUID, createCodeRevisionRequestDto: CreateCodeRevisionRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}

val (code, message, language) = createCodeRevisionRequestDto
val parentCodeRevision =
codeRevisionRepository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import delta.codecharacter.dtos.UpdateLatestCodeRequestDto
import delta.codecharacter.server.code.Code
import delta.codecharacter.server.code.LanguageEnum
import delta.codecharacter.server.config.DefaultCodeMapConfiguration
import delta.codecharacter.server.exception.CustomException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.time.Instant
import java.util.UUID
Expand All @@ -18,7 +21,7 @@ class LatestCodeService(
@Autowired private val latestCodeRepository: LatestCodeRepository,
@Autowired private val defaultCodeMapConfiguration: DefaultCodeMapConfiguration
) {

@Value("\${environment.is-event-open}") private val isEventOpen = true
fun getLatestCode(userId: UUID, codeType: CodeTypeDto = CodeTypeDto.NORMAL): CodeDto {
val latestCode = HashMap<CodeTypeDto, Code>()
latestCode[codeType] = defaultCodeMapConfiguration.defaultLatestCode
Expand Down Expand Up @@ -49,6 +52,9 @@ class LatestCodeService(
latestCodeRepository.deleteAll()
}
fun updateLatestCode(userId: UUID, updateLatestCodeRequestDto: UpdateLatestCodeRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
val latestCode = HashMap<CodeTypeDto, Code>()
latestCode[updateLatestCodeRequestDto.codeType ?: CodeTypeDto.NORMAL] =
Code(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import delta.codecharacter.dtos.UpdateLatestCodeRequestDto
import delta.codecharacter.server.code.Code
import delta.codecharacter.server.code.LanguageEnum
import delta.codecharacter.server.config.DefaultCodeMapConfiguration
import delta.codecharacter.server.exception.CustomException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.util.UUID

Expand All @@ -15,7 +18,7 @@ class LockedCodeService(
@Autowired private val lockedCodeRepository: LockedCodeRepository,
@Autowired private val defaultCodeMapConfiguration: DefaultCodeMapConfiguration
) {

@Value("\${environment.is-event-open}") private val isEventOpen = true
fun getLockedCode(
userId: UUID,
codeType: CodeTypeDto = CodeTypeDto.NORMAL
Expand Down Expand Up @@ -43,6 +46,9 @@ class LockedCodeService(
}

fun updateLockedCode(userId: UUID, updateLatestCodeRequestDto: UpdateLatestCodeRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
val lockedCode = HashMap<CodeTypeDto, Code>()
lockedCode[updateLatestCodeRequestDto.codeType ?: CodeTypeDto.NORMAL] =
Code(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class DailyChallengeController(
@Secured(value = ["ROLE_USER"])
override fun getDailyChallenge(): ResponseEntity<DailyChallengeGetRequestDto> {
val user = SecurityContextHolder.getContext().authentication.principal as UserEntity
return ResponseEntity.ok(dailyChallengeService.getDailyChallengeByDateForUser(user.id))
return ResponseEntity.ok(dailyChallengeService.getDailyChallengeByDateForUser(user.id, false))
}
override fun getDailyChallengeLeaderBoard(
page: Int?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package delta.codecharacter.server.daily_challenge

import delta.codecharacter.dtos.ChallengeTypeDto
import delta.codecharacter.dtos.DailyChallengeGetRequestDto
import delta.codecharacter.dtos.DailyChallengeObjectDto
import delta.codecharacter.server.daily_challenge.match.DailyChallengeMatchVerdictEnum
import delta.codecharacter.server.exception.CustomException
import delta.codecharacter.server.game.GameEntity
import delta.codecharacter.server.game.GameStatusEnum
import delta.codecharacter.server.logic.daily_challenge_score.DailyChallengeScoreAlgorithm
import delta.codecharacter.server.user.public_user.PublicUserService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
Expand All @@ -24,6 +27,8 @@ class DailyChallengeService(
) {

@Value("\${environment.event-start-date}") private lateinit var startDate: String
@Value("\${environment.is-event-open}") private var isEventOpen = true
private val logger: Logger = LoggerFactory.getLogger(PublicUserService::class.java)

fun findNumberOfDays(): Int {
val givenDateTime = Instant.parse(startDate)
Expand All @@ -33,19 +38,35 @@ class DailyChallengeService(
}

fun getDailyChallengeByDate(): DailyChallengeEntity {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
val currentDailyChallenge =
dailyChallengeRepository.findByDay(findNumberOfDays()).orElseThrow {
throw CustomException(HttpStatus.BAD_REQUEST, "Invalid Request")
}
return currentDailyChallenge
}

fun getDailyChallengeByDateForUser(userId: UUID): DailyChallengeGetRequestDto {
fun getDailyChallengeByDateForUser(
userId: UUID,
isFromMatch: Boolean
): DailyChallengeGetRequestDto {
val user = publicUserService.getPublicUser(userId)
val currentDailyChallenge = getDailyChallengeByDate()
val codeChallString =
"This is a blind code challenge, you have to build a map to counter this attack. Godspeed, commander.\n"
val chall =
if (currentDailyChallenge.challType == ChallengeTypeDto.CODE && !isFromMatch) {
DailyChallengeObjectDto(
cpp = codeChallString, python = codeChallString, java = codeChallString
)
} else {
currentDailyChallenge.chall
}
return DailyChallengeGetRequestDto(
challName = currentDailyChallenge.challName,
chall = currentDailyChallenge.chall,
chall = chall,
challType = currentDailyChallenge.challType,
description = currentDailyChallenge.description,
completionStatus = user.dailyChallengeHistory.containsKey(currentDailyChallenge.day)
Expand All @@ -66,6 +87,10 @@ class DailyChallengeService(
destruction < currentDailyChallenge.toleratedDestruction
)
) {
val user = publicUserService.getPublicUser(userId)
if (user.dailyChallengeHistory.containsKey(currentDailyChallenge.day)) {
return DailyChallengeMatchVerdictEnum.FAILURE
}
val score =
dailyChallengeScoreAlgorithm.getDailyChallengeScore(
playerCoinsUsed = coinsUsed,
Expand All @@ -78,10 +103,6 @@ class DailyChallengeService(
)
dailyChallengeRepository.save(updatedDailyChallenge)
publicUserService.updateDailyChallengeScore(userId, score, currentDailyChallenge)
val user = publicUserService.getPublicUser(userId)
if (user.dailyChallengeHistory.containsKey(currentDailyChallenge.day)) {
return DailyChallengeMatchVerdictEnum.FAILURE
}
return DailyChallengeMatchVerdictEnum.SUCCESS
}
return DailyChallengeMatchVerdictEnum.FAILURE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import delta.codecharacter.dtos.GameMapDto
import delta.codecharacter.dtos.GameMapTypeDto
import delta.codecharacter.dtos.UpdateLatestMapRequestDto
import delta.codecharacter.server.config.DefaultCodeMapConfiguration
import delta.codecharacter.server.exception.CustomException
import delta.codecharacter.server.game_map.GameMap
import delta.codecharacter.server.logic.validation.MapValidator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.time.Instant
import java.util.UUID
Expand All @@ -18,7 +21,7 @@ class LatestMapService(
@Autowired private val defaultCodeMapConfiguration: DefaultCodeMapConfiguration,
@Autowired private val mapValidator: MapValidator,
) {

@Value("\${environment.is-event-open}") private val isEventOpen = true
fun getLatestMap(userId: UUID, mapType: GameMapTypeDto = GameMapTypeDto.NORMAL): GameMapDto {
val defaultMap = HashMap<GameMapTypeDto, GameMap>()
defaultMap[mapType] = defaultCodeMapConfiguration.defaultLatestGameMap
Expand All @@ -45,6 +48,9 @@ class LatestMapService(
}

fun updateLatestMap(userId: UUID, updateLatestMapDto: UpdateLatestMapRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
mapValidator.validateMap(updateLatestMapDto.map)
val latestMap = HashMap<GameMapTypeDto, GameMap>()
latestMap[updateLatestMapDto.mapType ?: GameMapTypeDto.NORMAL] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package delta.codecharacter.server.game_map.locked_map
import delta.codecharacter.dtos.GameMapTypeDto
import delta.codecharacter.dtos.UpdateLatestMapRequestDto
import delta.codecharacter.server.config.DefaultCodeMapConfiguration
import delta.codecharacter.server.exception.CustomException
import delta.codecharacter.server.game_map.GameMap
import delta.codecharacter.server.logic.validation.MapValidator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.util.UUID

Expand All @@ -16,7 +19,7 @@ class LockedMapService(
@Autowired private val defaultCodeMapConfiguration: DefaultCodeMapConfiguration,
@Autowired private val mapValidator: MapValidator,
) {

@Value("\${environment.is-event-open}") private val isEventOpen = true
fun getLockedMap(userId: UUID, mapType: GameMapTypeDto? = GameMapTypeDto.NORMAL): String {
val defaultMap = HashMap<GameMapTypeDto, GameMap>()
defaultMap[mapType ?: GameMapTypeDto.NORMAL] = defaultCodeMapConfiguration.defaultLockedGameMap
Expand All @@ -33,6 +36,9 @@ class LockedMapService(
}

fun updateLockedMap(userId: UUID, updateLatestMapRequestDto: UpdateLatestMapRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
mapValidator.validateMap(updateLatestMapRequestDto.map)
val lockedMap = HashMap<GameMapTypeDto, GameMap>()
lockedMap[updateLatestMapRequestDto.mapType ?: GameMapTypeDto.NORMAL] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import delta.codecharacter.dtos.MapCommitByCommitIdResponseDto
import delta.codecharacter.server.exception.CustomException
import delta.codecharacter.server.logic.validation.MapValidator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.time.Instant
Expand All @@ -18,8 +19,11 @@ class MapRevisionService(
@Autowired private val mapRevisionRepository: MapRevisionRepository,
@Autowired private val mapValidator: MapValidator,
) {

@Value("\${environment.is-event-open}") private val isEventOpen = true
fun createMapRevision(userId: UUID, createMapRevisionRequestDto: CreateMapRevisionRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
val (map, _, message, mapType) = createMapRevisionRequestDto
mapValidator.validateMap(map)
val parentCodeRevision =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import java.util.UUID
@Repository
interface MatchRepository : MongoRepository<MatchEntity, UUID> {
fun findTop10ByOrderByTotalPointsDesc(): List<MatchEntity>
fun findByPlayer1OrderByCreatedAtDesc(player1: PublicUserEntity): List<MatchEntity>
fun findTop50ByPlayer1OrderByCreatedAtDesc(player1: PublicUserEntity): List<MatchEntity>
fun findTop10ByPlayer2AndModeOrderByCreatedAtDesc(
player2: PublicUserEntity,
mode: MatchModeEnum
): List<MatchEntity>
fun findByIdIn(matchIds: List<UUID>): List<MatchEntity>
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.amqp.rabbit.annotation.RabbitListener
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import org.springframework.messaging.simp.SimpMessagingTemplate
Expand Down Expand Up @@ -65,6 +66,7 @@ class MatchService(
@Autowired private val autoMatchRepository: AutoMatchRepository
) {
private var mapper: ObjectMapper = jackson2ObjectMapperBuilder.build()
@Value("\${environment.is-event-open}") private var isEventOpen = true
private val logger: Logger = LoggerFactory.getLogger(MatchService::class.java)

private fun createSelfMatch(userId: UUID, codeRevisionId: UUID?, mapRevisionId: UUID?) {
Expand Down Expand Up @@ -153,8 +155,11 @@ class MatchService(
}

fun createDCMatch(userId: UUID, dailyChallengeMatchRequestDto: DailyChallengeMatchRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
val (_, chall, challType, _, completionStatus) =
dailyChallengeService.getDailyChallengeByDateForUser(userId)
dailyChallengeService.getDailyChallengeByDateForUser(userId, true)
if (completionStatus != null && completionStatus) {
throw CustomException(
HttpStatus.BAD_REQUEST, "You have already completed your daily challenge"
Expand Down Expand Up @@ -193,6 +198,9 @@ class MatchService(
gameService.sendGameRequest(game, code, language, map)
}
fun createMatch(userId: UUID, createMatchRequestDto: CreateMatchRequestDto) {
if (!isEventOpen) {
throw CustomException(HttpStatus.BAD_REQUEST, "Match phase has ended")
}
when (createMatchRequestDto.mode) {
MatchModeDto.SELF -> {
val (_, _, mapRevisionId, codeRevisionId) = createMatchRequestDto
Expand All @@ -211,17 +219,19 @@ class MatchService(
}

fun createAutoMatch() {
val topNUsers = publicUserService.getTopNUsers()
val userIds = topNUsers.map { it.userId }
val usernames = topNUsers.map { it.username }
logger.info("Auto matches started for users: $usernames")
autoMatchRepository.deleteAll()
userIds.forEachIndexed { i, userId ->
run {
for (j in i + 1 until userIds.size) {
val opponentUsername = usernames[j]
val matchId = createDualMatch(userId, opponentUsername, MatchModeEnum.AUTO)
autoMatchRepository.save(AutoMatchEntity(matchId, 0))
if (isEventOpen) {
val topNUsers = publicUserService.getTopNUsers()
val userIds = topNUsers.map { it.userId }
val usernames = topNUsers.map { it.username }
logger.info("Auto matches started for users: $usernames")
autoMatchRepository.deleteAll()
userIds.forEachIndexed { i, userId ->
run {
for (j in i + 1 until userIds.size) {
val opponentUsername = usernames[j]
val matchId = createDualMatch(userId, opponentUsername, MatchModeEnum.AUTO)
autoMatchRepository.save(AutoMatchEntity(matchId, 0))
}
}
}
}
Expand Down Expand Up @@ -306,13 +316,19 @@ class MatchService(

fun getUserMatches(userId: UUID): List<MatchDto> {
val publicUser = publicUserService.getPublicUser(userId)
val matches = matchRepository.findByPlayer1OrderByCreatedAtDesc(publicUser)
val matches = matchRepository.findTop50ByPlayer1OrderByCreatedAtDesc(publicUser)
val autoMatchesPlayer2 =
matchRepository.findTop10ByPlayer2AndModeOrderByCreatedAtDesc(
publicUser, MatchModeEnum.AUTO
)
val dcMatches =
dailyChallengeMatchRepository.findByUserOrderByCreatedAtDesc(publicUser).takeWhile {
Duration.between(it.createdAt, Instant.now()).toHours() < 24 &&
it.verdict != DailyChallengeMatchVerdictEnum.STARTED
}
return mapDailyChallengeMatchEntitiesToDtos(dcMatches) + mapMatchEntitiesToDtos(matches)
return mapDailyChallengeMatchEntitiesToDtos(dcMatches) +
mapMatchEntitiesToDtos(matches) +
mapMatchEntitiesToDtos(autoMatchesPlayer2)
}

@RabbitListener(queues = ["gameStatusUpdateQueue"], ackMode = "AUTO")
Expand Down Expand Up @@ -428,8 +444,8 @@ class MatchService(
newRatings.forEach { (userId, newRating) ->
publicUserService.updateAutoMatchRating(userId = userId, newRating = newRating.rating)
}
logger.info("LeaderBoard Tier Promotion and Demotion started")
publicUserService.promoteTiers()
// logger.info("LeaderBoard Tier Promotion and Demotion started")
// publicUserService.promoteTiers()
}
notificationService.sendNotification(
match.player1.userId,
Expand Down
Loading

0 comments on commit f6b5147

Please sign in to comment.