Remove UUIDFetcher to avoid confusion, see #343

This commit is contained in:
HappyPikachu 2018-04-13 19:01:20 -04:00
parent 995a7d8839
commit ce485ae1ea
3 changed files with 1 additions and 249 deletions

View File

@ -1,114 +0,0 @@
/*******************************************************************************************************
* Continued by FlyingPikachu/HappyPikachu with permission from _Blackvein_. All rights reserved.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************************************/
package com.evilmidget38;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
return connection;
}
private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Collections.singletonList(name)).call().get(name);
}
}

View File

@ -22,7 +22,6 @@ import java.util.Map.Entry;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;

View File

@ -15,7 +15,6 @@ package me.blackvein.quests;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -24,7 +23,6 @@ import java.lang.reflect.Constructor;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
@ -52,7 +50,6 @@ import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
@ -80,7 +77,6 @@ import org.bukkit.potion.PotionEffectType;
import com.codisimus.plugins.phatloots.PhatLoots; import com.codisimus.plugins.phatloots.PhatLoots;
import com.codisimus.plugins.phatloots.PhatLootsAPI; import com.codisimus.plugins.phatloots.PhatLootsAPI;
import com.evilmidget38.UUIDFetcher;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SkillType; import com.gmail.nossr50.datatypes.skills.SkillType;
@ -126,7 +122,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
public boolean allowCommandsForNpcQuests = false; public boolean allowCommandsForNpcQuests = false;
public boolean allowQuitting = true; public boolean allowQuitting = true;
public boolean askConfirmation = true; public boolean askConfirmation = true;
public boolean convertData = false;
public boolean genFilesOnJoin = true; public boolean genFilesOnJoin = true;
public boolean ignoreLockedQuests = false; public boolean ignoreLockedQuests = false;
public int killDelay = 0; public int killDelay = 0;
@ -294,16 +289,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
getLogger().log(Level.INFO, "" + events.size() + " Event(s) loaded."); getLogger().log(Level.INFO, "" + events.size() + " Event(s) loaded.");
getLogger().log(Level.INFO, "" + Lang.getPhrases() + " Phrase(s) loaded."); getLogger().log(Level.INFO, "" + Lang.getPhrases() + " Phrase(s) loaded.");
questers.putAll(getOnlineQuesters()); questers.putAll(getOnlineQuesters());
if (convertData) {
convertQuesters();
FileConfiguration config = getConfig();
config.set("convert-data-on-startup", false);
try {
config.save(new File(Quests.this.getDataFolder(), "config.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
} }
}, 5L); }, 5L);
} }
@ -512,7 +497,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
allowCommandsForNpcQuests = config.getBoolean("allow-command-quests-with-npcs", false); allowCommandsForNpcQuests = config.getBoolean("allow-command-quests-with-npcs", false);
allowQuitting = config.getBoolean("allow-quitting", true); allowQuitting = config.getBoolean("allow-quitting", true);
askConfirmation = config.getBoolean("ask-confirmation", true); askConfirmation = config.getBoolean("ask-confirmation", true);
convertData = config.getBoolean("convert-data-on-startup", false);
genFilesOnJoin = config.getBoolean("generate-files-on-join", true); genFilesOnJoin = config.getBoolean("generate-files-on-join", true);
ignoreLockedQuests = config.getBoolean("ignore-locked-quests", false); ignoreLockedQuests = config.getBoolean("ignore-locked-quests", false);
killDelay = config.getInt("kill-delay", 600); killDelay = config.getInt("kill-delay", 600);
@ -1364,18 +1348,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
return true; return true;
} }
} }
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("convert")) {
if (cs instanceof ConsoleCommandSender) {
convertQuesters();
} else {
cs.sendMessage(ChatColor.YELLOW + Lang.get("questsUnknownCommand"));
return true;
}
} else {
cs.sendMessage(ChatColor.YELLOW + Lang.get("consoleError"));
return true;
}
} else { } else {
cs.sendMessage(ChatColor.YELLOW + Lang.get("consoleError")); cs.sendMessage(ChatColor.YELLOW + Lang.get("consoleError"));
return true; return true;
@ -1453,8 +1425,7 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
UUID id = UUID.fromString(s); UUID id = UUID.fromString(s);
s = Bukkit.getOfflinePlayer(id).getName(); s = Bukkit.getOfflinePlayer(id).getName();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
getLogger().warning("Invalid file name \"" + s + "\"in /data folder. Replace with player UUID" getLogger().warning("File name \"" + s + "\"in /data folder is not a valid player UUID!");
+ " or start the plugin with the \"convert-data-on-startup\" enabled in config.yml");
break; break;
} }
numPrinted++; numPrinted++;
@ -2114,13 +2085,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
break; break;
} }
} }
try {
if (id == null) {
id = UUIDFetcher.getUUIDOf(name);
}
} catch (Exception e) {
// Do nothing
}
if (id != null) { if (id != null) {
quester = getQuester(id); quester = getQuester(id);
} }
@ -4146,103 +4110,6 @@ public class Quests extends JavaPlugin implements ConversationAbandonedListener
} }
} }
public void convertQuesters() {
int numQuesters = 0;
int succeeded = 0;
int failed = 0;
final File dataFolder = new File(this.getDataFolder(), "data" + File.separator);
final File oldDataFolder = new File(this.getDataFolder(), "data" + File.separator + "old" + File.separator);
if (oldDataFolder.exists() == false || oldDataFolder.exists() && oldDataFolder.isDirectory() == false) {
oldDataFolder.mkdir();
}
if (dataFolder.exists() && dataFolder.isDirectory()) {
final File[] files = dataFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return dir.getPath().equals(dataFolder.getPath()) && name.endsWith(".yml");
}
});
if (files != null) {
numQuesters = files.length;
if (numQuesters > 0) {
final ArrayList<String> names = new ArrayList<String>();
getLogger().info("Gathering Quester information...");
for (int i = 0; i < numQuesters; i++) {
final File file = files[i];
final File old = new File(oldDataFolder, file.getName());
final String name = file.getName().substring(0, file.getName().length() - 4);
final FileConfiguration config = new YamlConfiguration();
try {
config.load(file);
config.save(old);
config.set("lastKnownName", name);
config.save(file);
} catch (Exception e) {
failed++;
}
names.add(name.toLowerCase());
succeeded++;
}
getLogger().info("Completed: " + succeeded + " Success(es). " + failed + " Failure(s). " + numQuesters + " Total.");
getLogger().info("Preparing to convert data.");
Bukkit.getScheduler().runTaskAsynchronously(this, new Runnable() {
@Override
public void run() {
getLogger().info("Done. Converting data...");
int converted = 0;
int failed = 0;
final UUIDFetcher fetcher = new UUIDFetcher(names);
final Map<String, UUID> idMap;
try {
idMap = fetcher.call();
} catch (Exception ex) {
getLogger().severe("Error retrieving data from Mojang account database. Error log:");
ex.printStackTrace();
return;
}
for (Entry<String, UUID> entry : idMap.entrySet()) {
try {
final File found = new File(dataFolder, entry.getKey() + ".yml");
final File copy = new File(dataFolder, entry.getValue() + ".yml");
final FileConfiguration config = new YamlConfiguration();
final FileConfiguration newConfig = new YamlConfiguration();
config.load(found);
if (config.contains("currentQuest")) {
LinkedList<String> currentQuests = new LinkedList<String>();
currentQuests.add(config.getString("currentQuest"));
LinkedList<Integer> currentStages = new LinkedList<Integer>();
currentStages.add(config.getInt("currentStage"));
newConfig.set("currentQuests", currentQuests);
newConfig.set("currentStages", currentStages);
newConfig.set("hasJournal", false);
newConfig.set("lastKnownName", entry.getKey());
ConfigurationSection dataSec = Quester.getLegacyQuestData(config, config.getString("currentQuest"));
newConfig.set("questData", dataSec);
}
newConfig.save(copy);
found.delete();
converted++;
} catch (Exception ex) {
failed++;
}
}
getLogger().info("Conversion completed: " + converted + " Converted. " + failed + " Failed.");
getLogger().info("Old data files stored in "
+ File.separator + "Quests" + File.separator + "data" + File.separator + "old");
}
});
} else {
getLogger().info("No Questers to convert!");
}
}
} else {
getLogger().info("Data folder does not exist!");
}
}
public void addToBlacklist(UUID id) { public void addToBlacklist(UUID id) {
List<String> blacklist = getConfig().getStringList("quester-blacklist"); List<String> blacklist = getConfig().getStringList("quester-blacklist");
if (!blacklist.contains(id.toString())) { if (!blacklist.contains(id.toString())) {