Skip to content

Commit

Permalink
Persist tracked quest
Browse files Browse the repository at this point in the history
  • Loading branch information
Krakenied committed Aug 22, 2024
1 parent 1005381 commit b3dc7ff
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class AdminMigrateCommandHandler implements CommandHandler {
Expand Down Expand Up @@ -87,11 +88,11 @@ public void handle(CommandSender sender, String[] args) {
}

sender.sendMessage(ChatColor.GRAY + "Loading quest progress files from '" + fromProvider.getName() + "'...");
List<QuestProgressFile> files = fromProvider.loadAllProgressFiles();
List<Map.Entry<QuestProgressFile, String>> files = fromProvider.loadAllProgressFiles();
sender.sendMessage(ChatColor.GRAY.toString() + files.size() + " files loaded.");

for (QuestProgressFile file : files) {
file.setModified(true);
for (Map.Entry<QuestProgressFile, String> file : files) {
file.getKey().setModified(true);
}

sender.sendMessage(ChatColor.GRAY + "Writing quest progress files to '" + toProvider.getName() + "'...");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,17 @@ public void onEvent(PlayerJoinEvent event) {
plugin.getQuestCompleter().queueFullCheck(qPlayer.getQuestProgressFile());

// track first quest
if (plugin.getConfig().getBoolean("options.allow-quest-track") && plugin.getConfig().getBoolean("options.quest-autotrack")) {
for (Quest quest : plugin.getQuestManager().getQuests().values()) {
if (qPlayer.hasStartedQuest(quest)) {
qPlayer.trackQuest(quest);
break;
if (plugin.getConfig().getBoolean("options.allow-quest-track")) {
if (qPlayer.getPlayerPreferences().getTrackedQuestId() != null) {
return;
}

if (plugin.getConfig().getBoolean("options.quest-autotrack")) {
for (Quest quest : plugin.getQuestManager().getQuests().values()) {
if (qPlayer.hasStartedQuest(quest)) {
qPlayer.trackQuest(quest);
break;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -51,6 +52,11 @@ public class MySqlStorageProvider implements StorageProvider {
" `progress` VARCHAR(64) NULL," +
" `data_type` VARCHAR(10) NULL," +
" PRIMARY KEY (`uuid`, `quest_id`, `task_id`));";
private static final String CREATE_TABLE_PLAYER_PREFERENCES =
"CREATE TABLE IF NOT EXISTS `{prefix}player_preferences` (" +
" `uuid` VARCHAR(36) NOT NULL," +
" `tracked_quest_id` VARCHAR(50) NOT NULL," +
" PRIMARY KEY (`uuid`));";
private static final String CREATE_TABLE_DATABASE_INFORMATION =
"CREATE TABLE IF NOT EXISTS `{prefix}database_information` (" +
" `key` VARCHAR(255) NOT NULL," +
Expand All @@ -60,6 +66,8 @@ public class MySqlStorageProvider implements StorageProvider {
"SELECT quest_id, started, started_date, completed, completed_before, completion_date FROM `{prefix}quest_progress` WHERE uuid=?;";
private static final String SELECT_PLAYER_TASK_PROGRESS =
"SELECT quest_id, task_id, completed, progress, data_type FROM `{prefix}task_progress` WHERE uuid=?;";
private static final String SELECT_PLAYER_PLAYER_PREFERENCES =
"SELECT tracked_quest_id FROM `{prefix}player_preferences` WHERE uuid=?;";
private static final String SELECT_UUID_LIST =
"SELECT DISTINCT uuid FROM `{prefix}quest_progress`;";
private static final String SELECT_KNOWN_PLAYER_QUEST_PROGRESS =
Expand All @@ -70,6 +78,8 @@ public class MySqlStorageProvider implements StorageProvider {
"INSERT INTO `{prefix}quest_progress` (uuid, quest_id, started, started_date, completed, completed_before, completion_date) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE started=?, started_date=?, completed=?, completed_before=?, completion_date=?";
private static final String WRITE_PLAYER_TASK_PROGRESS =
"INSERT INTO `{prefix}task_progress` (uuid, quest_id, task_id, completed, progress, data_type) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE completed=?, progress=?, data_type=?";
private static final String WRITE_PLAYER_PLAYER_PREFERENCES =
"INSERT INTO `{prefix}player_preferences` (uuid, tracked_quest_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE tracked_quest_id=?";

private final ConfigurationSection configuration;
private final BukkitQuestsPlugin plugin;
Expand Down Expand Up @@ -134,6 +144,7 @@ public void init() {
plugin.getQuestsLogger().debug("Creating default tables");
s.addBatch(this.statementProcessor.apply(CREATE_TABLE_QUEST_PROGRESS));
s.addBatch(this.statementProcessor.apply(CREATE_TABLE_TASK_PROGRESS));
s.addBatch(this.statementProcessor.apply(CREATE_TABLE_PLAYER_PREFERENCES));
s.addBatch(this.statementProcessor.apply(CREATE_TABLE_DATABASE_INFORMATION));

s.executeBatch();
Expand All @@ -158,14 +169,16 @@ public void shutdown() {

@Override
@Nullable
public QuestProgressFile loadProgressFile(@NotNull UUID uuid) {
public Map.Entry<QuestProgressFile, String> loadProgressFile(@NotNull UUID uuid) {
Objects.requireNonNull(uuid, "uuid cannot be null");

if (fault) return null;
Map<String, Quest> presentQuests = new HashMap<>(plugin.getQuestManager().getQuests());
boolean validateQuests = plugin.getQuestsConfig().getBoolean("options.verify-quest-exists-on-load", true);

QuestProgressFile questProgressFile = new QuestProgressFile(uuid, plugin);
String trackedQuestId = null;

try (Connection connection = hikari.getConnection()) {
plugin.getQuestsLogger().debug("Querying player " + uuid);
Map<String, QuestProgress> questProgressMap = new HashMap<>();
Expand Down Expand Up @@ -242,22 +255,33 @@ public QuestProgressFile loadProgressFile(@NotNull UUID uuid) {
for (QuestProgress questProgress : questProgressMap.values()) {
questProgressFile.addQuestProgress(questProgress);
}
try (PreparedStatement ps = connection.prepareStatement(this.statementProcessor.apply(SELECT_PLAYER_PLAYER_PREFERENCES))) {
ps.setString(1, uuid.toString());

try (ResultSet rs = ps.executeQuery()) {
if (rs.first()) {
trackedQuestId = rs.getString("tracked_quest_id");
}
}
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return questProgressFile;

return new AbstractMap.SimpleImmutableEntry<>(questProgressFile, trackedQuestId);
}

@Override
public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile questProgressFile) {
public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile questProgressFile, @Nullable String trackedQuestId) {
Objects.requireNonNull(uuid, "uuid cannot be null");
Objects.requireNonNull(questProgressFile, "questProgressFile cannot be null");

if (fault) return false;
try (Connection connection = hikari.getConnection()) {
try (PreparedStatement writeQuestProgress = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_QUEST_PROGRESS));
PreparedStatement writeTaskProgress = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_TASK_PROGRESS))) {
PreparedStatement writeTaskProgress = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_TASK_PROGRESS));
PreparedStatement writePlayerPreferences = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_PLAYER_PREFERENCES))) {

List<QuestProgress> questProgressValues = new ArrayList<>(questProgressFile.getAllQuestProgress());
for (QuestProgress questProgress : questProgressValues) {
Expand Down Expand Up @@ -318,8 +342,12 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
}
}

writePlayerPreferences.setString(1, uuid.toString());
writePlayerPreferences.setString(2, trackedQuestId);

writeQuestProgress.executeBatch();
writeTaskProgress.executeBatch();
writePlayerPreferences.executeUpdate();
}
return true;
} catch (SQLException e) {
Expand All @@ -329,7 +357,7 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
}

@Override
public @NotNull List<QuestProgressFile> loadAllProgressFiles() {
public @NotNull List<Map.Entry<QuestProgressFile, String>> loadAllProgressFiles() {
if (fault) return Collections.emptyList();

Set<UUID> uuids = new HashSet<>();
Expand All @@ -351,9 +379,9 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
return Collections.emptyList();
}

List<QuestProgressFile> files = new ArrayList<>();
List<Map.Entry<QuestProgressFile, String>> files = new ArrayList<>();
for (UUID uuid : uuids) {
QuestProgressFile file = loadProgressFile(uuid);
Map.Entry<QuestProgressFile, String> file = loadProgressFile(uuid);
if (file != null) {
files.add(file);
}
Expand All @@ -363,11 +391,11 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
}

@Override
public void saveAllProgressFiles(List<QuestProgressFile> files) {
public void saveAllProgressFiles(List<Map.Entry<QuestProgressFile, String>> files) {
if (fault) return;

for (QuestProgressFile file : files) {
saveProgressFile(file.getPlayerUUID(), file);
for (Map.Entry<QuestProgressFile, String> file : files) {
saveProgressFile(file.getKey().getPlayerUUID(), file.getKey(), file.getValue());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.leonardobishop.quests.common.player.questprogressfile.TaskProgress;
import com.leonardobishop.quests.common.quest.Quest;
import com.leonardobishop.quests.common.storage.StorageProvider;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
Expand All @@ -18,6 +19,7 @@
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -59,14 +61,16 @@ public void shutdown() {
// no impl
}

public @Nullable QuestProgressFile loadProgressFile(@NotNull UUID uuid) {
public @Nullable Map.Entry<QuestProgressFile, String> loadProgressFile(@NotNull UUID uuid) {
Objects.requireNonNull(uuid, "uuid cannot be null");

ReentrantLock lock = lock(uuid);
Map<String, Quest> presentQuests = new HashMap<>(plugin.getQuestManager().getQuests());
boolean validateQuests = plugin.getQuestsConfig().getBoolean("options.verify-quest-exists-on-load", true);

QuestProgressFile questProgressFile = new QuestProgressFile(uuid, plugin);
String trackedQuestId = null;

try {
File directory = new File(plugin.getDataFolder() + File.separator + "playerdata");
if (directory.exists() && directory.isDirectory()) {
Expand Down Expand Up @@ -101,6 +105,11 @@ public void shutdown() {
questProgressFile.addQuestProgress(questProgress);
}
}

final ConfigurationSection preferencesSection = data.getConfigurationSection("player-preferences");
if (preferencesSection != null) {
trackedQuestId = preferencesSection.getString("tracked-quest-id");
}
} else {
plugin.getQuestsLogger().debug("Player " + uuid + " does not have a quest progress file.");
}
Expand All @@ -112,10 +121,10 @@ public void shutdown() {
lock.unlock();
}

return questProgressFile;
return new AbstractMap.SimpleEntry<>(questProgressFile, trackedQuestId);
}

public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile questProgressFile) {
public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile questProgressFile, @Nullable String trackedQuestId) {
Objects.requireNonNull(uuid, "uuid cannot be null");
Objects.requireNonNull(questProgressFile, "questProgressFile cannot be null");

Expand Down Expand Up @@ -152,6 +161,9 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
}
}

// Player preferences
data.set("player-preferences.tracked-quest-id", trackedQuestId);

plugin.getQuestsLogger().debug("Writing player " + uuid + " to disk.");
try {
data.save(file);
Expand All @@ -165,8 +177,8 @@ public boolean saveProgressFile(@NotNull UUID uuid, @NotNull QuestProgressFile q
}
}

public @NotNull List<QuestProgressFile> loadAllProgressFiles() {
List<QuestProgressFile> files = new ArrayList<>();
public @NotNull List<Map.Entry<QuestProgressFile, String>> loadAllProgressFiles() {
List<Map.Entry<QuestProgressFile, String>> files = new ArrayList<>();

File directory = new File(plugin.getDataFolder() + File.separator + "playerdata");
FileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
Expand All @@ -180,7 +192,7 @@ public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
return FileVisitResult.CONTINUE;
}

QuestProgressFile file = loadProgressFile(uuid);
Map.Entry<QuestProgressFile, String> file = loadProgressFile(uuid);
if (file != null) {
files.add(file);
}
Expand All @@ -199,9 +211,9 @@ public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
}

@Override
public void saveAllProgressFiles(List<QuestProgressFile> files) {
for (QuestProgressFile file : files) {
saveProgressFile(file.getPlayerUUID(), file);
public void saveAllProgressFiles(List<Map.Entry<QuestProgressFile, String>> files) {
for (Map.Entry<QuestProgressFile, String> file : files) {
saveProgressFile(file.getKey().getPlayerUUID(), file.getKey(), file.getValue());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public static void useOtherPlayer(CommandSender sender, String name, BukkitQuest
public static void doSafeSave(QPlayer qPlayer, QuestProgressFile questProgressFile, BukkitQuestsPlugin plugin) {
if (Bukkit.getPlayer(qPlayer.getPlayerUUID()) == null) {
plugin.getScheduler().doAsync(() -> {
plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile);
plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile, qPlayer.getPlayerPreferences());
plugin.getScheduler().doSync(() -> {
if (Bukkit.getPlayer(qPlayer.getPlayerUUID()) == null) {
plugin.getPlayerManager().dropPlayer(qPlayer.getPlayerUUID());
Expand Down
Loading

0 comments on commit b3dc7ff

Please sign in to comment.