Skip to content

Commit

Permalink
- README.md changes
Browse files Browse the repository at this point in the history
- Optimized pack storing, should use less resources now
- general optimizations
  • Loading branch information
onebeastchris committed Oct 19, 2023
1 parent 0419b67 commit 1e58484
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 111 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,15 @@ Download available in the releases tab.
### Usage:
- Configure the ip/port in the config.yml. The file is located under /Geyser/extensions/PickPack/config.yml.
These are needed so the automatic transfer packet works.
- Place packs that players can opt out of in the "optOut" folder. (located in Geyser/extensions/PickPack)
- Place packs that players can opt in to in the "optIn" folder. (located in Geyser/extensions/PickPack)
- Place packs that are applied by default go in the "defaultPacks" folder. (located in Geyser/extensions/PickPack/defaultPacks)
- Place packs that players can optionally turn on go in the "optionalPacks" folder. (located in Geyser/extensions/optionalPacks)
- Reload the extension using `/pickpack reload`, or restart the server.

### Commands:
- `/pickpack menu` or `/pickpack list` - Opens the pack selection menu.
- `/pickpack reset` or `/pickpack default` - Resets the player's pack selection to the default packs.
- `/pickpack reload` - Reloads the config.yml and the packs.

### Languages:
This extension has multi-language support. However, the default language is English - to add more languages, copy the `en_US.properties` file from the /extensions/PickPack/translations folder, and translate the strings.
Then, save the file as e.g. `de_DE.properties` for German. You can select a default locale in the config.yml. Otherwise, all locales will be loaded & used automatically if a player's language matches.
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package net.onebeastchris.geyser.extension.pickpack.Util;
package net.onebeastchris.geyser.extension.pickpack;

import net.onebeastchris.geyser.extension.pickpack.PickPack;
import net.onebeastchris.geyser.extension.pickpack.Util.LanguageManager;
import org.geysermc.cumulus.component.ToggleComponent;
import org.geysermc.cumulus.form.CustomForm;
import org.geysermc.cumulus.form.ModalForm;
import org.geysermc.geyser.api.connection.GeyserConnection;
import org.geysermc.geyser.api.pack.ResourcePack;
import org.geysermc.geyser.api.pack.ResourcePackManifest;
import org.geysermc.geyser.session.GeyserSession;
import org.geysermc.geyser.text.ChatColor;

