Skip to content

Commit

Permalink
refactor some code, use api.ashcon.app if rate limited
Browse files Browse the repository at this point in the history
  • Loading branch information
Leymooo committed Jan 15, 2019
1 parent 2043e92 commit 33cc61b
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 101 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>ru.leymooo</groupId>
<artifactId>simpleskins</artifactId>
<version>1.1</version>
<version>1.2</version>
<packaging>jar</packaging>

<name>SimpleSkins</name>
Expand Down
89 changes: 28 additions & 61 deletions src/main/java/ru/leymooo/simpleskins/SimpleSkins.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package ru.leymooo.simpleskins;

import ru.leymooo.simpleskins.utils.UuidFetchCache;
import ru.leymooo.simpleskins.utils.RoundIterator;
import ru.leymooo.simpleskins.utils.DataBaseUtils;
import ru.leymooo.simpleskins.utils.SkinUtils;
import com.google.gson.JsonSyntaxException;
import ru.leymooo.simpleskins.utils.SkinFetcher;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.GameProfileRequestEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import java.io.File;
import java.io.IOException;
Expand All @@ -23,7 +22,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Expand All @@ -36,28 +34,31 @@
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import ru.leymooo.simpleskins.command.SkinCommand;
import ru.leymooo.simpleskins.utils.SkinApplier;
import ru.leymooo.simpleskins.utils.SkinFetcher.FetchResult;

