Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,11 @@ public ResponseEntity<ApiResponder<UserDto>> updateAdmin(
final String userId = newAdminBody.getId();
final boolean toggleTo = newAdminBody.getToggleTo();

User user = userRepository.getUserById(userId);

if (user == null) {
var userResult = userRepository.getUserById(userId);
if (userResult.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponder.failure("User has not been found."));
}
User user = userResult.get();

user.setAdmin(toggleTo);
boolean isSuccessful = userRepository.updateUser(user);
Expand Down Expand Up @@ -177,7 +177,7 @@ public ResponseEntity<ApiResponder<Announcement>> createNewAnnouncement(

Announcement announcement = Announcement.builder()
.expiresAt(expiresAtWithOffset)
.showTimer(createAnnouncementBody.isShowTimer())
.showTimer(Optional.of(createAnnouncementBody.isShowTimer()))
.message(createAnnouncementBody.getMessage())
.createdAt(nowWithOffset)
.build();
Expand Down Expand Up @@ -209,10 +209,9 @@ public ResponseEntity<ApiResponder<Announcement>> createNewAnnouncement(
public ResponseEntity<ApiResponder<Empty>> deleteAnnouncement(
@Valid @RequestBody final DeleteAnnouncementBody deleteAnnouncementBody,
@Protected(admin = true) final AuthenticationObject authenticationObject) {
Announcement announcement = announcementRepository.getAnnouncementById(deleteAnnouncementBody.getId());
if (announcement == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Announcement does not exist");
}
Announcement announcement = announcementRepository
.getAnnouncementById(deleteAnnouncementBody.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Announcement does not exist"));
OffsetDateTime nowWithOffset = StandardizedOffsetDateTime.now();
announcement.setExpiresAt(nowWithOffset);
boolean updatedAnnouncement = announcementRepository.updateAnnouncement(announcement);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@ is to use the success key of the payload and check whether it is true (announcem
})
@GetMapping("")
public ResponseEntity<ApiResponder<AnnouncementDto>> getLatestAnnouncement() {
Announcement announcement = announcementRepository.getRecentAnnouncement();

if (announcement == null) {
var announcementResult = announcementRepository.getRecentAnnouncement();
if (announcementResult.isEmpty()) {
return ResponseEntity.ok().body(ApiResponder.failure("No announcement available: check back later."));
}
Announcement announcement = announcementResult.get();
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
boolean isExpired = announcement.getExpiresAt().isBefore(now);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.time.Duration;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -304,7 +305,7 @@ public RedirectView verifySchoolEmail(final HttpServletRequest request) {
return new RedirectView("/settings?success=false&message=This email is not supported");
}

user.setSchoolEmail(magicLink.getEmail());
user.setSchoolEmail(Optional.ofNullable(magicLink.getEmail()));
boolean isSuccessful = userRepository.updateUser(user);

if (!isSuccessful) {
Expand All @@ -324,7 +325,7 @@ public RedirectView verifySchoolEmail(final HttpServletRequest request) {
Report.builder()
.data(String.format(
"User %s\nAlready has tag %s",
user.getNickname() != null ? user.getNickname() : user.getDiscordName(),
user.getNickname().orElse(user.getDiscordName()),
schoolEnum.getInternalTag().name()))
.build());
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
Expand Down Expand Up @@ -89,18 +90,24 @@ public void onAuthenticationSuccess(
discordId = attributes.get("id").toString();
discordName = attributes.get("username").toString();

User existingUser = userRepository.getUserByDiscordId(discordId);
var existingUserResult = userRepository.getUserByDiscordId(discordId);
User existingUser;

if (existingUser != null) {
if (existingUserResult.isPresent()) {
existingUser = existingUserResult.get();
existingUser.setDiscordName(discordName);
if (existingUser.getLeetcodeUsername() != null) {
if (existingUser.getLeetcodeUsername().isPresent()) {
try {
UserProfile profile = leetcodeClient.getUserProfile(existingUser.getLeetcodeUsername());
UserProfile profile = leetcodeClient.getUserProfile(
existingUser.getLeetcodeUsername().orElseThrow());
if (profile != null && profile.getUserAvatar() != null) {
existingUser.setProfileUrl(profile.getUserAvatar());
existingUser.setProfileUrl(Optional.ofNullable(profile.getUserAvatar()));
}
} catch (RuntimeException ex) {
LOGGER.warn("LeetCode lookup failed for {}", existingUser.getLeetcodeUsername(), ex);
LOGGER.warn(
"LeetCode lookup failed for {}",
existingUser.getLeetcodeUsername().orElseThrow(),
ex);
}
}
userRepository.updateUser(existingUser);
Expand Down Expand Up @@ -160,11 +167,13 @@ public void onAuthenticationSuccess(
// TODO: Abstract this logic into `DiscordClub`
if ("Patina Network".equals(club.getName())) {
if (member.get().getNickname() != null) {
existingUser.setNickname(member.get().getNickname());
existingUser.setNickname(
Optional.ofNullable(member.get().getNickname()));
} else if (member.get().getUser().getGlobalName() != null) {
existingUser.setNickname(member.get().getUser().getGlobalName());
existingUser.setNickname(
Optional.ofNullable(member.get().getUser().getGlobalName()));
} else {
existingUser.setNickname(existingUser.getDiscordName());
existingUser.setNickname(Optional.ofNullable(existingUser.getDiscordName()));
}
userRepository.updateUser(existingUser);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,9 @@ public ResponseEntity<ApiResponder<UserTag>> validatePassword(
final String clubSlug = registerClubBody.getClubSlug();
final String password = registerClubBody.getPassword();

Club club = clubRepository.getClubBySlug(clubSlug);

if (club == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Club does not exist.");
}
Club club = clubRepository
.getClubBySlug(clubSlug)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Club does not exist."));

boolean valid = clubService.isPasswordValid(club, password);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public ClubService(final ClubRepository clubRepository) {
}

public ClubDto getClubDtoBySlug(final String slug) {
Club club = clubRepository.getClubBySlug(slug);
Club club = clubRepository.getClubBySlug(slug).orElse(null);
if (club == null) {
return null;
}
Expand All @@ -34,6 +34,6 @@ public boolean isPasswordValid(final Club club, final String rawPassword) {
}

public Club getClubBySlug(final String slug) {
return clubRepository.getClubBySlug(slug);
return clubRepository.getClubBySlug(slug).orElse(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@ public ExternalController(
public ResponseEntity<ApiResponder<List<UserWithScore>>> getGwcUsers(
@RequestHeader("X-API-Key") final String apiKey,
@RequestParam("leaderboardId") final String leaderboardId) {
ApiKey validApiKey = apiKeyRepository.getApiKeyByHash(apiKey);
if (validApiKey == null) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid API key");
}
ApiKey validApiKey = apiKeyRepository
.getApiKeyByHash(apiKey)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid API key"));

List<ApiKeyAccess> accesses = apiKeyAccessRepository.getApiKeyAccessesByApiKeyId(validApiKey.getId());
boolean hasGwcAccess =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,16 +287,13 @@ public ResponseEntity<ApiResponder<UserWithScoreDto>> getUserCurrentLeaderboardF
}

// we do not support point of time in this endpoint currently
UserWithScore user = userRepository.getUserWithScoreByIdAndLeaderboardId(
userId,
leaderboardData.get().getId(),
UserFilterOptions.builder().build());

// if (user == null) {
// return
// ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponder.failure("This
// user does not exist on this leaderboard."));
// }
UserWithScore user = userRepository
.getUserWithScoreByIdAndLeaderboardId(
userId,
leaderboardData.get().getId(),
UserFilterOptions.builder().build())
.orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "User does not exist on this leaderboard."));

return ResponseEntity.ok().body(ApiResponder.success("User found!", UserWithScoreDto.fromUserWithScore(user)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.patinanetwork.codebloom.api.submission.body.LeetcodeUsernameObject;
import org.patinanetwork.codebloom.common.db.models.potd.POTD;
import org.patinanetwork.codebloom.common.db.models.user.User;
Expand Down Expand Up @@ -145,7 +146,7 @@ public ResponseEntity<ApiResponder<Empty>> setLeetcodeUsername(

User user = authenticationObject.getUser();

if (user.getLeetcodeUsername() != null) {
if (user.getLeetcodeUsername().isPresent()) {
throw new ResponseStatusException(
HttpStatus.CONFLICT,
"User has already set a username previously. You cannot change your name anymore. Please contact support if there are any issues.");
Expand All @@ -167,8 +168,8 @@ public ResponseEntity<ApiResponder<Empty>> setLeetcodeUsername(
"This username has already been taken. If this is a mistake, please get in touch with us so we can attempt to rectify it.");
}

user.setLeetcodeUsername(leetcodeUsernameObject.getLeetcodeUsername());
user.setProfileUrl(leetcodeUserProfile.getUserAvatar());
user.setLeetcodeUsername(Optional.ofNullable(leetcodeUsernameObject.getLeetcodeUsername()));
user.setProfileUrl(Optional.ofNullable(leetcodeUserProfile.getUserAvatar()));
userRepository.updateUser(user);

return ResponseEntity.ok().body(ApiResponder.success("Leetcode username has been set!", Empty.of()));
Expand Down Expand Up @@ -206,7 +207,7 @@ public ResponseEntity<ApiResponder<ArrayList<AcceptedSubmission>>> checkLatestSu
@Protected final AuthenticationObject authenticationObject) {
User user = authenticationObject.getUser();

if (user.getLeetcodeUsername() == null) {
if (user.getLeetcodeUsername().isEmpty()) {
throw new ResponseStatusException(
HttpStatus.PRECONDITION_FAILED,
"You cannot access this resource without setting a Leetcode username first.");
Expand All @@ -225,8 +226,8 @@ public ResponseEntity<ApiResponder<ArrayList<AcceptedSubmission>>> checkLatestSu

simpleRedis.put(user.getId(), System.currentTimeMillis());

List<LeetcodeSubmission> leetcodeSubmissions =
leetcodeClient.findSubmissionsByUsernameFast(user.getLeetcodeUsername(), 20);
List<LeetcodeSubmission> leetcodeSubmissions = leetcodeClient.findSubmissionsByUsernameFast(
user.getLeetcodeUsername().orElse(null), 20);

return ResponseEntity.ok()
.body(ApiResponder.success(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,9 @@ public UserController(
public ResponseEntity<ApiResponder<UserDto>> getUserProfileByUserId(
final HttpServletRequest request, @PathVariable final String userId) {

User user = userRepository.getUserById(userId);

if (user == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to find user profile.");
}
User user = userRepository
.getUserById(userId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to find user profile."));

return ResponseEntity.ok().body(ApiResponder.success("User profile found!", UserDto.fromUser(user)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,9 @@ public UserV2Controller(final QuestionRepository questionRepository, final UserR
public ResponseEntity<ApiResponder<UserDto>> getUserProfileByLeetcodeUsername(
final HttpServletRequest request, @PathVariable final String leetcodeUsername) {

User user = userRepository.getUserByLeetcodeUsername(leetcodeUsername);

if (user == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to find user profile.");
}
User user = userRepository
.getUserByLeetcodeUsername(leetcodeUsername)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to find user profile."));

return ResponseEntity.ok().body(ApiResponder.success("User profile found!", UserDto.fromUser(user)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,8 +311,9 @@ public RefreshResultDto refreshSubmissions(String guildId, String discordId) thr

String userId = user.getId();

UserWithScore scoredUser = userRepository.getUserWithScoreByIdAndLeaderboardId(
userId, currentLeaderboard.getId(), UserFilterOptions.DEFAULT);
UserWithScore scoredUser = userRepository
.getUserWithScoreByIdAndLeaderboardId(userId, currentLeaderboard.getId(), UserFilterOptions.DEFAULT)
.orElse(null);

int score = scoredUser.getTotalScore();
Indexed<UserWithScore> globalIndex = leaderboardRepository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void generateAchievementsForAllWinners() {
.userId(user.getId())
.leaderboardId(currentLeaderboard.get().getId())
.place(AchievementPlaceEnum.fromInteger(place))
.leaderboard(pair.getRight())
.leaderboard(Optional.of(pair.getRight()))
.title(String.format(
"%s - %s - %s Place",
currentLeaderboard.get().getName(),
Expand Down Expand Up @@ -121,7 +121,6 @@ public void generateAchievementsForAllWinners() {
.userId(user.getId())
.leaderboardId(currentLeaderboard.get().getId())
.place(AchievementPlaceEnum.fromInteger(place))
.leaderboard(null)
.title(String.format(
"%s - %s Place", currentLeaderboard.get().getName(), placeString))
.build();
Expand Down Expand Up @@ -177,26 +176,30 @@ public Page<Indexed<UserWithScoreDto>> getLeaderboardUsers(
}

public User refreshUserSubmissions(final String discordId) throws LeaderboardException {
User user = userRepository.getUserByDiscordId(discordId);

if (user == null) {
throw new LeaderboardException(
"Cannot refresh submissions",
"Please link your account by [logging in to Codebloom](https://codebloom.patinanetwork.org/login) and completing onboarding.");
}

if (user.getLeetcodeUsername() == null) {
User user = userRepository
.getUserByDiscordId(discordId)
.orElseThrow(
() -> new LeaderboardException(
"Cannot refresh submissions",
"Please link your account by [logging in to Codebloom](https://codebloom.patinanetwork.org/login) and completing onboarding."));

if (user.getLeetcodeUsername().isEmpty()) {
throw new LeaderboardException(
"Cannot refresh submissions", "Your Discord Account is not linked to a LeetCode username.");
}
try {
log.info("Fetching recent LeetCode submissions for user: {}", user.getLeetcodeUsername());
List<LeetcodeSubmission> leetcodeSubmissions =
leetcodeClient.findSubmissionsByUsername(user.getLeetcodeUsername(), 20);
log.info(
"Fetching recent LeetCode submissions for user: {}",
user.getLeetcodeUsername().orElse(null));
List<LeetcodeSubmission> leetcodeSubmissions = leetcodeClient.findSubmissionsByUsername(
user.getLeetcodeUsername().orElse(null), 20);

submissionsHandler.handleSubmissions(leetcodeSubmissions, user, true);
} catch (Exception e) {
log.error("Failed to fetch or process submissions for user {}", user.getLeetcodeUsername(), e);
log.error(
"Failed to fetch or process submissions for user {}",
user.getLeetcodeUsername().orElse(null),
e);
throw new LeaderboardException(
"Cannot refresh submissions",
"Failed to fetch or process submissions from LeetCode. Please try again later.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -111,7 +110,7 @@ private List<UserDto> buildPlayersInLobby(final String lobbyId) {

return lobbyPlayers.stream()
.map(lobbyPlayer -> userRepository.getUserById(lobbyPlayer.getPlayerId()))
.filter(Objects::nonNull)
.flatMap(Optional::stream)
.map(UserDto::fromUser)
.collect(Collectors.toList());
}
Expand Down Expand Up @@ -290,8 +289,8 @@ public int processSubmissions(User user, Lobby activeLobby) throws DuelException
.map(QuestionBank::getQuestionTitle)
.collect(Collectors.toSet());

List<LeetcodeSubmission> leetcodeSubmissions =
leetcodeClient.findSubmissionsByUsername(user.getLeetcodeUsername(), MAX_LEETCODE_SUBMISSIONS);
List<LeetcodeSubmission> leetcodeSubmissions = leetcodeClient.findSubmissionsByUsername(
user.getLeetcodeUsername().orElse(null), MAX_LEETCODE_SUBMISSIONS);

var solvedLeetcodeSubmissions = leetcodeSubmissions.stream()
.filter(s -> solvableQuestionTitlesSet.contains(s.getTitle()))
Expand Down
Loading
Loading