Expand Down Expand Up @@ -41,7 +41,7 @@ public void send(String... args) {
return;
}
case "clear" -> {
CompletableFuture<Void> future = PickPack.storage.setPacks(xuid, new ArrayList<>(loader.OPT_OUT.values()));
CompletableFuture<Void> future = PickPack.storage.setPacks(xuid, new ArrayList<>(loader.OPTIONAL.keySet()));
future.thenRun(() -> handle(config.useTransferPacket()));
return;
}
Expand All @@ -53,7 +53,7 @@ public void send(String... args) {
.button1(LanguageManager.getLocaleString(lang, "main.menu.filter"))
.button2(LanguageManager.getLocaleString(lang, "main.menu.select"));

form.validResultHandler((modalform, response) -> {
form.validResultHandler((modalForm, response) -> {
switch (response.clickedButtonId()) {
case 0 -> filterForm();
case 1 -> packsForm(config.useTransferPacket(), config.showPackDescription(), Filter.ALL);
Expand All @@ -66,8 +66,8 @@ public void filterForm() {
CustomForm.Builder form = CustomForm.builder()
.title(LanguageManager.getLocaleString(lang, "filter.form.title"));

if (PickPack.storage.getPacks(connection.xuid()).isEmpty()) {
form.dropdown(LanguageManager.getLocaleString(lang, "filter.button.name"), LanguageManager.getLocaleString(lang, "filter.all.packs"), LanguageManager.getLocaleString(lang, "filter.all.packs"));
if (PickPack.storage.getPackIds(connection.xuid()).isEmpty()) {
form.dropdown(LanguageManager.getLocaleString(lang, "filter.button.name"), LanguageManager.getLocaleString(lang, "filter.all.packs"));
} else {
form.dropdown(LanguageManager.getLocaleString(lang, "filter.button.name"),
LanguageManager.getLocaleString(lang, "filter.all.packs"),
Expand All @@ -81,6 +81,7 @@ public void filterForm() {
form.validResultHandler((customform, response) -> {
int filterResult = response.asDropdown(0);
boolean description = response.asToggle(1);
// 2 is the label
boolean transfer = response.asToggle(3);

switch (filterResult) {
Expand All @@ -98,16 +99,18 @@ public void packsForm(boolean transferPacket, boolean description, Filter filter
CustomForm.Builder form = CustomForm.builder()
.title(LanguageManager.getLocaleString(lang, "pack.form.title"));

form.label(LanguageManager.getLocaleString(lang, "pack.form.label").replace("%filter%", getFilterType(filter)));
form.label(String.format(LanguageManager.getLocaleString(lang, "pack.form.label"), getFilterType(filter)));

for (Map.Entry<String, String[]> entry : loader.PACKS_INFO.entrySet()) {
String name = entry.getValue()[0];
for (Map.Entry<String, ResourcePackManifest> entry : loader.PACKS_INFO.entrySet()) {
String name = entry.getValue().header().name();
boolean currentlyApplied = PickPack.storage.hasSpecificPack(xuid, entry.getKey());
boolean isVisible = filter.equals(Filter.ALL) || (filter.equals(Filter.APPLIED) && currentlyApplied) || (filter.equals(Filter.NOT_APPLIED) && !currentlyApplied);
boolean isVisible = filter.equals(Filter.ALL) ||
(filter.equals(Filter.APPLIED) && currentlyApplied) ||
(filter.equals(Filter.NOT_APPLIED) && !currentlyApplied);
if (isVisible) {
form.toggle(name, currentlyApplied);
if (description) form.label(ChatColor.ITALIC + entry.getValue()[1] + ChatColor.RESET);
tempMap.put(entry.getValue()[0], entry.getKey()); //makes it easier to get the uuid from the name later on
if (description) form.label(ChatColor.ITALIC + entry.getValue().header().description() + ChatColor.RESET);
tempMap.put(entry.getValue().header().name(), entry.getKey()); //makes it easier to get the uuid from the name later on
}
}

Expand All @@ -116,19 +119,19 @@ public void packsForm(boolean transferPacket, boolean description, Filter filter
});

form.validResultHandler((customform, response) -> {
List<ResourcePack> playerPacks = new ArrayList<>();
List<String> playerPacks = new ArrayList<>();
customform.content().forEach((component) -> {
if (component instanceof ToggleComponent) {
if (Boolean.TRUE.equals(response.next())) {
String uuid = tempMap.get(component.text());
playerPacks.add(loader.getPack(uuid));
playerPacks.add(uuid);
}
}
});

if (filter.equals(Filter.NOT_APPLIED)) {
//keep the old packs if we are filtering for not applied packs
playerPacks.addAll(PickPack.storage.getPacks(xuid));
playerPacks.addAll(PickPack.storage.getPackIds(xuid));
}

CompletableFuture<Void> future = PickPack.storage.setPacks(xuid, playerPacks);
Expand All @@ -141,8 +144,8 @@ public void packsForm(boolean transferPacket, boolean description, Filter filter

private String getPacks(String xuid) {
StringBuilder packs = new StringBuilder();
for (ResourcePack pack : PickPack.storage.getPacks(xuid)) {
String name = pack.manifest().header().name();
for (String packId : PickPack.storage.getPackIds(xuid)) {
String name = loader.PACKS_INFO.get(packId).header().name();
packs.append(" - ").append(name).append("\n");
}
if (packs.length() == 0) packs.append(LanguageManager.getLocaleString(lang, "no_packs.warning"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,19 @@
import org.geysermc.geyser.api.pack.ResourcePack;
import org.geysermc.geyser.command.GeyserCommandSource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;

public class PickPack implements Extension {
public static ResourcePackLoader loader;
public static PlayerStorage storage;
public static Path storagePath;

public static ConfigLoader.Config config;
public static ExtensionLogger logger;

private Path optInPath;
private Path optOutPath;

@Subscribe
public void onPreInitialize(GeyserPreInitializeEvent event) {
// need to load config early so commands can get their translations
Expand All @@ -46,26 +45,41 @@ public void onPreInitialize(GeyserPreInitializeEvent event) {
}

try {
LanguageManager.init(this.dataFolder().resolve("lang"));
LanguageManager.init(this.dataFolder().resolve("translations"));
} catch (Exception e) {
e.printStackTrace();
this.disable();
throw new RuntimeException("Failed to load language files!", e);
}
}

@Subscribe
public void onPostInitialize(GeyserPostInitializeEvent event) {
optInPath = this.dataFolder().resolve("optIn");
optOutPath = this.dataFolder().resolve("optOut");
Path optionalPacksPath = this.dataFolder().resolve("OptionalPacks");
Path defaultPacksPath = this.dataFolder().resolve("DefaultPacks");
storagePath = this.dataFolder().resolve("cache");

try {
// Replace opt-in and opt-out directories with new ones
if (this.dataFolder().resolve("optIn").toFile().exists()) {
Files.move(this.dataFolder().resolve("optIn"), optionalPacksPath, StandardCopyOption.REPLACE_EXISTING);
}
if (this.dataFolder().resolve("optOut").toFile().exists()) {
Files.move(this.dataFolder().resolve("optOut"), defaultPacksPath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
logger.error("Unable to migrate optIn and optOut directories!" + e.getMessage());
e.printStackTrace();
this.disable();
}

logger = this.logger();

FileSaveUtil.makeDir(optInPath, "opt-in-packs");
FileSaveUtil.makeDir(optOutPath, "opt-out-packs");
FileSaveUtil.makeDir(optionalPacksPath, "optional packs directory");
FileSaveUtil.makeDir(defaultPacksPath, "default packs directory");
FileSaveUtil.makeDir(storagePath, "storage");

loader = new ResourcePackLoader(optOutPath, optInPath);
loader = new ResourcePackLoader(optionalPacksPath, defaultPacksPath);
storage = new PlayerStorage();

logger.info("PickPack extension loaded!");
Expand All @@ -83,9 +97,6 @@ public void onPlayerResourcePackLoadEvent(SessionLoadResourcePacksEvent event) {

@Subscribe
public void CommandEvent(GeyserDefineCommandsEvent commandsEvent) {
if (!this.isEnabled()) {
return;
}
commandsEvent.register(Command.builder(this)
.name("menu")
.aliases(List.of("list"))
Expand Down Expand Up @@ -125,7 +136,7 @@ public void CommandEvent(GeyserDefineCommandsEvent commandsEvent) {
.suggestedOpOnly(true)
.permission(config.reloadPermission())
.executor((source, command, args) -> {
loader.reload(optOutPath, optInPath);
loader.reload();
try {
config = ConfigLoader.load(this, this.getClass(), ConfigLoader.Config.class);
assert config != null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public record Config(
@JsonProperty("use-transfer-packet") boolean useTransferPacket,
@JsonProperty("menu-permission") String menuPermission,
@JsonProperty("default-permission") String defaultPermission,

@JsonProperty("default-locale") String defaultLocale,
@JsonProperty("reload-permission") String reloadPermission,
@JsonProperty("translations") Translations translations
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,42 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static net.onebeastchris.geyser.extension.pickpack.PickPack.loader;
import static net.onebeastchris.geyser.extension.pickpack.PickPack.logger;

public class FileSaveUtil {
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void save(List<ResourcePack> list, String xuid) {

public static void save(List<String> list, String xuid) {
Path filepath = PickPack.storagePath.resolve(xuid + ".txt");
if (filepath.toFile().exists()) {
filepath.toFile().delete();
}
List<String> packUUIDs = new ArrayList<>();
for (ResourcePack pack : list) {
packUUIDs.add(pack.manifest().header().uuid().toString());
}
saveToFile(packUUIDs, filepath);
saveToFile(list, filepath);
}

public static List<ResourcePack> load(Path filepath) {
List<String> packUUIDs = readFromFile(filepath);
List<ResourcePack> list = new ArrayList<>();
for (String pack : packUUIDs) {
ResourcePack resourcePack = loader.getPack(pack);
if (resourcePack != null) {
list.add(resourcePack);
} else {
logger.debug("Could not find pack with UUID " + pack + " in either folder! We are not loading it.");
}
public static List<String> load(Path filepath) {
List<String> packs = readFromFile(filepath);
AtomicBoolean changed = new AtomicBoolean(false);
packs.forEach(packId -> {
ResourcePack pack = loader.getPack(packId);
if (pack == null) {
logger.debug("Could not find pack with UUID " + packId + " in cache, removing from file");
packs.remove(packId);
changed.set(true);
}
return list;
});
if (changed.get()) {
saveToFile(packs, filepath);
}
return packs;
}

public static void saveToFile(List<String> packs, Path filepath) {
if (filepath.toFile().exists()) {
if (!filepath.toFile().delete()) {
logger.error("Failed to delete " + filepath.getFileName());
return;
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filepath.toFile()))) {
for (String pack : packs) {
writer.write(pack);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
import java.util.*;

public class LanguageManager {

private static final String EN_US_PROPERTIES = "en_us.properties";
public static String DEFAULT_LOCALE;
public static String DEFAULT_LOCALE = "en_us";
public static final String EN_US_PROPERTIES = "en_US.properties";
public static Map<String, Properties> LOCALE_PROPERTIES = new HashMap<>();

@SuppressWarnings("resource")
Expand All @@ -33,15 +32,17 @@ public static void init(Path languageFolder) throws IOException {
throw new RuntimeException("Failed to list language files!", e);
}

DEFAULT_LOCALE = PickPack.config.defaultLocale() == null ? EN_US_PROPERTIES : PickPack.config.defaultLocale() + ".properties";
if (PickPack.config.defaultLocale() != null) {
DEFAULT_LOCALE = PickPack.config.defaultLocale().replace(".properties", "");
}

//Check: Does default locale exist? Fallback to en_us if it does not.
if (languageFiles.stream().noneMatch(path -> path.getFileName().toString().equalsIgnoreCase(DEFAULT_LOCALE + ".properties"))) {

//Check: Does english exist?
String currentDefaultLocale = DEFAULT_LOCALE;
if (languageFiles.stream().noneMatch(path -> path.getFileName().toString().equalsIgnoreCase(currentDefaultLocale))) {
// Check: Is default locale not english?
if (!DEFAULT_LOCALE.equalsIgnoreCase(EN_US_PROPERTIES)) {
if (!DEFAULT_LOCALE.equalsIgnoreCase("en_us")) {
PickPack.logger.warning("Default configured locale " + DEFAULT_LOCALE + " not found, falling back to en_us.properties");
DEFAULT_LOCALE = EN_US_PROPERTIES;
DEFAULT_LOCALE = "en_us";
}

try (InputStream input = PickPack.class.getClassLoader().getResourceAsStream(EN_US_PROPERTIES)) {
Expand Down Expand Up @@ -69,6 +70,8 @@ public static void init(Path languageFolder) throws IOException {
localeProp.load(reader);
} catch (Exception e) {
throw new AssertionError("Failed to load locale " + fileName);
} finally {
localeStream.close();
}

// Insert the locale into the mappings, all lowercase
Expand Down
Loading

0 comments on commit 1e58484

Please sign in to comment.