@Plugin(id = "simpleskins", name = "SimpleSkins", version = "1.1",
@Plugin(id = "simpleskins", name = "SimpleSkins", version = "1.2",
description = "Simple skins restorer plugin for velocity",
authors = "Leymooo")
public class SimpleSkins {

private final ProxyServer server;
private final Logger logger;
private final Path dataDirectory;
private final SkinUtils skinUtils;
private SkinFetcher skinFetcher;
private final ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private final UuidFetchCache uuidCache = new UuidFetchCache();
private RoundIterator<SkinUtils.FetchResult> defaultSkins;
private final DataBaseUtils dataBaseUtils;
private RoundIterator<SkinFetcher.FetchResult> defaultSkins;
private Configuration config;
private DataBaseUtils dataBaseUtils;

@Inject
public SimpleSkins(ProxyServer server, Logger logger, @DataDirectory Path userConfigDirectory) {
logger.info("Loading SimpleSkins");
this.server = server;
this.logger = logger;
this.dataDirectory = userConfigDirectory;
this.skinUtils = new SkinUtils(this);
this.dataBaseUtils = new DataBaseUtils(this);
logger.info("SimpleSkins loaded");
}

@Subscribe
Expand All @@ -69,9 +70,9 @@ public void onProxyInitialize(ProxyInitializeEvent event) {
logger.error("Config is not loaded. Plugin will be inactive");
return;
}
initDefaultSkins();
this.dataBaseUtils = new DataBaseUtils(this);
this.skinFetcher = new SkinFetcher(this, dataBaseUtils, new UuidFetchCache(this));

initDefaultSkins();
this.server.getCommandManager().register(new SkinCommand(this), "skin");
logger.info("SimpleSkins enabled");
}
Expand All @@ -90,13 +91,18 @@ public void onShutDown(ProxyShutdownEvent ev) {

@Subscribe
public void onGameProfileRequest(GameProfileRequestEvent event) {
Optional<FetchResult> maybeCached = skinFetcher.getPlayerSkinFromDatabase(event.getUsername());

if (maybeCached.isPresent() && event.isOnlineMode()) {
event.setGameProfile(SkinApplier.createProfileWithSkin(event.getGameProfile(), maybeCached.get().getProperty()));
return;
}
if (!event.isOnlineMode()) {
Optional<SkinUtils.FetchResult> maybeCached = fetchSkin(Optional.empty(), event.getUsername(), false, true);
Optional<SkinUtils.FetchResult> toSet = maybeCached.isPresent()
? maybeCached : fetchSkin(Optional.empty(), event.getUsername(), false, false);
SkinUtils.FetchResult skin = toSet.orElse(defaultSkins.next());
Optional<FetchResult> toSet = maybeCached.isPresent()
? maybeCached : skinFetcher.fetchSkin(event.getUsername(), true);
FetchResult skin = toSet.orElse(defaultSkins.next());
if (skin != null) {
event.setGameProfile(skinUtils.applySkin(event.getGameProfile(), skin.getProperty()));
event.setGameProfile(SkinApplier.createProfileWithSkin(event.getGameProfile(), skin.getProperty()));
if (!maybeCached.isPresent()) {
service.execute(() -> {
dataBaseUtils.saveUser(event.getUsername(), skin);
Expand Down Expand Up @@ -125,11 +131,11 @@ private boolean loadConfig() {

private void initDefaultSkins() {
logger.info("Loading default skins");
List<SkinUtils.FetchResult> skins = new ArrayList<>();
List<SkinFetcher.FetchResult> skins = new ArrayList<>();
List<Future<?>> futures = new ArrayList<>();
for (String user : config.getStringList("default-skins")) {
futures.add(service.submit(() -> fetchSkin(Optional.empty(), user, true, false)
.ifPresent(skin -> skins.add(new SkinUtils.FetchResult(null, skin.getProperty())))));
futures.add(service.submit(() -> skinFetcher.fetchSkin(user, false)
.ifPresent(skin -> skins.add(new SkinFetcher.FetchResult(null, skin.getProperty())))));
}
for (Future<?> future : futures) {
try {
Expand All @@ -142,36 +148,6 @@ private void initDefaultSkins() {
logger.info("Default skins loaded");
}

public Optional<SkinUtils.FetchResult> fetchSkin(Optional<Player> player, String name, boolean logError, boolean fromDatabase) {
try {
if (fromDatabase) {
return dataBaseUtils.getProperty(name);
}
UUID uuid = (uuid = checkUUID(name)) == null ? skinUtils.fetchUUID(name) : uuid;
if (uuidCache.isWorking(uuid)) {
player.ifPresent(pl -> pl.sendMessage(deserialize("messages.working")));
return Optional.empty();
}
uuidCache.addWorking(uuid);
try {
Optional<SkinUtils.FetchResult> result = uuidCache.getIfCached(uuid);
result = result.isPresent() ? result : Optional.of(skinUtils.fetchSkin(uuid));
uuidCache.cache(result.get());
return result;
} finally {
uuidCache.removeWorking(uuid);
}
} catch (SkinUtils.UserNotFoundExeption ex) {
if (logError) {
logger.error("Can not fetch skin for '{}': {}", name, ex.getMessage());
}
} catch (IOException | JsonSyntaxException ex) {
logger.error("Can not fetch skin", ex);
}
player.ifPresent(pl -> pl.sendMessage(deserialize("messages.skin-not-found")));
return Optional.empty();
}

public Logger getLogger() {
return logger;
}
Expand All @@ -196,20 +172,11 @@ public DataBaseUtils getDataBaseUtils() {
return dataBaseUtils;
}

public SkinUtils getSkinUtils() {
return skinUtils;
public SkinFetcher getSkinFetcher() {
return skinFetcher;
}

public Component deserialize(String configKey) {
return ComponentSerializers.LEGACY.deserialize(config.getString(configKey), '&');
}

private UUID checkUUID(String toCheck) {
try {
return UUID.fromString(toCheck);
} catch (IllegalArgumentException ex) {
return null;
}
}

}
14 changes: 7 additions & 7 deletions src/main/java/ru/leymooo/simpleskins/command/SkinCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import java.util.UUID;
import net.kyori.text.serializer.ComponentSerializers;
import ru.leymooo.simpleskins.SimpleSkins;
import ru.leymooo.simpleskins.utils.SkinUtils;
import ru.leymooo.simpleskins.utils.SkinApplier;
import ru.leymooo.simpleskins.utils.SkinFetcher;

/**
*
Expand Down Expand Up @@ -46,10 +47,10 @@ public void execute(CommandSource cs, String[] args) {
Optional<UUID> uuid = plugin.getDataBaseUtils().getUuid(player.getUsername());
if (uuid.isPresent()) {
cs.sendMessage(plugin.deserialize("messages.fetching"));
Optional<SkinUtils.FetchResult> newSkin = plugin.fetchSkin(Optional.of(player), uuid.get().toString(), false, false);
Optional<SkinFetcher.FetchResult> newSkin = plugin.getSkinFetcher().fetchSkin(player, uuid.get());
newSkin.ifPresent(skin -> {
cs.sendMessage(plugin.deserialize("messages.skin-changed"));
plugin.getSkinUtils().applySkin(player, skin.getProperty());
SkinApplier.applySkin(player, skin.getProperty());
});
} else {
cs.sendMessage(plugin.deserialize("messages.skin-update-error"));
Expand All @@ -60,12 +61,11 @@ public void execute(CommandSource cs, String[] args) {
}
plugin.getExecutorService().execute(() -> {
cs.sendMessage(plugin.deserialize("messages.fetching"));
Optional<SkinUtils.FetchResult> newSkin = plugin.fetchSkin(Optional.of(player),
args[0].equalsIgnoreCase("reset") ? player.getUsername() : args[0], false, false);
Optional<SkinFetcher.FetchResult> newSkin = plugin.getSkinFetcher().fetchSkin(player, args[0].equalsIgnoreCase("reset") ? player.getUsername() : args[0]);
newSkin.ifPresent(skin -> {
cs.sendMessage(plugin.deserialize("messages.skin-changed"));
plugin.getDataBaseUtils().saveUser(player.getUsername(), skin);
plugin.getSkinUtils().applySkin(player, skin.getProperty());
SkinApplier.applySkin(player, skin.getProperty());
cs.sendMessage(plugin.deserialize("messages.skin-changed"));

});
working.remove(cs);
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/ru/leymooo/simpleskins/utils/DataBaseUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ private void connect() {
}
}

public Optional<SkinUtils.FetchResult> getProperty(String name) {
public Optional<SkinFetcher.FetchResult> getProperty(String name) {
try (PreparedStatement ps = connection.prepareStatement(SELECT_SKIN_SQL)) {
ps.setString(1, name.toLowerCase());
ResultSet set = ps.executeQuery();
if (set.next()) {
return Optional.of(new SkinUtils.FetchResult(set.getObject(1, UUID.class),
return Optional.of(new SkinFetcher.FetchResult(set.getObject(1, UUID.class),
new GameProfile.Property("textures", set.getString(2), set.getString(3))));
}
} catch (SQLException ex) {
Expand All @@ -74,7 +74,7 @@ public Optional<UUID> getUuid(String name) {
return Optional.empty();
}

public void saveUser(String name, SkinUtils.FetchResult result) {
public void saveUser(String name, SkinFetcher.FetchResult result) {
try (PreparedStatement ps = connection.prepareStatement(SELECT_NAME_SQL)) {
ps.setString(1, name.toLowerCase());
ResultSet set = ps.executeQuery();
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/ru/leymooo/simpleskins/utils/SkinApplier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.leymooo.simpleskins.utils;

import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.util.GameProfile;
import java.util.ArrayList;
import java.util.List;

public class SkinApplier {

public static GameProfile createProfileWithSkin(GameProfile original, GameProfile.Property toApply) {
List<GameProfile.Property> properties = createProperties(original.getProperties(), toApply);
return new GameProfile(original.getId(), original.getName(), properties);
}

public static void applySkin(Player player, GameProfile.Property property) {
player.setGameProfileProperties(createProperties(player.getGameProfileProperties(), property));
}

private static List<GameProfile.Property> createProperties(List<GameProfile.Property> original, GameProfile.Property property) {
List<GameProfile.Property> properties = new ArrayList<>(original);
boolean applied = false;
for (int i = 0; i < properties.size(); i++) {
GameProfile.Property lproperty = properties.get(i);
if ("textures".equals(lproperty.getName())) {
properties.set(i, property);
applied = true;
}
}
if (!applied) {
properties.add(property);
}
return properties;
}
}
Loading

0 comments on commit 33cc61b

Please sign in to comment.