Skip to content

Commit

Permalink
SimpleSkins
Browse files Browse the repository at this point in the history
  • Loading branch information
Leymooo committed Dec 30, 2018
0 parents commit e8f7089
Show file tree
Hide file tree
Showing 9 changed files with 755 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target/
.idea/
*.iml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Leymooo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
86 changes: 86 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

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

<name>SimpleSkins</name>
<url>https://github.com/Leymooo/SimpleSkins</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<!-- Disable tests -->
<skipTests>true</skipTests>
<maven.test.skip>true</maven.test.skip>
</properties>

<repositories>
<repository>
<id>velocity-repo</id>
<url>https://repo.velocitypowered.com/snapshots/</url>
</repository>
<repository>
<id>bungeecord-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>

<dependencies>
<dependency>
<groupId>com.velocitypowered</groupId>
<artifactId>velocity-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-config</artifactId>
<version>1.13-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<defaultGoal>clean package</defaultGoal>
<finalName>SimpleSkins</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>

</project>
176 changes: 176 additions & 0 deletions src/main/java/ru/leymooo/simpleskins/SimpleSkins.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package ru.leymooo.simpleskins;

import ru.leymooo.simpleskins.utils.RoundIterator;
import ru.leymooo.simpleskins.utils.DataBaseUtils;
import ru.leymooo.simpleskins.utils.SkinUtils;
import com.google.gson.JsonSyntaxException;
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;
import java.io.InputStream;
import java.nio.file.Files;
import org.slf4j.Logger;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import net.kyori.text.serializer.ComponentSerializers;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import ru.leymooo.simpleskins.command.SkinCommand;

@Plugin(id = "simpleskins", name = "SimpleSkins", version = "1.0.0",
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 final ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private RoundIterator<SkinUtils.FetchResult> defaultSkins;
private Configuration config;
private DataBaseUtils dataBaseUtils;

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

@Subscribe
public void onProxyInitialize(ProxyInitializeEvent event) {
logger.info("Enabling SimspleSkins version 1.0.0");

if (!loadConfig()) {
server.getEventManager().unregisterListeners(this);
logger.error("Config is not loaded. Plugin will be inactive");
return;
}
initDefaultSkins();
this.dataBaseUtils = new DataBaseUtils(this);

this.server.getCommandManager().register(new SkinCommand(this), "skin");
//Config
//Command
}

@Subscribe
public void onShutDown(ProxyShutdownEvent ev) {

}

@Subscribe
public void onGameProfileRequest(GameProfileRequestEvent event) {
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());
if (skin != null) {
event.setGameProfile(skinUtils.applySkin(event.getGameProfile(), skin.getProperty()));
if (!maybeCached.isPresent()) {
service.execute(() -> {
dataBaseUtils.saveUser(event.getUsername(), skin);
});
}
}
}
}

private boolean loadConfig() {
File config = new File(dataDirectory.toFile(), "config.yml");
config.getParentFile().mkdir();
try {
if (!config.exists()) {
try (InputStream in = SimpleSkins.class.getClassLoader().getResourceAsStream("config.yml")) {
Files.copy(in, config.toPath());
}
}
this.config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(config);
} catch (IOException ex) {
logger.error("Can not load or save config", ex);
return false;
}
return true;
}

private void initDefaultSkins() {
logger.info("Loading default skins");
List<SkinUtils.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())))));
}
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException ex) {
}
}
this.defaultSkins = new RoundIterator<>(skins);
logger.info("Default skins loaded");
}

public Optional<SkinUtils.FetchResult> fetchSkin(Optional<Player> player, String name, boolean logError, boolean fromDatabase) {
try {
return fromDatabase ? dataBaseUtils.getProperty(name) : Optional.of(skinUtils.fetchSkin(name));
} 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(ComponentSerializers.LEGACY.deserialize(config.getString("messages.skin-not-found"), '&')));
return Optional.empty();
}

public Logger getLogger() {
return logger;
}

public ProxyServer getProxyServer() {
return server;
}

public Configuration getConfig() {
return config;
}

public ExecutorService getExecutorService() {
return service;
}

public Path getDataDirectory() {
return dataDirectory;
}

public DataBaseUtils getDataBaseUtils() {
return dataBaseUtils;
}

public SkinUtils getSkinUtils() {
return skinUtils;
}

}
81 changes: 81 additions & 0 deletions src/main/java/ru/leymooo/simpleskins/command/SkinCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package ru.leymooo.simpleskins.command;

import com.velocitypowered.api.command.Command;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import net.kyori.text.serializer.ComponentSerializers;
import ru.leymooo.simpleskins.SimpleSkins;
import ru.leymooo.simpleskins.utils.SkinUtils;

/**
*
* @author mikim
*/
public class SkinCommand implements Command {

private final SimpleSkins plugin;
private final Set<CommandSource> working = new HashSet<>();

public SkinCommand(SimpleSkins plugin) {
this.plugin = plugin;
}

@Override
public void execute(CommandSource cs, String[] args) {
if (plugin.getConfig().getBoolean("use-permission") && !cs.hasPermission("simpleskins.skin")) {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.no-permission"), '&'));
return;
}
if (cs instanceof Player) {
if (args.length == 0) {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.help"), '&'));
return;
}
if (working.contains(cs)) {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.working"), '&'));
return;
}
Player player = (Player) cs;
working.add(cs);
if (args[0].equalsIgnoreCase("update")) {
plugin.getExecutorService().execute(() -> {
Optional<UUID> uuid = plugin.getDataBaseUtils().getUuid(player.getUsername());
if (uuid.isPresent()) {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.fetching"), '&'));
Optional<SkinUtils.FetchResult> newSkin = plugin.fetchSkin(Optional.of(player), uuid.get().toString(), false, false);
newSkin.ifPresent(skin -> {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.skin-changed"), '&'));
plugin.getSkinUtils().applySkin(player, skin.getProperty());
});
} else {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.skin-update-error"), '&'));
}
working.remove(cs);
});
return;
}
plugin.getExecutorService().execute(() -> {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.fetching"), '&'));
Optional<SkinUtils.FetchResult> newSkin = plugin.fetchSkin(Optional.of(player),
args[0].equalsIgnoreCase("reset") ? player.getUsername() : args[0], false, false);
newSkin.ifPresent(skin -> {
cs.sendMessage(ComponentSerializers.LEGACY.deserialize(plugin.getConfig().getString("messages.skin-changed"), '&'));
plugin.getDataBaseUtils().saveUser(player.getUsername(), skin);
plugin.getSkinUtils().applySkin(player, skin.getProperty());

});
working.remove(cs);
});
}
}

@Override
public boolean hasPermission(CommandSource cs, String[] strings) {
return true;
}

}
Loading

0 comments on commit e8f7089

Please sign in to comment.