Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

bug/1169-ttb-resolve-doublicated-citizen-saving #4

Merged
merged 1 commit into from
Jul 3, 2024
Merged
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
68 changes: 34 additions & 34 deletions src/main/java/net/turniptales/discord/commands/StatsCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.turniptales.discord.common.api.Api;
import net.turniptales.discord.common.api.model.DiscordPlayerStats;
import net.turniptales.discord.common.api.model.ConnectionDataValue;
import net.turniptales.discord.common.api.model.PunishmentData;

import java.text.DecimalFormat;
Expand Down Expand Up @@ -42,17 +42,17 @@ public void onSlashCommandInteraction(SlashCommandInteractionEvent e) {
Member member = e.getMember();
if (nonNull(playerOptionMapping)) {
try {
DiscordPlayerStats discordPlayerStats = api.getPlayerStatsByDiscordUserId(playerOptionMapping.getAsUser().getIdLong(), null);
MessageEmbed publicPlayerStats = isTicketChannel(e.getChannel()) ? getPrivatePlayerStats(discordPlayerStats, member) : getPublicPlayerStats(discordPlayerStats, member);
ConnectionDataValue connectionDataValue = api.getData(e.getUser().getIdLong());
MessageEmbed publicPlayerStats = isTicketChannel(e.getChannel()) ? getPrivatePlayerStats(connectionDataValue, member) : getPublicPlayerStats(connectionDataValue, member);
e.replyEmbeds(publicPlayerStats).queue();
} catch (Exception ex) {
e.reply("Der angegebene Spieler hat seinen Minecraft Account noch nicht verknüpft.").setEphemeral(true).queue();
e.getHook().deleteOriginal().queueAfter(5, SECONDS);
}
} else {
try {
DiscordPlayerStats discordPlayerStats = api.getPlayerStatsByDiscordUserId(e.getUser().getIdLong(), null);
MessageEmbed privatePlayerStats = getPrivatePlayerStats(discordPlayerStats, member);
ConnectionDataValue connectionDataValue = api.getData(e.getUser().getIdLong());
MessageEmbed privatePlayerStats = getPrivatePlayerStats(connectionDataValue, member);
e.replyEmbeds(privatePlayerStats).setEphemeral(true).queue();
} catch (Exception ex) {
e.reply("Du hast deinen Minecraft Account noch nicht verknüpft.").setEphemeral(true).queue();
Expand All @@ -67,64 +67,64 @@ && nonNull(textChannel.getTopic())
&& textChannel.getTopic().contains("Ticket von ");
}

private MessageEmbed getPublicPlayerStats(DiscordPlayerStats discordPlayerStats, Member member) {
return getDefaultEmbedBuilder(discordPlayerStats, member)
.addField("Level", valueOf(discordPlayerStats.getLevel()), true)
.addField("Fraktion:", discordPlayerStats.getGroup(), true)
.addField("Kennt Spieler", valueOf(discordPlayerStats.getKnownPlayerCount()), true)
private MessageEmbed getPublicPlayerStats(ConnectionDataValue connectionDataValue, Member member) {
return getDefaultEmbedBuilder(connectionDataValue, member)
.addField("Level", valueOf(connectionDataValue.getLevel()), true)
.addField("Fraktion:", connectionDataValue.getGroup(), true)
.addField("Kennt Spieler", valueOf(connectionDataValue.getKnownPlayerCount()), true)

.addField("Steckbrief", getCharacteristics(discordPlayerStats), false)
.addField("Steckbrief", getCharacteristics(connectionDataValue), false)
.addBlankField(false)
.addField("Häuser:", getHouses(discordPlayerStats.getHouses()), true)
.addField("Autos:", getCars(discordPlayerStats.getCars()), true)
.addField("Häuser:", getHouses(connectionDataValue.getHouses()), true)
.addField("Autos:", getCars(connectionDataValue.getCars()), true)
.build();
}

private MessageEmbed getPrivatePlayerStats(DiscordPlayerStats discordPlayerStats, Member member) {
return getDefaultEmbedBuilder(discordPlayerStats, member)
.addField("Level", valueOf(discordPlayerStats.getLevel()), true)
.addField("Fraktion:", discordPlayerStats.getGroup(), true)
.addField("Kennt Spieler", valueOf(discordPlayerStats.getKnownPlayerCount()), true)
private MessageEmbed getPrivatePlayerStats(ConnectionDataValue connectionDataValue, Member member) {
return getDefaultEmbedBuilder(connectionDataValue, member)
.addField("Level", valueOf(connectionDataValue.getLevel()), true)
.addField("Fraktion:", connectionDataValue.getGroup(), true)
.addField("Kennt Spieler", valueOf(connectionDataValue.getKnownPlayerCount()), true)

.addField("Steckbrief", getCharacteristics(discordPlayerStats), false)
.addField("Finanzen", getBalances(discordPlayerStats), true)
.addField("Bestrafung", getPunishments(discordPlayerStats.getPunishmentData()), true)
.addField("Steckbrief", getCharacteristics(connectionDataValue), false)
.addField("Finanzen", getBalances(connectionDataValue), true)
.addField("Bestrafung", getPunishments(connectionDataValue.getPunishmentData()), true)
.addBlankField(false)
.addField("Häuser:", getHouses(discordPlayerStats.getHouses()), true)
.addField("Autos:", getCars(discordPlayerStats.getCars()), true)
.addField("Häuser:", getHouses(connectionDataValue.getHouses()), true)
.addField("Autos:", getCars(connectionDataValue.getCars()), true)
.build();
}

private EmbedBuilder getDefaultEmbedBuilder(DiscordPlayerStats discordPlayerStats, Member member) {
private EmbedBuilder getDefaultEmbedBuilder(ConnectionDataValue connectionDataValue, Member member) {
assert BOT != null;
return new EmbedBuilder()
.setColor(CYAN)
.setThumbnail("https://minotar.net/helm/" + discordPlayerStats.getMinecraftUuid() + "/300.png")
.setThumbnail("https://minotar.net/helm/" + connectionDataValue.getMinecraftUuid() + "/300.png")
.setAuthor("TurnipTales", "https://turniptales.net/", BOT.getEffectiveAvatarUrl())
.setTitle("Statistiken von " + discordPlayerStats.getMinecraftName())
.setDescription("**Role**: " + discordPlayerStats.getRole())
.setTitle("Statistiken von " + connectionDataValue.getMinecraftName())
.setDescription("**Role**: " + connectionDataValue.getRole())
.setFooter(member.getEffectiveName(), member.getEffectiveAvatarUrl())
.setTimestamp(new Date().toInstant());
}

private String getCharacteristics(DiscordPlayerStats discordPlayerStats) {
private String getCharacteristics(ConnectionDataValue connectionDataValue) {
return """
**Name**: %s
**Alter**: %s
**Geschlecht**: %s
"""
.formatted(discordPlayerStats.getRoleplayName(),
discordPlayerStats.getAge(),
discordPlayerStats.getGender().equals("MAN") ? ":male_sign:" : ":female_sign:");
.formatted(connectionDataValue.getRoleplayName(),
connectionDataValue.getAge(),
connectionDataValue.getGender().equals("MAN") ? ":male_sign:" : ":female_sign:");
}

private String getBalances(DiscordPlayerStats discordPlayerStats) {
private String getBalances(ConnectionDataValue connectionDataValue) {
return """
**Bank**: %s$
**Bargeld**: %s$
**PayPal**: %s$
"""
.formatted(DECIMAL_FORMAT.format(discordPlayerStats.getBankBalance()), DECIMAL_FORMAT.format(discordPlayerStats.getCashBalance()), DECIMAL_FORMAT.format(discordPlayerStats.getPalPayBalance()));
.formatted(DECIMAL_FORMAT.format(connectionDataValue.getBankBalance()), DECIMAL_FORMAT.format(connectionDataValue.getCashBalance()), DECIMAL_FORMAT.format(connectionDataValue.getPalPayBalance()));
}

private String getPunishments(PunishmentData punishmentData) {
Expand All @@ -139,7 +139,7 @@ private String getPunishments(PunishmentData punishmentData) {
.formatted(!punishmentData.noWeaponBlockActive(), !punishmentData.noGroupBlockActive(), !punishmentData.noSkillBlockActive(), !punishmentData.noAdBlockActive(), !punishmentData.noCarBlockActive(), punishmentData.getCheckpointsLeft());
}

private String getHouses(List<Integer> houses) {
private String getHouses(List<Long> houses) {
StringJoiner houseJoiner = new StringJoiner("\n- ", "- ", "");
houses.stream()
.map(Object::toString)
Expand Down
16 changes: 11 additions & 5 deletions src/main/java/net/turniptales/discord/commands/VerifyCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.turniptales.discord.common.api.Api;
import net.turniptales.discord.common.api.model.DiscordPlayerStats;
import net.turniptales.discord.common.api.model.ConnectionDataValue;
import org.springframework.http.ResponseEntity;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static java.util.concurrent.TimeUnit.SECONDS;

public class VerifyCommand extends ListenerAdapter {
Expand All @@ -24,10 +24,16 @@ public void onSlashCommandInteraction(SlashCommandInteractionEvent e) {
return;
}

DiscordPlayerStats discordPlayerStats = new Api().getPlayerStatsByDiscordUserId(e.getUser().getIdLong(), codeOptionMapping.getAsString());
Api api = new Api();

long accountUserId = e.getUser().getIdLong();
ResponseEntity<Void> response = api.connect(accountUserId, codeOptionMapping.getAsString());
boolean success = response.getStatusCode().is2xxSuccessful();

String message;
if (nonNull(discordPlayerStats)) {
message = "Du hast deinen Discord Account mit dem Minecraft Account " + discordPlayerStats.getMinecraftName() + " verknüpft!\nDiese Nachricht zerstört sich gleich von selbst...";
if (success) {
ConnectionDataValue connectionDataValue = api.getData(accountUserId);
message = "Du hast deinen Discord Account mit dem Minecraft Account " + connectionDataValue.getMinecraftName() + " verknüpft!";
} else {
message = "Dein Discord Account konnte nicht mit deinem Minecraft Account verknüpft werden.";
}
Expand Down
35 changes: 20 additions & 15 deletions src/main/java/net/turniptales/discord/common/api/Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,38 @@
import com.google.gson.JsonSerializer;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import net.turniptales.discord.common.api.model.DiscordPlayerStats;
import org.jetbrains.annotations.Nullable;
import net.turniptales.discord.common.api.model.ConnectionDataValue;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.ZonedDateTime;

import static java.lang.String.format;
import static java.time.ZonedDateTime.parse;
import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME;
import static java.util.Optional.ofNullable;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;

@Log4j2
@Data
public class Api {

/**
* {@link DiscordPlayerStats}
* {@link ConnectionDataValue}
*/
public DiscordPlayerStats getPlayerStatsByDiscordUserId(long userId, @Nullable String discordCode) {
String code = ofNullable(discordCode)
.map(c -> "?discordCode=" + c)
.orElse("");
public ConnectionDataValue getData(long accountUserId) {
String url = format("/data?discordUserId%s", accountUserId);
return getGson().fromJson(sendGetRequest(url), ConnectionDataValue.class);
}

return parseGetRequest("/" + userId + code, DiscordPlayerStats.class);
public ResponseEntity<Void> connect(long accountUserId, String code) {
String url = format("/connect?type=DISCORD&accountUserId=%s&code=%s", accountUserId, code);
return sendPostRequest(url);
}

/**
* Request
*/
private <T> T parseGetRequest(String url, Class<T> model) {
Gson gson = getGson();
return gson.fromJson(sendGetRequest(url), model);
}

private Gson getGson() {
return new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, (JsonDeserializer<ZonedDateTime>) (json, type, jsonDeserializationContext) -> parse(json.getAsJsonPrimitive().getAsString()))
Expand All @@ -55,9 +53,16 @@ private String sendGetRequest(String url) {
.block();
}

private ResponseEntity<Void> sendPostRequest(String url) {
return getClient(url).method(POST)
.retrieve()
.toBodilessEntity()
.block();
}

private WebClient getClient(String url) {
return WebClient.builder()
.baseUrl("https://turniptales.net:7200/turniptalesapi/v1/verification/discord" + url)
.baseUrl("https://turniptales.net:7200/turniptalesapi/v1/connection" + url)
.defaultHeader("Authorization", "Basic dHVybmlwdGFsZXMtYXBpdXNlcjoqYnp0OThjV3EvLCckOT41SEN7NlEtTycralZFZmprMQ==")
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,21 @@

@Data
@Builder
public class DiscordPlayerStats {
public class ConnectionDataValue {

// data
private String citizenId;
private UUID minecraftUuid;
private String minecraftName;
private String role;
private String roleDisplayName;
private List<String> teams;
private int level;
private String group;
private int knownPlayerCount;
// group
private String group;
private int factionRank;
private boolean leaderRights;
// characteristics
private String roleplayName;
private int age;
Expand All @@ -25,7 +31,8 @@ public class DiscordPlayerStats {
private double bankBalance;
private double cashBalance;
private double palPayBalance;
// other
private PunishmentData punishmentData;
private List<Integer> houses;
private List<Long> houses;
private List<String> cars;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
@Builder
public class PunishmentData {

private long id;
@Nullable
private ZonedDateTime weaponBlockUntilDateTime;
@Nullable
Expand Down
Loading