Skip to content

Commit

Permalink
fix duplicates in save and concurrency issue, comments and logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyagara committed Sep 24, 2024
1 parent 43b1729 commit f95c45c
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 30 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
# CoopTweaks

Cooperative advancements, chat relay for a Discord channel and more.
Sync advancements, chat relay for a Discord channel and more.

## About

This project is inspired by the [CooperativeAdvancements](https://modrinth.com/mod/cooperative-advancements) mod, my
goal with it mod is to add on the coop experience I really enjoyed from CooperativeAdvancements by giving more
configurable features in just one package.
goal with this is to add on the coop experience I really enjoyed from CooperativeAdvancements by giving more features in just one package.

## Features

- Bridges a Discord channel to the Minecraft server chat, allowing for chat between the two.
- Send events like advancements, join/leave, death, from the server to Discord.
- Sync advancements completion, so all players can share the same advancement progress.
- Sync advancements completion, all players share the same advancement progress.
- Discord commands to retrieve information about the server.

## TODO

- Add Discord commands to retrieve general information about the server, TPS, uptime, etc.
- Utils class might need to become a package as more features are added.

## Configuration

Expand Down
2 changes: 0 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@ loom {
}

dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"

// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

shadow implementation("com.discord4j:discord4j-core:${project.discord4j_version}")
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/cooptweaks/Configuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Configuration {
public final class Configuration {
/** Main config folder path. */
private static final Path MAIN_PATH = FabricLoader.getInstance().getConfigDir().resolve("cooptweaks");

Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/cooptweaks/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public static String GetPlayerDimension(String player) {

/**
Gets the advancements progress of the server.
Currently only takes into account the number of criterion, the total is very inaccurate.
@return The advancements progress of the server. Example: "10/122".
*/
Expand Down
27 changes: 14 additions & 13 deletions src/main/java/com/cooptweaks/advancements/Advancements.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public final class Advancements {
private Advancements() {
Expand All @@ -50,13 +51,13 @@ public static Advancements getInstance() {
private static MinecraftServer SERVER;

public static HashMap<Identifier, AdvancementEntry> ALL_ADVANCEMENTS = new HashMap<>(122);
public static HashMap<String, AdvancementEntry> COMPLETED_ADVANCEMENTS = new HashMap<>(122);
public static ConcurrentHashMap<String, AdvancementEntry> COMPLETED_ADVANCEMENTS = new ConcurrentHashMap<>(122);

private static FileChannel CURRENT_SEED_FILE;

private static synchronized void appendToSave(String text) throws IOException {
private static synchronized int appendToSave(String text) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(text.getBytes());
CURRENT_SEED_FILE.write(buffer);
return CURRENT_SEED_FILE.write(buffer);
}

public void LoadAdvancements(MinecraftServer server, Path savePath) {
Expand Down Expand Up @@ -88,7 +89,7 @@ private static int loadServerAdvancements(MinecraftServer server) {
for (AdvancementEntry entry : advancements) {
Advancement advancement = entry.value();

// If the advancement has a display, add it to the list of advancements
// If the advancement has a display, add it to the list.
advancement.display().ifPresent(display -> {
ALL_ADVANCEMENTS.put(entry.id(), entry);
});
Expand Down Expand Up @@ -116,7 +117,7 @@ private static int loadSaveAdvancements(MinecraftServer server, Path saveFolder)
while (line != null) {
String[] arr = line.split(",");
if (arr.length < 2) {
Main.LOGGER.warn("Skipping malformed line: {}", line);
Main.LOGGER.warn("Skipping malformed line: '{}'", line.trim());
continue;
}

Expand Down Expand Up @@ -150,20 +151,19 @@ public void SyncPlayerOnJoin(ServerPlayerEntity player, String name) {
}

public void OnCriterion(ServerPlayerEntity currentPlayer, AdvancementEntry entry, String criterionName, boolean isDone) {
String id = entry.id().toString();
if (COMPLETED_ADVANCEMENTS.containsKey(id)) {
if (COMPLETED_ADVANCEMENTS.containsKey(criterionName)) {
return;
}

// turn this into a lambda expression or use functional programming
Advancement advancement = entry.value();
advancement.display().ifPresent(display -> {
if (isDone) {
String id = entry.id().toString();
String playerName = currentPlayer.getName().getString();

COMPLETED_ADVANCEMENTS.put(id, entry);
COMPLETED_ADVANCEMENTS.put(criterionName, entry);

// Grant the advancement to all players
// Grant the advancement to all players.
List<ServerPlayerEntity> players = SERVER.getPlayerManager().getPlayerList();
for (ServerPlayerEntity player : players) {
if (currentPlayer != player) {
Expand All @@ -173,7 +173,8 @@ public void OnCriterion(ServerPlayerEntity currentPlayer, AdvancementEntry entry

try {
String line = String.format("%s,%s\n", id, criterionName);
appendToSave(line);
int n = appendToSave(line);
Main.LOGGER.info("Saved line '{}' ({} bytes written).", line, n);
} catch (IOException e) {
// This should be handled in another way, has to be recoverable, so we can try again.
throw new RuntimeException(e);
Expand All @@ -184,13 +185,13 @@ public void OnCriterion(ServerPlayerEntity currentPlayer, AdvancementEntry entry
advancementName = Optional.of(Text.literal(criterionName));
}

// Send announcement to the server chat
// Send announcement to the server chat.
MutableText text = Text.literal(playerName + " has made the advancement ")
.append(advancementName.get());

SERVER.getPlayerManager().broadcast(text, false);

// Send announcement to the Discord channel
// Send announcement to the Discord channel.
String title = display.getTitle().getString();
if (title.isEmpty()) {
title = criterionName;
Expand Down
13 changes: 5 additions & 8 deletions src/main/java/com/cooptweaks/discord/Discord.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,7 @@ public void QueueEvent(Runnable event) {
}

private static void ProcessQueue() {
for (Runnable event : new ArrayList<>(QUEUE)) {
event.run();
}

QUEUE.forEach(Runnable::run);
QUEUE.clear();
}

Expand All @@ -110,7 +107,7 @@ public void Start(ConfigMap config) {
SlashCommand command = COMMANDS.get(key);
ApplicationCommandRequest cmd = command.Build();

Main.LOGGER.info("Found command {}", command.getName());
Main.LOGGER.info("Found command '{}'", command.getName());
commands.add(cmd);
}

Expand Down Expand Up @@ -174,7 +171,7 @@ private void onInteraction(ChatInputInteractionEvent event) {
String cmd = event.getCommandName();

if (COMMANDS.containsKey(cmd)) {
Main.LOGGER.info("Executing command {}", cmd);
Main.LOGGER.info("Executing command '{}'", cmd);

SlashCommand command = COMMANDS.get(cmd);
Result<EmbedCreateSpec> embed = command.Execute(SERVER);
Expand All @@ -183,14 +180,14 @@ private void onInteraction(ChatInputInteractionEvent event) {
event.reply().withEmbeds(embed.getValue()).subscribe();
} else {
String err = embed.getError();
Main.LOGGER.error("Command {} failed to execute. Error: {}", cmd, err);
Main.LOGGER.error("Command '{}' failed to execute. Error: {}", cmd, err);
event.reply().withContent(String.format("Command failed to execute. Error: %s", err)).subscribe();
}

return;
}

Main.LOGGER.warn("Unknown command {}", cmd);
Main.LOGGER.warn("Unknown command '{}'", cmd);
}

private void onMessage(MessageCreateEvent event) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/fabric.mod.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"id": "cooptweaks",
"version": "${version}",
"name": "CoopTweaks",
"description": "Cooperative advancements, chat relay for a Discord channel and more.",
"description": "Sync advancements, chat relay for a Discord channel and more.",
"authors": [
"Kyagara"
],
Expand Down

0 comments on commit f95c45c

Please sign in to comment.