Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
  • Loading branch information
Inerska committed Mar 8, 2024
2 parents cfa9d70 + 15490e9 commit 81a4d8d
Show file tree
Hide file tree
Showing 17 changed files with 192 additions and 89 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Build
on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]
jobs:
sonarcloud:
name: SonarCloud
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
2 changes: 2 additions & 0 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
sonar.projectKey=TalentHubProject_monolith
sonar.organization=talenthubproject
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.Setter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
public class Main {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public Setup(List<DBACommand> commands, List<DBAButton> buttons, List<DBAStringS

@Override
public void onGuildReady(GuildReadyEvent event) {

event.getJDA().updateCommands().queue();
event.getGuild().updateCommands().queue();
DBALoader.getInstance(event.getJDA()).addDBACommandsToGuild(event.getGuild(),
this.commands.toArray()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.talenthub.module.embed.dba.command;

import fr.leonarddoo.dba.annotation.Command;
import fr.leonarddoo.dba.annotation.Option;
import fr.leonarddoo.dba.annotation.Options;
import fr.leonarddoo.dba.element.DBACommand;
import lombok.AllArgsConstructor;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import org.springframework.stereotype.Component;
import org.talenthub.service.ConfigService;

import java.awt.*;
import java.util.Objects;

@Command(name = "informational-message", description = "Créer un message d'information.")
@Options({
@Option(type = OptionType.STRING, name = "title", description = "Titre du message.", required = true),
@Option(type = OptionType.STRING, name = "description", description = "Description du message.", required = true)
})
@Component
@AllArgsConstructor
public class InformationalMessageCmd implements DBACommand {

private final ConfigService configService;

@Override
public void execute(SlashCommandInteractionEvent event) {

final var title = Objects.requireNonNull(event.getOption("title")).getAsString();
final var description = Objects.requireNonNull(event.getOption("description")).getAsString();

event.getChannel().asTextChannel().sendMessageEmbeds(new EmbedBuilder()
.setTitle(title)
.setColor(Color.decode(configService.getString("color-code")))
.setDescription(description)
.build()).queue();

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import org.springframework.stereotype.Component;
import org.talenthub.module.xp.entity.PlayerLevel;
import org.talenthub.module.xp.repository.PlayerLevelRepository;
import org.talenthub.service.ConfigService;

import java.awt.*;
import java.util.List;

@Command(name = "experience-leaderboard", description = "Afficher le classement des joueurs avec le plus d'expérience")
Expand All @@ -17,10 +19,11 @@
public class ExperienceLeaderboardCmd implements DBACommand {

private final PlayerLevelRepository playerLevelRepository;
private final ConfigService configService;

@Override
public void execute(final SlashCommandInteractionEvent event) {

/**
event.deferReply(true).queue();
List<PlayerLevel> top10 = playerLevelRepository.findTop10ByOrderByExperienceDesc();
Expand All @@ -34,8 +37,11 @@ public void execute(final SlashCommandInteractionEvent event) {
.setTitle("Leaderboard de l'experience")
.setThumbnail(event.getGuild().getIconUrl())
.setDescription(sb.toString())
.build()).queue();
.setColor(Color.decode(configService.getString("color-code")))
.build()).queue();
**/
return;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import org.talenthub.module.xp.entity.PlayerLevel;
import org.talenthub.module.xp.service.PlayerLevelService;
import org.talenthub.module.xp.service.api.CreatureAPIService;
import org.talenthub.service.ConfigService;

import java.awt.*;
import java.io.File;

@Command(name = "experience-profil", description = "Command pour récupérer le profil expérience d'un membre.")
Expand All @@ -25,10 +27,12 @@
public class ExperienceProfilCmd implements DBACommand {

private final PlayerLevelService playerLevelService;
private final ConfigService configService;

@Override
public void execute(final SlashCommandInteractionEvent event) {

/**
event.deferReply().queue();
Member member;
Expand All @@ -50,11 +54,14 @@ public void execute(final SlashCommandInteractionEvent event) {
.addField("Niveau", String.valueOf(playerLevel.getLevel().getId()), true)
.addField("XP", String.valueOf(playerLevel.getXp()), true)
.addField("XP restant", String.valueOf(playerLevel.getLevel().getMaxXp() - playerLevel.getXp()), true)
.setColor(Color.decode(configService.getString("color-code")))
.setImage(imageUrl)
.build()).queue(success ->
message.delete().queue());
});
**/

return;

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.talenthub.module.xp.task.ActivityCalculTask;
import org.talenthub.module.xp.task.ActivityCalculTaskFactory;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
Expand All @@ -24,25 +25,27 @@ public class ReadyListener extends ListenerAdapter {

@Override
public void onReady(final ReadyEvent event) {

levelService.checkAndGenerateFirsLevel();

levelService.checkAndGenerateFirstLevel();
}

@Override
public void onGuildReady(final GuildReadyEvent event) {

ActivityCalculTask activityCalculTask = new ActivityCalculTaskFactory().create(event.getGuild());

try (ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1)) {

scheduler.scheduleAtFixedRate(activityCalculTask, 0, 1, TimeUnit.HOURS);

}catch (Exception e){

LOGGER.error("Error while scheduling ActivityCalculTask", e);

}

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(activityCalculTask, 0, 1, TimeUnit.HOURS);

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
scheduler.shutdown();
if (!scheduler.awaitTermination(1, TimeUnit.MINUTES)) {
LOGGER.error("Executor did not terminate in the specified time.");
List<Runnable> droppedTasks = scheduler.shutdownNow();
LOGGER.error("Executor was abruptly shut down. {} tasks will not be executed.", droppedTasks.size());
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
Thread.currentThread().interrupt();
}
}));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@ public class TextMessageListener extends ListenerAdapter {

@Override
public void onMessageReceived(final MessageReceivedEvent event) {

if(event.getAuthor().isBot()) return;
if(!event.getChannelType().equals(ChannelType.TEXT)) return;
if (event.getAuthor().isBot() || event.getMember() == null || !event.getChannelType().equals(ChannelType.TEXT)) {
return;
}

int xpEarned = event.getMessage().getContentRaw().split(" ").length;

levelService.addXp(event.getChannel().asTextChannel(), event.getMember(), xpEarned);

//fix(Leonarddoo): Le système de gain d'xp est à revoir
//levelService.addXp(event.getChannel().asTextChannel(), event.getMember(), xpEarned);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public void onGuildVoiceUpdate(final GuildVoiceUpdateEvent event) {

long minutes = joined.until(left, ChronoUnit.MINUTES);

levelService.addXp(event.getChannelLeft().asVoiceChannel(), event.getEntity(), minutes);
//fix(Leonarddoo): Le système de gain d'xp est à revoir
//levelService.addXp(event.getChannelLeft().asVoiceChannel(), event.getEntity(), minutes);

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public void onMessageReceived(MessageReceivedEvent event) {
}

// Add the xp to the user
levelService.addXp(event.getChannel().asTextChannel(), event.getMember(), xpEarned);
//fix(Leonarddoo): Le système de gain d'xp est à revoir
//levelService.addXp(event.getChannel().asTextChannel(), event.getMember(), xpEarned);

// Add reaction to show the user gain xp
event.getMessage().addReaction(Emoji.fromUnicode("U+2728")).queue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
import lombok.AllArgsConstructor;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.talenthub.module.xp.entity.Level;
import org.talenthub.module.xp.entity.PlayerLevel;
import org.talenthub.module.xp.repository.LevelRepository;
import org.talenthub.module.xp.task.ActivityCalculTask;
import org.talenthub.service.ConfigService;
import org.talenthub.service.MessageBroadcasterService;

import java.util.Optional;

@Service
@AllArgsConstructor
public class LevelService {
Expand All @@ -20,86 +24,66 @@ public class LevelService {
private final LevelRepository levelRepository;
private final MessageBroadcasterService messageBroadcasterService;
private final ConfigService configService;
private final Logger LOGGER = LoggerFactory.getLogger(LevelService.class);

public void addXp(final GuildMessageChannel channel, final Member member, final long xp){
@Transactional
public void addXp(final GuildMessageChannel channel, final Member member, final long xp) {
if (member == null) {
LOGGER.error("Member is null. Cannot add XP.");
return;
}

PlayerLevel playerLevel = playerLevelService.getPlayerLevel(member.getIdLong());
long newXp = playerLevel.getXp() + getBoostedXp(member, xp);

playerLevel.setXp(newXp);
LOGGER.info("Added XP to member with ID {}. New XP: {}", member.getId(), newXp);

Optional<Level> nextLevelOpt = levelRepository.findNextLevelByMaxXp(newXp);
while (nextLevelOpt.isPresent() && playerLevel.getLevel().getId() < nextLevelOpt.get().getId()) {

// Si le joueur a atteint un nouveau niveau
if (newXp >= nextLevelOpt.get().getMaxXp()) {
playerLevel.setLevel(nextLevelOpt.get());
playerLevelService.updatePlayerLevel(playerLevel);
broadcastLevelUpMessage(channel, member, nextLevelOpt.get());
LOGGER.info("Member with ID {} leveled up to {}", member.getId(), playerLevel.getLevel().getId());
} else {
break;
}

//long xpToAdd = ActivityCalculTask.getInstance().isBoostActivated() ? xp * 2 : xp;
//xpToAdd = getBoostedXp(member, xpToAdd);
long xpToAdd = xp;
xpToAdd = getBoostedXp(member, xpToAdd);

playerLevel.setXp(playerLevel.getXp() + xpToAdd);

if(playerLevel.getLevel().getMaxXp() <= playerLevel.getXp()){

Level newLevel = levelUp(playerLevel);

messageBroadcasterService.broadcastBasicMessageEmbed(channel, "Félécitation **" + member.getEffectiveName() + "**! Tu as atteint le niveau " + newLevel.getId() + "!");

}else{
playerLevelService.updatePlayerLevel(playerLevel);
// Sinon, continue de vérifier si le joueur a atteint un autre niveau
newXp -= nextLevelOpt.get().getMaxXp();
nextLevelOpt = levelRepository.findNextLevelByMaxXp(newXp);
}

}

private Level levelUp(final PlayerLevel playerLevel){

Level newlevel = levelRepository.findNextLevelByMaxXp(playerLevel.getXp()).orElse(createNewLevels(playerLevel.getXp(), playerLevel.getLevel()));
playerLevel.setLevel(newlevel);

playerLevelService.updatePlayerLevel(playerLevel);

return newlevel;
}

public void checkAndGenerateFirsLevel() {

public void checkAndGenerateFirstLevel() {
if (levelRepository.count() == 0) {

int maxXp = configService.getInt("first-level-xp");
Level level = new Level(1, maxXp);

levelRepository.save(level);

LOGGER.info("First level created with max XP: {}", maxXp);
}
}

private Level createNewLevels(long targetXp, Level level) {
long currentXp = level.getMaxXp();
int currentLevel = level.getId();

while (currentXp < targetXp) {
currentLevel++;
currentXp *= (long) 1.2;
Level newLevel = new Level(currentLevel, currentXp);
levelRepository.save(newLevel);
level = newLevel;
}

return level;
private void broadcastLevelUpMessage(GuildMessageChannel channel, Member member, Level level) {
messageBroadcasterService.broadcastBasicMessageEmbed(channel,
String.format("Congratulations **%s**! You have reached level %d!", member.getEffectiveName(), level.getId()));
}


private long getBoostedXp(Member member, final long xp) {
int maxBoostValue = 1;

for (JsonElement boost : configService.getJsonArray("boost-role-xp")) {
String roleId = boost.getAsJsonObject().get("role-id").getAsString();

if (member.getRoles().stream().anyMatch(role -> role.getId().equals(roleId))) {
int boostValue = boost.getAsJsonObject().get("value").getAsInt();
if (boostValue > maxBoostValue) {
maxBoostValue = boostValue;
}
maxBoostValue = Math.max(maxBoostValue, boostValue);
}
}

return xp * maxBoostValue;
}




}

Loading

0 comments on commit 81a4d8d

Please sign in to comment.