Archived
Private
Public Access
1
0

Initial commit

This commit is contained in:
2022-09-04 12:45:01 +02:00
commit f4a01d6a69
11601 changed files with 4206660 additions and 0 deletions

View File

@@ -0,0 +1,303 @@
/*
* Copyright (C) 2016 Zombie_Striker
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package me.zombie_striker.tts;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.zombie_striker.tts.data.*;
import me.zombie_striker.tts.util.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import org.bukkit.plugin.java.JavaPlugin;
public class CoreTTS extends JavaPlugin implements Listener {
public HashMap<StoreableStrings, Word> words = new HashMap<StoreableStrings, Word>();
public HashMap<Long, PlayObject> map = new HashMap<Long, PlayObject>();
HashMap<Long, Integer> mapP = new HashMap<Long, Integer>();
HashMap<String, List<UUID>> bannedG = new HashMap<String, List<UUID>>();
HashMap<UUID, String> groups = new HashMap<UUID, String>();
HashMap<UUID, Integer> lType = new HashMap<UUID, Integer>();
public HashMap<UUID, Integer> pitch = new HashMap<UUID, Integer>();
String prefix = ChatColor.RED + "[TTS]" + ChatColor.RESET;
// public static String RES = "https://dev.bukkit.org/media/files/956/355/TextToSpeech.zip";
public static String RES = "https://dev.bukkit.org/projects/texttospeach/files/956355/download";
private long tick = 0;
private File langFile = null;
private int speed;
@SuppressWarnings("deprecation")
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
// Do it afterwords so words can be overwritten
try {
langFile = new File(this.getDataFolder(), "lang.txt");
LangFile.verify(langFile);
BufferedReader br = new BufferedReader(new FileReader(langFile));
for (int i = 0; i < 2000; i++) {
String word = br.readLine();
if (word == null)
break;
if (word.trim().length() == 0)
continue;
if (word.trim().startsWith("+"))
continue;
StoreableStrings ss = StoreableStrings.getStoreableString(word
.split(" : ")[0].trim());
words.put(ss, new Word(word.split(" : ")[1].trim()));
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
for (Player p : Bukkit.getOnlinePlayers()) {
initG(p);
}
for (String group : getConfig().getStringList("group.list")) {
List<UUID> pp = new ArrayList<UUID>();
bannedG.put(group, pp);
for (String uuid : getConfig().getStringList(
"group." + group + ".banned")) {
pp.add(UUID.fromString(uuid));
}
}
TTSCommand ttsc = new TTSCommand(this);
getCommand("tts").setExecutor(ttsc);
getCommand("tts").setTabCompleter(ttsc);
if(!getConfig().contains("SpeechDelay")){
getConfig().set("SpeechDelay", 3);
saveConfig();
}
speed = getConfig().getInt("SpeechDelay");
Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, new Runnable() {
public void run() {
tick();
if (!map.containsKey(getTick()))
return;
PlayObject po = map.get(getTick());
if (po == null)
return;
Location locationOfVoice = po.locationOfVoice;
for (UUID uuidS : groups.keySet()) {
Player p = Bukkit.getPlayer(uuidS);
if ((po.sound.get(locationOfVoice) == null))
System.out
.println(" Owner is null. This should not be happening.");
if (p != null) {
Location loc = null;
if (lType.get(uuidS) == 1) {// local
loc = locationOfVoice;
// po.sound.get(owner).chars + "", 1, 0.5f +
// ((float) po.pitch.get(owner) / 10));
} else if (lType.get(uuidS) == 2) {// world
if (locationOfVoice.getWorld().equals(p.getWorld()))
loc = p.getLocation();
// PlaySound.playSound(p, p.getLocation(),
// po.sound.get(owner).chars + "", 1, 0.5f +
// ((float) po.pitch.get(owner) / 10));
} else if (lType.get(uuidS) == 3) {// global
loc = p.getLocation();
// PlaySound.playSound(p, p.getLocation(),
// po.sound.get(owner).chars + "", 1, 0.5f +
// ((float) po.pitch.get(owner) / 10));
}
if (loc != null) {
p.playSound(
locationOfVoice,
po.sound.get(locationOfVoice).chars + "",
3,
0.5f + ((float) po.pitch.get(locationOfVoice) / 10));
if (map.containsKey(getTick()+1)) {
PlayObject po2 = map.get(getTick() + 1);
if ((po2.sound.get(locationOfVoice) != null)) {
int sP = po2.sound.get(locationOfVoice).pitch;
String extSound = "";
if(sP==0&&po.sound.get(locationOfVoice).pitch==0)extSound="xaa";
if(sP==1&&po.sound.get(locationOfVoice).pitch==0)extSound="xab";
if(sP==0&&po.sound.get(locationOfVoice).pitch==1)extSound="xba";
p.playSound(locationOfVoice,
extSound,
3, 0.5f + ((float) po.pitch
.get(locationOfVoice) / 10));
}
}
}
}
}
map.remove(getTick());
}
}, 0, speed);
if (!getConfig().contains("auto-update")) {
getConfig().set("auto-update", true);
saveConfig();
}
new Updater(this, 103001, getConfig().getBoolean("auto-update"));
// bStats metrics
Metrics met = new Metrics(this);
met.addCustomChart(new Metrics.SimplePie("updater-active") {
@Override
public String getValue() {
return String.valueOf(getConfig().getBoolean("auto-update"));
}
});
}
@Override
public void onDisable() {
reloadConfig();
LangFile.words = null;
CoreTTS.RES = null;
for (UUID k : groups.keySet()) {
int l = lType.get(k);
String g = groups.get(k);
getConfig().set("users." + k.toString() + ".g", g);
getConfig().set("users." + k.toString() + ".l", l);
}
for (String group : bannedG.keySet()) {
List<String> ls = new ArrayList<String>();
for (UUID uuid : bannedG.get(group)) {
ls.add(uuid.toString());
}
getConfig().set("group." + group + ".banned", ls);
}
List<String> groups = new ArrayList<String>(bannedG.keySet());
getConfig().set("group.list", groups);
saveConfig();
}
@EventHandler
public void onJoin(final PlayerJoinEvent e) {
initG(e.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable(){
public void run(){
TalkUtil.speakOut("Text To Speech has been activated", e.getPlayer());
}
}, 10L);
}
@EventHandler
public void onInteract(PlayerInteractEvent e){
if(e.getClickedBlock()!=null){
if(e.getClickedBlock().getType()==Material.WALL_SIGN||e.getClickedBlock().getType()==Material.SIGN_POST){
Sign sign = (Sign)e.getClickedBlock().getState();
String text = sign.getLine(0)+" . "+sign.getLine(1)+" . "+sign.getLine(2)+" . "+sign.getLine(3);
TalkUtil.speakOut(text, e.getPlayer());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent e) {
if (groups.get(e.getPlayer().getUniqueId()).equalsIgnoreCase("none"))
return;
Pattern noRepeats = Pattern.compile(".*([a-z[A-Z[0-9]]])\\1{5,}.*");
Matcher match = noRepeats.matcher(e.getMessage());
boolean repeats = match.find();
if (repeats) {
e.getPlayer().sendMessage(
prefix + "Do not mic spam. Voice over canceled.");
return;
}
String mF = e.getMessage();
TalkUtil.speakOut(mF, e.getPlayer());
}
public void initG(Player p) {
if (!groups.containsKey(p.getUniqueId().toString())) {
String group = getConfig().getString(
"users." + p.getUniqueId().toString() + ".g");
if (group == null || group.length() == 0) {
getConfig().set("users." + p.getUniqueId().toString() + ".g",
"none");
saveConfig();
groups.put(p.getUniqueId(), "none");
group = "none";
}
groups.put(p.getUniqueId(), group);
}
if (!lType.containsKey(p.getUniqueId().toString())) {
int l = getConfig().getInt(
"users." + p.getUniqueId().toString() + ".t");
if (l == 0 || l == -1) {
int lt = 2;
getConfig().set("users." + p.getUniqueId().toString() + ".l",
lt);
saveConfig();
lType.put(p.getUniqueId(), lt);
l = lt;
}
lType.put(p.getUniqueId(), l);
}
if (!pitch.containsKey(p.getUniqueId().toString())) {
int l = getConfig().getInt(
"users." + p.getUniqueId().toString() + ".p");
if (l == 0 || l == -1) {
int pi = 6;
getConfig().set("users." + p.getUniqueId().toString() + ".p",
pi);
saveConfig();
pitch.put(p.getUniqueId(), pi);
l = pi;
}
pitch.put(p.getUniqueId(), l);
}
}
public void tick() {
tick++;
}
public long getTick() {
return tick;
}
}

View File

@@ -0,0 +1,916 @@
package me.zombie_striker.tts;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
*
* Check out https://bStats.org/ to learn more about bStats!
*/
public class Metrics {
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData";
// Should failed requests be logged?
private static boolean logFailedRequests;
// The uuid of the server
private static String serverUUID;
// The plugin
private final JavaPlugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(JavaPlugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
if (config.getBoolean("enabled", true)) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
submitData();
}
});
}
}, 1000*60*5, 1000*60*30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount = Bukkit.getOnlinePlayers().size();
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = org.bukkit.Bukkit.getVersion();
bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
} catch (NoSuchFieldException ignored) {
continue; // Continue "searching"
}
// Found one!
try {
pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service)));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
protected final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
protected JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData();
}
/**
* Represents a custom simple pie.
*/
public static abstract class SimplePie extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public SimplePie(String chartId) {
super(chartId);
}
/**
* Gets the value of the pie.
*
* @return The value of the pie.
*/
public abstract String getValue();
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
String value = getValue();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static abstract class AdvancedPie extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public AdvancedPie(String chartId) {
super(chartId);
}
/**
* Gets the values of the pie.
*
* @param valueMap Just an empty map. The only reason it exists is to make your life easier.
* You don't have to create a map yourself!
* @return The values of the pie.
*/
public abstract HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap);
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static abstract class SingleLineChart extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public SingleLineChart(String chartId) {
super(chartId);
}
/**
* Gets the value of the chart.
*
* @return The value of the chart.
*/
public abstract int getValue();
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
int value = getValue();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static abstract class MultiLineChart extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public MultiLineChart(String chartId) {
super(chartId);
}
/**
* Gets the values of the chart.
*
* @param valueMap Just an empty map. The only reason it exists is to make your life easier.
* You don't have to create a map yourself!
* @return The values of the chart.
*/
public abstract HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap);
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple map chart.
*/
public static abstract class SimpleMapChart extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public SimpleMapChart(String chartId) {
super(chartId);
}
/**
* Gets the value of the chart.
*
* @return The value of the chart.
*/
public abstract Country getValue();
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
Country value = getValue();
if (value == null) {
// Null = skip the chart
return null;
}
data.put("value", value.getCountryIsoTag());
return data;
}
}
/**
* Represents a custom advanced map chart.
*/
public static abstract class AdvancedMapChart extends CustomChart {
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
public AdvancedMapChart(String chartId) {
super(chartId);
}
/**
* Gets the value of the chart.
*
* @param valueMap Just an empty map. The only reason it exists is to make your life easier.
* You don't have to create a map yourself!
* @return The value of the chart.
*/
public abstract HashMap<Country, Integer> getValues(HashMap<Country, Integer> valueMap);
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<Country, Integer> map = getValues(new HashMap<Country, Integer>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<Country, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey().getCountryIsoTag(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* A enum which is used for custom maps.
*/
public enum Country {
/**
* bStats will use the country of the server.
*/
AUTO_DETECT("AUTO", "Auto Detected"),
ANDORRA("AD", "Andorra"),
UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"),
AFGHANISTAN("AF", "Afghanistan"),
ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"),
ANGUILLA("AI", "Anguilla"),
ALBANIA("AL", "Albania"),
ARMENIA("AM", "Armenia"),
NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"),
ANGOLA("AO", "Angola"),
ANTARCTICA("AQ", "Antarctica"),
ARGENTINA("AR", "Argentina"),
AMERICAN_SAMOA("AS", "American Samoa"),
AUSTRIA("AT", "Austria"),
AUSTRALIA("AU", "Australia"),
ARUBA("AW", "Aruba"),
ÃLAND_ISLANDS("AX", "Ã…land Islands"),
AZERBAIJAN("AZ", "Azerbaijan"),
BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"),
BARBADOS("BB", "Barbados"),
BANGLADESH("BD", "Bangladesh"),
BELGIUM("BE", "Belgium"),
BURKINA_FASO("BF", "Burkina Faso"),
BULGARIA("BG", "Bulgaria"),
BAHRAIN("BH", "Bahrain"),
BURUNDI("BI", "Burundi"),
BENIN("BJ", "Benin"),
SAINT_BARTHÃLEMY("BL", "Saint Barthélemy"),
BERMUDA("BM", "Bermuda"),
BRUNEI("BN", "Brunei"),
BOLIVIA("BO", "Bolivia"),
BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"),
BRAZIL("BR", "Brazil"),
BAHAMAS("BS", "Bahamas"),
BHUTAN("BT", "Bhutan"),
BOUVET_ISLAND("BV", "Bouvet Island"),
BOTSWANA("BW", "Botswana"),
BELARUS("BY", "Belarus"),
BELIZE("BZ", "Belize"),
CANADA("CA", "Canada"),
COCOS_ISLANDS("CC", "Cocos Islands"),
THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"),
CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"),
CONGO("CG", "Congo"),
SWITZERLAND("CH", "Switzerland"),
CTE_D_IVOIRE("CI", "´te d'Ivoire"),
COOK_ISLANDS("CK", "Cook Islands"),
CHILE("CL", "Chile"),
CAMEROON("CM", "Cameroon"),
CHINA("CN", "China"),
COLOMBIA("CO", "Colombia"),
COSTA_RICA("CR", "Costa Rica"),
CUBA("CU", "Cuba"),
CAPE_VERDE("CV", "Cape Verde"),
CURAÃAO("CW", "Curaçao"),
CHRISTMAS_ISLAND("CX", "Christmas Island"),
CYPRUS("CY", "Cyprus"),
CZECH_REPUBLIC("CZ", "Czech Republic"),
GERMANY("DE", "Germany"),
DJIBOUTI("DJ", "Djibouti"),
DENMARK("DK", "Denmark"),
DOMINICA("DM", "Dominica"),
DOMINICAN_REPUBLIC("DO", "Dominican Republic"),
ALGERIA("DZ", "Algeria"),
ECUADOR("EC", "Ecuador"),
ESTONIA("EE", "Estonia"),
EGYPT("EG", "Egypt"),
WESTERN_SAHARA("EH", "Western Sahara"),
ERITREA("ER", "Eritrea"),
SPAIN("ES", "Spain"),
ETHIOPIA("ET", "Ethiopia"),
FINLAND("FI", "Finland"),
FIJI("FJ", "Fiji"),
FALKLAND_ISLANDS("FK", "Falkland Islands"),
MICRONESIA("FM", "Micronesia"),
FAROE_ISLANDS("FO", "Faroe Islands"),
FRANCE("FR", "France"),
GABON("GA", "Gabon"),
UNITED_KINGDOM("GB", "United Kingdom"),
GRENADA("GD", "Grenada"),
GEORGIA("GE", "Georgia"),
FRENCH_GUIANA("GF", "French Guiana"),
GUERNSEY("GG", "Guernsey"),
GHANA("GH", "Ghana"),
GIBRALTAR("GI", "Gibraltar"),
GREENLAND("GL", "Greenland"),
GAMBIA("GM", "Gambia"),
GUINEA("GN", "Guinea"),
GUADELOUPE("GP", "Guadeloupe"),
EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"),
GREECE("GR", "Greece"),
SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"),
GUATEMALA("GT", "Guatemala"),
GUAM("GU", "Guam"),
GUINEA_BISSAU("GW", "Guinea-Bissau"),
GUYANA("GY", "Guyana"),
HONG_KONG("HK", "Hong Kong"),
HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"),
HONDURAS("HN", "Honduras"),
CROATIA("HR", "Croatia"),
HAITI("HT", "Haiti"),
HUNGARY("HU", "Hungary"),
INDONESIA("ID", "Indonesia"),
IRELAND("IE", "Ireland"),
ISRAEL("IL", "Israel"),
ISLE_OF_MAN("IM", "Isle Of Man"),
INDIA("IN", "India"),
BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"),
IRAQ("IQ", "Iraq"),
IRAN("IR", "Iran"),
ICELAND("IS", "Iceland"),
ITALY("IT", "Italy"),
JERSEY("JE", "Jersey"),
JAMAICA("JM", "Jamaica"),
JORDAN("JO", "Jordan"),
JAPAN("JP", "Japan"),
KENYA("KE", "Kenya"),
KYRGYZSTAN("KG", "Kyrgyzstan"),
CAMBODIA("KH", "Cambodia"),
KIRIBATI("KI", "Kiribati"),
COMOROS("KM", "Comoros"),
SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"),
NORTH_KOREA("KP", "North Korea"),
SOUTH_KOREA("KR", "South Korea"),
KUWAIT("KW", "Kuwait"),
CAYMAN_ISLANDS("KY", "Cayman Islands"),
KAZAKHSTAN("KZ", "Kazakhstan"),
LAOS("LA", "Laos"),
LEBANON("LB", "Lebanon"),
SAINT_LUCIA("LC", "Saint Lucia"),
LIECHTENSTEIN("LI", "Liechtenstein"),
SRI_LANKA("LK", "Sri Lanka"),
LIBERIA("LR", "Liberia"),
LESOTHO("LS", "Lesotho"),
LITHUANIA("LT", "Lithuania"),
LUXEMBOURG("LU", "Luxembourg"),
LATVIA("LV", "Latvia"),
LIBYA("LY", "Libya"),
MOROCCO("MA", "Morocco"),
MONACO("MC", "Monaco"),
MOLDOVA("MD", "Moldova"),
MONTENEGRO("ME", "Montenegro"),
SAINT_MARTIN("MF", "Saint Martin"),
MADAGASCAR("MG", "Madagascar"),
MARSHALL_ISLANDS("MH", "Marshall Islands"),
MACEDONIA("MK", "Macedonia"),
MALI("ML", "Mali"),
MYANMAR("MM", "Myanmar"),
MONGOLIA("MN", "Mongolia"),
MACAO("MO", "Macao"),
NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"),
MARTINIQUE("MQ", "Martinique"),
MAURITANIA("MR", "Mauritania"),
MONTSERRAT("MS", "Montserrat"),
MALTA("MT", "Malta"),
MAURITIUS("MU", "Mauritius"),
MALDIVES("MV", "Maldives"),
MALAWI("MW", "Malawi"),
MEXICO("MX", "Mexico"),
MALAYSIA("MY", "Malaysia"),
MOZAMBIQUE("MZ", "Mozambique"),
NAMIBIA("NA", "Namibia"),
NEW_CALEDONIA("NC", "New Caledonia"),
NIGER("NE", "Niger"),
NORFOLK_ISLAND("NF", "Norfolk Island"),
NIGERIA("NG", "Nigeria"),
NICARAGUA("NI", "Nicaragua"),
NETHERLANDS("NL", "Netherlands"),
NORWAY("NO", "Norway"),
NEPAL("NP", "Nepal"),
NAURU("NR", "Nauru"),
NIUE("NU", "Niue"),
NEW_ZEALAND("NZ", "New Zealand"),
OMAN("OM", "Oman"),
PANAMA("PA", "Panama"),
PERU("PE", "Peru"),
FRENCH_POLYNESIA("PF", "French Polynesia"),
PAPUA_NEW_GUINEA("PG", "Papua New Guinea"),
PHILIPPINES("PH", "Philippines"),
PAKISTAN("PK", "Pakistan"),
POLAND("PL", "Poland"),
SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"),
PITCAIRN("PN", "Pitcairn"),
PUERTO_RICO("PR", "Puerto Rico"),
PALESTINE("PS", "Palestine"),
PORTUGAL("PT", "Portugal"),
PALAU("PW", "Palau"),
PARAGUAY("PY", "Paraguay"),
QATAR("QA", "Qatar"),
REUNION("RE", "Reunion"),
ROMANIA("RO", "Romania"),
SERBIA("RS", "Serbia"),
RUSSIA("RU", "Russia"),
RWANDA("RW", "Rwanda"),
SAUDI_ARABIA("SA", "Saudi Arabia"),
SOLOMON_ISLANDS("SB", "Solomon Islands"),
SEYCHELLES("SC", "Seychelles"),
SUDAN("SD", "Sudan"),
SWEDEN("SE", "Sweden"),
SINGAPORE("SG", "Singapore"),
SAINT_HELENA("SH", "Saint Helena"),
SLOVENIA("SI", "Slovenia"),
SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"),
SLOVAKIA("SK", "Slovakia"),
SIERRA_LEONE("SL", "Sierra Leone"),
SAN_MARINO("SM", "San Marino"),
SENEGAL("SN", "Senegal"),
SOMALIA("SO", "Somalia"),
SURINAME("SR", "Suriname"),
SOUTH_SUDAN("SS", "South Sudan"),
SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"),
EL_SALVADOR("SV", "El Salvador"),
SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"),
SYRIA("SY", "Syria"),
SWAZILAND("SZ", "Swaziland"),
TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"),
CHAD("TD", "Chad"),
FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"),
TOGO("TG", "Togo"),
THAILAND("TH", "Thailand"),
TAJIKISTAN("TJ", "Tajikistan"),
TOKELAU("TK", "Tokelau"),
TIMOR_LESTE("TL", "Timor-Leste"),
TURKMENISTAN("TM", "Turkmenistan"),
TUNISIA("TN", "Tunisia"),
TONGA("TO", "Tonga"),
TURKEY("TR", "Turkey"),
TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"),
TUVALU("TV", "Tuvalu"),
TAIWAN("TW", "Taiwan"),
TANZANIA("TZ", "Tanzania"),
UKRAINE("UA", "Ukraine"),
UGANDA("UG", "Uganda"),
UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"),
UNITED_STATES("US", "United States"),
URUGUAY("UY", "Uruguay"),
UZBEKISTAN("UZ", "Uzbekistan"),
VATICAN("VA", "Vatican"),
SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"),
VENEZUELA("VE", "Venezuela"),
BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"),
U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"),
VIETNAM("VN", "Vietnam"),
VANUATU("VU", "Vanuatu"),
WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"),
SAMOA("WS", "Samoa"),
YEMEN("YE", "Yemen"),
MAYOTTE("YT", "Mayotte"),
SOUTH_AFRICA("ZA", "South Africa"),
ZAMBIA("ZM", "Zambia"),
ZIMBABWE("ZW", "Zimbabwe");
private String isoTag;
private String name;
Country(String isoTag, String name) {
this.isoTag = isoTag;
this.name = name;
}
/**
* Gets the name of the country.
*
* @return The name of the country.
*/
public String getCountryName() {
return name;
}
/**
* Gets the iso tag of the country.
*
* @return The iso tag of the country.
*/
public String getCountryIsoTag() {
return isoTag;
}
/**
* Gets a country by it's iso tag.
*
* @param isoTag The iso tag of the county.
* @return The country with the given iso tag or <code>null</code> if unknown.
*/
public static Country byIsoTag(String isoTag) {
for (Country country : Country.values()) {
if (country.getCountryIsoTag().equals(isoTag)) {
return country;
}
}
return null;
}
/**
* Gets a country by a locale.
*
* @param locale The locale.
* @return The country from the giben locale or <code>null</code> if unknown country or
* if the locale does not contain a country.
*/
public static Country byLocale(Locale locale) {
return byIsoTag(locale.getCountry());
}
}
}

View File

@@ -0,0 +1,59 @@
package me.zombie_striker.tts;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class PlaySound {
// private final static Class<?> CRAFTPLAYERCLASS = ReflectionUtil
// .getCraftbukkitClass("CraftPlayer", "entity");
// private static final Class<?> PACKET_PLAY_OUT_NAMED_SOUND = /*ReflectionUtil
// .isVersionHigherThan(1, 7) ?*/ReflectionUtil
// .getNMSClass("PacketPlayOutNamedSoundEffect")/*: ReflectionUtil
// .getNMSClass("Packet201PlayerInfo")*/;
// private static final Class<?> MINECRAFT_KEY = ReflectionUtil
// .getNMSClass("MinecraftKey");
// private static final Class<?> SOUND_EFFECT = ReflectionUtil
// .getNMSClass("SoundEffect");
// private static final Class<?> PACKET_CLASS = ReflectionUtil
// .getNMSClass("Packet");
public static void playSound(Player p, Location l, String sound, float vol, float pitch){
// PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(new SoundEffect(new MinecraftKey(sound)), SoundCategory.VOICE, l.getX(), l.getY(), l.getZ(), vol, pitch);
/*Object packet = ReflectionUtil
.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(PACKET_PLAY_OUT_NAMED_SOUND)
.get());
try {
Object mckey = ReflectionUtil.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(MINECRAFT_KEY)
.get());
ReflectionUtil.setInstanceField(mckey, "a", sound);
Object sf = ReflectionUtil.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(SOUND_EFFECT)
.get());
ReflectionUtil.setInstanceField(sf, "a", mckey);*
ReflectionUtil.setInstanceField(packet, "a", sf);
ReflectionUtil.setInstanceField(packet, "b", 1);
ReflectionUtil.setInstanceField(packet, "c", l.getBlockX()*32);
ReflectionUtil.setInstanceField(packet, "d", l.getBlockY()*32);
ReflectionUtil.setInstanceField(packet, "e", l.getBlockZ()*32);
ReflectionUtil.setInstanceField(packet, "f", vol);
ReflectionUtil.setInstanceField(packet, "g", pitch);
} catch (Exception e) {
e.printStackTrace();
}*/
// Object handle = ReflectionUtil.invokeMethod(
// CRAFTPLAYERCLASS.cast(p), "getHandle", null);
// Object playerConnection = ReflectionUtil.getInstanceField(handle,
// "playerConnection");
// ReflectionUtil.invokeMethod(playerConnection, "sendPacket",
// new Class[] { PACKET_CLASS }, packet);
}
}

View File

@@ -0,0 +1,308 @@
package me.zombie_striker.tts;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
import org.bukkit.Bukkit;
/**
* A small help with reflection
*/
public class ReflectionUtil {
private static final String SERVER_VERSION;
static {
String name = Bukkit.getServer().getClass().getName();
name = name.substring(name.indexOf("craftbukkit.")
+ "craftbukkit.".length());
name = name.substring(0, name.indexOf("."));
SERVER_VERSION = name;
}
public static boolean isVersionHigherThan(int mainVersion,
int secondVersion) {
String firstChar = SERVER_VERSION.substring(1, 2);
int fInt = Integer.parseInt(firstChar);
if (fInt < mainVersion)
return false;
StringBuilder secondChar = new StringBuilder();
for (int i = 3; i < 10; i++) {
if (SERVER_VERSION.charAt(i) == '_'
|| SERVER_VERSION.charAt(i) == '.')
break;
secondChar.append(SERVER_VERSION.charAt(i));
}
int sInt = Integer.parseInt(secondChar.toString());
if (sInt < secondVersion)
return false;
return true;
}
/**
* Returns the NMS class.
*
* @param name
* The name of the class
*
* @return The NMS class or null if an error occurred
*/
public static Class<?> getNMSClass(String name) {
try {
return Class.forName("net.minecraft.server." + SERVER_VERSION
+ "." + name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the CraftBukkit class.
*
* @param name
* The name of the class
*
* @return The CraftBukkit class or null if an error occurred
*/
public static Class<?> getCraftbukkitClass(String name,
String packageName) {
try {
return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION
+ "." + packageName + "." + name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the mojang.authlib class.
*
* @param name
* The name of the class
*
* @return The mojang.authlib class or null if an error occurred
*/
public static Class<?> getMojangAuthClass(String name) {
try {
return Class.forName("com.mojang.authlib." + name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Invokes the method
*
* @param handle
* The handle to invoke it on
* @param methodName
* The name of the method
* @param parameterClasses
* The parameter types
* @param args
* The arguments
*
* @return The resulting object or null if an error occurred / the
* method didn't return a thing
*/
@SuppressWarnings("rawtypes")
public static Object invokeMethod(Object handle, String methodName,
Class[] parameterClasses, Object... args) {
return invokeMethod(handle.getClass(), handle, methodName,
parameterClasses, args);
}
/**
* Invokes the method
*
* @param clazz
* The class to invoke it from
* @param handle
* The handle to invoke it on
* @param methodName
* The name of the method
* @param parameterClasses
* The parameter types
* @param args
* The arguments
*
* @return The resulting object or null if an error occurred / the
* method didn't return a thing
*/
@SuppressWarnings("rawtypes")
public static Object invokeMethod(Class<?> clazz, Object handle,
String methodName, Class[] parameterClasses, Object... args) {
Optional<Method> methodOptional = getMethod(clazz, methodName,
parameterClasses);
if (!methodOptional.isPresent()) {
return null;
}
Method method = methodOptional.get();
try {
return method.invoke(handle, args);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
/**
* Sets the value of an instance field
*
* @param handle
* The handle to invoke it on
* @param name
* The name of the field
* @param value
* The new value of the field
*/
public static void setInstanceField(Object handle, String name,
Object value) {
Class<?> clazz = handle.getClass();
Optional<Field> fieldOptional = getField(clazz, name);
if (!fieldOptional.isPresent()) {
return;
}
Field field = fieldOptional.get();
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
field.set(handle, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Sets the value of an instance field
*
* @param handle
* The handle to invoke it on
* @param name
* The name of the field
*
* @return The result
*/
public static Object getInstanceField(Object handle, String name) {
Class<?> clazz = handle.getClass();
Optional<Field> fieldOptional = getField(clazz, name);
if (!fieldOptional.isPresent()) {
return handle;
}
Field field = fieldOptional.get();
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
return field.get(handle);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
* Returns an enum constant
*
* @param enumClass
* The class of the enum
* @param name
* The name of the enum constant
*
* @return The enum entry or null
*/
public static Object getEnumConstant(Class<?> enumClass, String name) {
if (!enumClass.isEnum()) {
return null;
}
for (Object o : enumClass.getEnumConstants()) {
if (name.equals(invokeMethod(o, "name", new Class[0]))) {
return o;
}
}
return null;
}
/**
* Returns the constructor
*
* @param clazz
* The class
* @param params
* The Constructor parameters
*
* @return The Constructor or an empty Optional if there is none with
* these parameters
*/
public static Optional<?> getConstructor(Class<?> clazz,
Class<?>... params) {
try {
return Optional.of(clazz.getConstructor(params));
} catch (NoSuchMethodException e) {
try {
return Optional.of(clazz.getDeclaredConstructor(params));
} catch (NoSuchMethodException e2) {
e2.printStackTrace();
}
}
return Optional.empty();
}
/**
* Instantiates the class. Will print the errors it gets
*
* @param constructor
* The constructor
* @param arguments
* The initial arguments
*
* @return The resulting object, or null if an error occurred.
*/
public static Object instantiate(Constructor<?> constructor,
Object... arguments) {
try {
return constructor.newInstance(arguments);
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static Optional<Method> getMethod(Class<?> clazz, String name,
Class<?>... params) {
try {
return Optional.of(clazz.getMethod(name, params));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
return Optional.of(clazz.getDeclaredMethod(name, params));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return Optional.empty();
}
public static Optional<Field> getField(Class<?> clazz, String name) {
try {
return Optional.of(clazz.getField(name));
} catch (NoSuchFieldException e){}
try {
return Optional.of(clazz.getDeclaredField(name));
} catch (NoSuchFieldException e) {}
return Optional.empty();
}
}

View File

@@ -0,0 +1,255 @@
/*
* Copyright (C) 2016 Zombie_Striker
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package me.zombie_striker.tts;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import me.zombie_striker.tts.util.TalkUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.BookMeta;
public class TTSCommand implements CommandExecutor, TabCompleter {
CoreTTS tts;
public TTSCommand(CoreTTS tts) {
this.tts = tts;// TODO Auto-generated constructor stub
}
@Override
public List<String> onTabComplete(CommandSender arg0, Command arg1,
String arg2, String[] args) {
List<String> ls = new ArrayList<String>();
if (args.length == 1) {
startsWith(ls, "get", args[0]);
startsWith(ls, "join", args[0]);
startsWith(ls, "leave", args[0]);
startsWith(ls, "kick", args[0]);
startsWith(ls, "ban", args[0]);
startsWith(ls, "unban", args[0]);
startsWith(ls, "setpitch", args[0]);
startsWith(ls, "download", args[0]);
startsWith(ls, "ban", args[0]);
startsWith(ls, "readBook", args[0]);
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("join")) {
startsWith(ls, "public", args[1]);
for (String groups : tts.groups.values()) {
if (!ls.contains(groups))
startsWith(ls, groups, args[1]);
}
} else if (args[0].equalsIgnoreCase("kick")
|| args[0].equalsIgnoreCase("ban")) {
for (UUID player : tts.groups.keySet()) {
if (tts.groups.get(player).equalsIgnoreCase(
tts.groups.get(Bukkit.getPlayer(arg0.getName())
.getUniqueId())))
startsWith(ls, tts.groups.get(player), args[1]);
}
}
}
return ls;
}
public void startsWith(List<String> ls, String s, String arg) {
if (s.startsWith(arg))
ls.add(s);
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("You need to be a player in order to issue these commands.");
return true;
}
final Player p = (Player) sender;
if (args.length == 0) {
sendHelp(p);
return true;
}
if (args[0].equalsIgnoreCase("join")) {
if (args.length < 2) {
sender.sendMessage(tts.prefix
+ "You need to specify a group to join");
return true;
}
String group = args[1];
if (tts.bannedG.containsKey(group)
&& tts.bannedG.get(group).contains(p.getUniqueId())) {
sender.sendMessage(tts.prefix
+ " You have been banned from this group. If you feel this is a mistake, please talk to an admin.");
return true;
}
tts.groups.put(p.getUniqueId(), group);
sender.sendMessage(tts.prefix + " You have been added to group "
+ group);
sender.sendMessage(ChatColor.BOLD+tts.prefix+ChatColor.BOLD+" If you do not have the voice resource pack, you can download it here. Current Version 1.3");
sender.sendMessage(CoreTTS.RES);
p.sendTitle("Downloading will begin soon", "If the prompt does not display in 5 seconds, use the link in the chat.");
Bukkit.getScheduler().scheduleSyncDelayedTask(this.tts, new Runnable(){public void run(){p.setResourcePack(CoreTTS.RES);}}, 20*5);
} else if (args[0].equalsIgnoreCase("readbook")){
if(p.getInventory().getItemInMainHand()!=null&&p.getInventory().getItemInMainHand().getType()==Material.BOOK_AND_QUILL){
BookMeta bm = (BookMeta) p.getInventory().getItemInMainHand().getItemMeta();
StringBuilder fullBook = new StringBuilder();
for(String page : bm.getPages()){
fullBook.append(page+" .. ");
}
TalkUtil.speakOut(fullBook.toString(), p);
}else{
p.sendMessage("You must have the book in your hand.");
}
} else if (args[0].equalsIgnoreCase("get")){
sender.sendMessage(ChatColor.BOLD+tts.prefix+ChatColor.BOLD+" If you do not have the voice resource pack, you can download it here. Current Version 1.3");
sender.sendMessage(CoreTTS.RES);
p.sendTitle("Downloading will begin soon", "If the prompt does not display in 5 seconds, use the link in the chat.");
Bukkit.getScheduler().scheduleSyncDelayedTask(this.tts, new Runnable(){public void run(){p.setResourcePack(CoreTTS.RES);}}, 20*5);
} else if (args[0].equalsIgnoreCase("leave")) {
tts.groups.put(p.getUniqueId(), "none");
sender.sendMessage(tts.prefix
+ " You have been removed from your groups.");
} else if (args[0].equalsIgnoreCase("kick")) {
if (sender.hasPermission("tts.ban") || sender.isOp()) {
if (args.length < 2) {
sender.sendMessage(tts.prefix
+ " You have to specify which player to " + args[0]);
return true;
}
Player p2 = Bukkit.getPlayer(args[1]);
if (p2 == null) {
sender.sendMessage(tts.prefix + " The player you want to "
+ args[0] + " must be on the server.");
return true;
}
tts.groups.put(p2.getUniqueId(), "none");
p2.sendMessage(tts.prefix + " You have been " + args[0]
+ " from your group.");
p.sendMessage(tts.prefix + " You have " + args[0] + " "
+ p2.getName() + " from your group.");
}
} else if (args[0].equalsIgnoreCase("ban")
|| args[0].equalsIgnoreCase("unban")) {
if (sender.hasPermission("tts.ban") || sender.isOp()) {
if (args.length < 2) {
sender.sendMessage(tts.prefix
+ " You have to specify which player to " + args[0]);
return true;
}
Player p2 = Bukkit.getPlayer(args[1]);
if (p2 == null) {
sender.sendMessage(tts.prefix + " The player you want to "
+ args[0] + " must be on the server.");
return true;
}
if (args.length < 3) {
sender.sendMessage(tts.prefix
+ " You have to specify which group to unban the player from");
return true;
}
String group = args[2];
if (args[0].equalsIgnoreCase("ban")) {
tts.groups.put(p2.getUniqueId(), "none");
if (!tts.bannedG.containsKey(group))
tts.bannedG.put(group, new ArrayList<UUID>());
tts.bannedG.get(group).add(p2.getUniqueId());
} else {
if (tts.bannedG.containsKey(group))
tts.bannedG.get(group).remove(p2.getUniqueId());
}
tts.groups.put(p2.getUniqueId(), "none");
p2.sendMessage(tts.prefix + " You have been " + args[0]
+ " from the group " + group);
p.sendMessage(tts.prefix + " You have " + args[0] + " "
+ p2.getName() + " from the group." + group);
}
}else if (args[0].equalsIgnoreCase("setPitch")){
if (args.length < 2) {
sender.sendMessage("You need to specify the pitch between 0 and 10. Default is 5");
return true;
}
int pitch=5;
try{
pitch = Integer.parseInt(args[1]);
}catch(Exception e){
sender.sendMessage("You need to specify a number");
return true;
}
tts.pitch.put(p.getUniqueId(), pitch);
p.sendMessage("Your pitch has been set to "+pitch+".");
} else if (args[0].equalsIgnoreCase("type")) {
if (args.length < 2) {
sender.sendMessage("You need to specify the type <local, world, or global>");
return true;
}
String t = args[1];
if (t.equalsIgnoreCase("local")) {
tts.lType.put(p.getUniqueId(), 1);
sender.sendMessage(tts.prefix
+ " Your chattype has been set to Local.");
} else if (t.equalsIgnoreCase("world")) {
tts.lType.put(p.getUniqueId(), 2);
sender.sendMessage(tts.prefix
+ " Your chattype has been set to World.");
} else if (t.equalsIgnoreCase("global")) {
tts.lType.put(p.getUniqueId(), 3);
sender.sendMessage(tts.prefix
+ " Your chattype has been set to Global.");
} else {
sender.sendMessage("Choose either 'Local', 'World', or 'Global'.");
}
} else if (args[0].equalsIgnoreCase("download")) {
sender.sendMessage(tts.prefix+" Link to resourcepack. Download it and activate it to hear the voices.");
sender.sendMessage("https://dev.bukkit.org/bukkit-plugins/texttospeach/files/4-voice-pack-1-1/");
} else {
sendHelp(p);
}
return true;
}
public void sendHelp(Player p) {
p.sendMessage(ChatColor.GRAY + " /tts type <local,world,global>:"
+ ChatColor.RESET + " changes the chat type");
p.sendMessage(ChatColor.GRAY + " /tts join <group>:" + ChatColor.RESET
+ " Join a selected group");
p.sendMessage(ChatColor.GRAY + " /tts leave :" + ChatColor.RESET
+ " Leave the group you are in");
p.sendMessage(ChatColor.GRAY + " /tts get:"
+ ChatColor.RESET + " gives the player the link to the resourcepack.");
p.sendMessage(ChatColor.GRAY + " /tts kick <player> :"
+ ChatColor.RESET + " Kicks a player from their group.");
p.sendMessage(ChatColor.GRAY + " /tts ban/unban <player> <group>:" + ChatColor.RESET
+ "(un)Bans a player from the group.");
p.sendMessage(ChatColor.GRAY + " /tts setPitch <pitch> :" + ChatColor.RESET
+ " sets the pitch for your player.");
p.sendMessage(ChatColor.GRAY + " /tts readbook :" + ChatColor.RESET
+ " Reads the book in your hand.");
p.sendMessage(ChatColor.DARK_RED+""+ChatColor.BOLD+"If a word is not right, please go here:");
p.sendMessage("https://dev.bukkit.org/bukkit-plugins/texttospeach/");
}
}

View File

@@ -0,0 +1,738 @@
package me.zombie_striker.tts;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* Checks and auto updates a plugin<br>
* <br>
* <b>You must have a option in your config to disable the updater!</b>
*
* @author Arsen
*/
public class Updater {
private static final String HOST = "https://api.curseforge.com";
private static final String QUERY = "/servermods/files?projectIds=";
private static final String AGENT = "Mozilla/5.0 Updater by ArsenArsen";
private static final File WORKING_DIR = new File("plugins" + File.separator + "AUpdater" + File.separator);
private static final File BACKUP_DIR = new File(WORKING_DIR, "backups" + File.separator);
private static final File LOG_FILE = new File(WORKING_DIR, "updater.log");
private static final File CONFIG_FILE = new File(WORKING_DIR, "global.yml");
private static final char[] HEX_CHAR_ARRAY = "0123456789abcdef".toCharArray();
private static final Pattern NAME_MATCH = Pattern.compile(".+\\sv?[0-9.]+");
private static final String VERSION_SPLIT = "\\sv?";
private int id = -1;
private Plugin p;
@SuppressWarnings("FieldCanBeLocal")
private boolean debug = false;
private UpdateAvailability lastCheck = null;
private UpdateResult lastUpdate = UpdateResult.NOT_UPDATED;
private File pluginFile = null;
private String downloadURL = null;
private String futuremd5;
private String downloadName;
private List<Channel> allowedChannels = Arrays.asList(Channel.ALPHA, Channel.BETA, Channel.RELEASE);
private List<UpdateCallback> callbacks = new ArrayList<>();
private SyncCallbackCaller caller = new SyncCallbackCaller();
private List<String> skipTags = new ArrayList<>();
private String latest;
private FileConfiguration global;
/**
* Makes the updater for a plugin
*
* @param p Plugin to update
*/
public Updater(Plugin p) {
this.p = p;
try {
pluginFile = new File(URLDecoder.decode(p.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
debug(e.toString());
// Should not ever happen
}
latest = p.getDescription().getVersion();
if (!CONFIG_FILE.exists()) {
try {
CONFIG_FILE.getParentFile().mkdirs();
CONFIG_FILE.createNewFile();
log("Created config file!");
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Could not create " + CONFIG_FILE.getName() + "!", e);
}
}
global = YamlConfiguration.loadConfiguration(CONFIG_FILE);
global.options().header("Updater by ArsenArsen\nGlobal config\nSets should updates be downloaded globaly");
if (!global.isSet("update")) {
global.set("update", true);
try {
global.save(CONFIG_FILE);
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Could not save default config file!", e);
}
}
if (!LOG_FILE.exists()) {
try {
LOG_FILE.getParentFile().mkdirs();
LOG_FILE.createNewFile();
log("Created log file!");
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Could not create " + LOG_FILE.getName() + "!", e);
}
}
}
/**
* Makes the updater for a plugin with an ID
*
* @param p The plugin
* @param id Plugin ID
*/
public Updater(Plugin p, int id) {
this(p);
setID(id);
}
/**
* Makes the updater for a plugin with an ID
*
* @param p The plugin
* @param id Plugin ID
* @param download Set to true if your plugin needs to be immediately downloaded
* @param skipTags Tags, endings of a filename, that updater will ignore, must begin with a dash ('-')
*/
public Updater(Plugin p, int id, boolean download, String... skipTags) {
this(p);
setID(id);
for (String tag : skipTags)
if (tag.startsWith("-"))
this.skipTags.add(tag);
if (download && (checkForUpdates() == UpdateAvailability.UPDATE_AVAILABLE)) {
update();
}
}
/**
* Makes the updater for a plugin with an ID
*
* @param p The plugin
* @param id Plugin ID
* @param download Set to true if your plugin needs to be immediately downloaded
* @param skipTags Tags, endings of a filename, that updater will ignore, or null for none
* @param callbacks All update callbacks you need
*/
public Updater(Plugin p, int id, boolean download, String[] skipTags, UpdateCallback... callbacks) {
this(p);
setID(id);
this.callbacks.addAll(Arrays.asList(callbacks));
if (skipTags != null) {
for (String tag : skipTags)
if (tag.startsWith("-"))
this.skipTags.add(tag);
}
if (global.getBoolean("update", true) && download && (checkForUpdates() == UpdateAvailability.UPDATE_AVAILABLE)) {
update();
}
}
/**
* Gets the plugin ID
*
* @return the plugin ID
*/
public int getID() {
return id;
}
/**
* Sets the plugin ID
*
* @param id The plugin ID
*/
public void setID(int id) {
this.id = id;
}
/**
* Adds a new callback
*
* @param callback Callback to register
*/
public void registerCallback(UpdateCallback callback) {
callbacks.add(callback);
}
/**
* Attempts a update
*
* @throws IllegalStateException if the ID was not set
*/
public void update() {
debug(WORKING_DIR.getAbsolutePath());
debug("Update!");
if (id == -1) {
throw new IllegalStateException("Plugin ID is not set!");
}
if (lastCheck == null) {
checkForUpdates();
}
if (!BACKUP_DIR.exists() || !BACKUP_DIR.isDirectory()) {
BACKUP_DIR.mkdir();
}
final Updater updater = this;
if (!global.getBoolean("update", true)) {
lastUpdate = UpdateResult.DISABLED;
debug("Disabled!");
caller.call(callbacks, UpdateResult.DISABLED, updater);
return;
}
if (lastCheck == UpdateAvailability.UPDATE_AVAILABLE) {
new BukkitRunnable() {
@Override
public void run() {
debug("Update STARTED!");
p.getLogger().info("Starting update of " + p.getName());
log("Updating " + p.getName() + "!");
lastUpdate = download();
p.getLogger().log(Level.INFO, "Update done! Result: " + lastUpdate);
caller.call(callbacks, lastUpdate, updater);
}
}.runTaskAsynchronously(p);
} else if (lastCheck == UpdateAvailability.SM_UNREACHABLE) {
lastUpdate = UpdateResult.IOERROR;
debug("Fail!");
caller.call(callbacks, UpdateResult.IOERROR, updater);
} else {
lastUpdate = UpdateResult.GENERAL_ERROR;
debug("Fail!");
caller.call(callbacks, UpdateResult.IOERROR, updater);
}
}
private UpdateResult download() {
try {
Files.copy(pluginFile.toPath(),
new File(BACKUP_DIR, "backup-" + System.currentTimeMillis() + "-" + p.getName() + ".jar").toPath(),
StandardCopyOption.REPLACE_EXISTING);
final File downloadTo = new File(pluginFile.getParentFile().getAbsolutePath() +
File.separator + "AUpdater" + File.separator, downloadName);
downloadTo.getParentFile().mkdirs();
downloadTo.delete();
debug("Started download!");
downloadIsSeperateBecauseGotoGotRemoved(downloadTo);
debug("Ended download!");
if (!fileHash(downloadTo).equalsIgnoreCase(futuremd5))
return UpdateResult.BAD_HASH;
if (downloadTo.getName().endsWith(".jar")) {
pluginFile.setWritable(true, false);
pluginFile.delete();
debug("Started copy!");
InputStream in = new FileInputStream(downloadTo);
File file = new File(pluginFile.getParentFile()
.getAbsoluteFile() + File.separator + "update" + File.separator, pluginFile.getName());
file.getParentFile().mkdirs();
file.createNewFile();
OutputStream out = new FileOutputStream(file);
long bytes = copy(in, out);
p.getLogger().info("Update done! Downloaded " + bytes + " bytes!");
log("Updated plugin " + p.getName() + " with " + bytes + "bytes!");
return UpdateResult.UPDATE_SUCCEEDED;
} else
return unzip(downloadTo);
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Couldn't download update for " + p.getName(), e);
log("Failed to update " + p.getName() + "!", e);
return UpdateResult.IOERROR;
}
}
/**
* God damn it Gosling, <a href="http://stackoverflow.com/a/4547764/3809164">reference here.</a>
*/
private void downloadIsSeperateBecauseGotoGotRemoved(File downloadTo) throws IOException {
URL url = new URL(downloadURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", AGENT);
connection.connect();
if (connection.getResponseCode() >= 300 && connection.getResponseCode() < 400) {
downloadURL = connection.getHeaderField("Location");
downloadIsSeperateBecauseGotoGotRemoved(downloadTo);
} else {
debug(connection.getResponseCode() + " " + connection.getResponseMessage() + " when requesting " + downloadURL);
copy(connection.getInputStream(), new FileOutputStream(downloadTo));
}
}
private long copy(InputStream in, OutputStream out) throws IOException {
long bytes = 0;
byte[] buf = new byte[0x1000];
while (true) {
int r = in.read(buf);
if (r == -1)
break;
out.write(buf, 0, r);
bytes += r;
debug("Another 4K, current: " + r);
}
out.flush();
out.close();
in.close();
return bytes;
}
private UpdateResult unzip(File download) {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(download);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
ZipEntry entry;
File updateFile = new File(pluginFile.getParentFile()
.getAbsoluteFile() + File.separator + "update" + File.separator, pluginFile.getName());
while ((entry = entries.nextElement()) != null) {
File target = new File(updateFile, entry.getName());
File inPlugins = new File(pluginFile.getParentFile(), entry.getName());
if(!inPlugins.exists()){
target = inPlugins;
}
if (!entry.isDirectory()) {
target.getParentFile().mkdirs();
InputStream zipStream = zipFile.getInputStream(entry);
OutputStream fileStream = new FileOutputStream(target);
copy(zipStream, fileStream);
}
}
return UpdateResult.UPDATE_SUCCEEDED;
} catch (IOException e) {
if (e instanceof ZipException) {
p.getLogger().log(Level.SEVERE, "Could not unzip downloaded file!", e);
log("Update for " + p.getName() + "was an unknown filetype! ", e);
return UpdateResult.UNKNOWN_FILE_TYPE;
} else {
p.getLogger().log(Level.SEVERE,
"An IOException occured while trying to update %s!".replace("%s", p.getName()), e);
log("Update for " + p.getName() + "was an unknown filetype! ", e);
return UpdateResult.IOERROR;
}
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException ignored) {
}
}
}
}
/**
* Checks for new updates
*
* @param force Discards the cached state in order to get a new one, ignored if update check didn't run
* @return Is there any updates
* @throws IllegalStateException If the plugin ID is not set
*/
public UpdateAvailability checkForUpdates(boolean force) {
if (id == -1) {
throw new IllegalStateException("Plugin ID is not set!");
}
if (force || lastCheck == null) {
String target = HOST + QUERY + id;
debug(target);
try {
URL url = new URL(target);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", AGENT);
connection.connect();
debug("Connecting!");
BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder responseBuffer = new StringBuilder();
String line;
while ((line = responseReader.readLine()) != null) {
responseBuffer.append(line);
}
debug("All read!");
responseReader.close();
String response = responseBuffer.toString();
int counter = 1;
if (connection.getResponseCode() == 200) {
try {
debug("RESCODE 200");
while (true) {
debug("Counter: " + counter);
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(response);
if (json.size() - counter < 0) {
lastCheck = UpdateAvailability.NO_UPDATE;
debug("No update!");
break;
}
JSONObject latest = (JSONObject) json.get(json.size() - counter);
futuremd5 = (String) latest.get("md5");
String channel = (String) latest.get("releaseType");
String name = (String) latest.get("name");
if (allowedChannels.contains(Channel.matchChannel(channel.toUpperCase()))
&& !hasTag(name)) {
String noTagName = name;
String oldVersion = p.getDescription().getVersion().replaceAll("-.*", "");
for (String tag : skipTags) {
noTagName = noTagName.replace(tag, "");
oldVersion = oldVersion.replace(tag, "");
}
if (!NAME_MATCH.matcher(noTagName).matches()) {
lastCheck = UpdateAvailability.CANT_PARSE_NAME;
return lastCheck;
}
String[] splitName = noTagName.split(VERSION_SPLIT);
String version = splitName[splitName.length - 1];
if (oldVersion.length() > version.length()) {
while (oldVersion.length() > version.length()) {
version += ".0";
}
} else if (oldVersion.length() < version.length()) {
while (oldVersion.length() < version.length()) {
oldVersion += ".0";
}
}
debug("Versions are same length");
String[] splitOldVersion = oldVersion.split("\\.");
String[] splitVersion = version.split("\\.");
Integer[] parsedOldVersion = new Integer[splitOldVersion.length];
Integer[] parsedVersion = new Integer[splitVersion.length];
for (int i = 0; i < parsedOldVersion.length; i++) {
parsedOldVersion[i] = Integer.parseInt(splitOldVersion[i]);
}
for (int i = 0; i < parsedVersion.length; i++) {
parsedVersion[i] = Integer.parseInt(splitVersion[i]);
}
boolean update = false;
for (int i = 0; i < parsedOldVersion.length; i++) {
if (parsedOldVersion[i] < parsedVersion[i]) {
update = true;
break;
}
}
if (!update) {
lastCheck = UpdateAvailability.NO_UPDATE;
} else {
lastCheck = UpdateAvailability.UPDATE_AVAILABLE;
downloadURL = ((String) latest.get("downloadUrl")).replace(" ", "%20");
downloadName = (String) latest.get("fileName");
}
break;
} else
counter++;
}
debug("While loop over!");
} catch (ParseException e) {
p.getLogger().log(Level.SEVERE, "Could not parse API Response for " + target, e);
log("Could not parse API Response for " + target + " while updating " + p.getName(), e);
lastCheck = UpdateAvailability.CANT_UNDERSTAND;
}
} else {
log("Could not reach API for " + target + " while updating " + p.getName());
lastCheck = UpdateAvailability.SM_UNREACHABLE;
}
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Could not check for updates for plugin " + p.getName(), e);
log("Could not reach API for " + target + " while updating " + p.getName(), e);
lastCheck = UpdateAvailability.SM_UNREACHABLE;
}
}
log("Update check ran for " + p.getName() + "! Check resulted in " + lastCheck);
return lastCheck;
}
private void debug(String message) {
if (debug)
p.getLogger().info(message + ' ' + new Throwable().getStackTrace()[1]);
}
private void log(String message) {
try {
Files.write(LOG_FILE.toPath(), Collections.singletonList(
"[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "] " + message),
StandardCharsets.UTF_8, StandardOpenOption.APPEND);
} catch (IOException e) {
p.getLogger().log(Level.SEVERE, "Could not log to " + LOG_FILE.getAbsolutePath() + "!", e);
}
}
private void log(String message, Exception exception) {
StringWriter string = new StringWriter();
PrintWriter print = new PrintWriter(string);
exception.printStackTrace(print);
log(message + " " + string.toString());
try {
string.close();
} catch (IOException ignored) {
}
print.close();
}
private boolean hasTag(String name) {
for (String tag : skipTags) {
if (name.toLowerCase().endsWith(tag.toLowerCase())) {
return true;
}
}
return false;
}
/**
* Checks for new updates, non forcing cache override
*
* @return Is there any updates
* @throws IllegalStateException If the plugin ID is not set
*/
public UpdateAvailability checkForUpdates() {
return checkForUpdates(false);
}
/**
* Checks did the update run successfully
*
* @return The update state
*/
public UpdateResult isUpdated() {
return lastUpdate;
}
/**
* Sets allowed channels, AKA release types
*
* @param channels The allowed channels
*/
public void setChannels(Channel... channels) {
allowedChannels.clear();
allowedChannels.addAll(Arrays.asList(channels));
}
/**
* Gets the latest version
*
* @return The latest version
*/
public String getLatest() {
return latest;
}
/**
* Shows the outcome of an update
*
* @author Arsen
*/
public enum UpdateResult {
/**
* Update was successful
*/
UPDATE_SUCCEEDED,
/**
* Update was not attempted yet
*/
NOT_UPDATED,
/**
* Could not unpack the update
*/
UNKNOWN_FILE_TYPE,
/**
* Miscellanies error occurred while update checking
*/
GENERAL_ERROR,
/**
* Updater is globally disabled
*/
DISABLED,
/**
* The hashing algorithm and the remote hash had different results.
*/
BAD_HASH,
/**
* An unknown IO error occurred
*/
IOERROR
}
/**
* Shows the outcome of an update check
*
* @author Arsen
*/
public enum UpdateAvailability {
/**
* There is an update
*/
UPDATE_AVAILABLE,
/**
* You have the latest version
*/
NO_UPDATE,
/**
* Could not reach server mods API
*/
SM_UNREACHABLE,
/**
* Update name cannot be parsed, meaning the version cannot be compared
*/
CANT_PARSE_NAME,
/**
* Could not parse response from server mods API
*/
CANT_UNDERSTAND
}
public enum Channel {
/**
* Normal release
*/
RELEASE("release"),
/**
* Beta release
*/
BETA("beta"),
/**
* Alpha release
*/
ALPHA("alpha");
private String channel;
Channel(String channel) {
this.channel = channel;
}
/**
* Gets the channel value
*
* @return the channel value
*/
public String getChannel() {
return channel;
}
/**
* Returns channel whose channel value matches the given string
*
* @param channel The channel value
* @return The Channel constant
*/
public static Channel matchChannel(String channel) {
for (Channel c : values()) {
if (c.channel.equalsIgnoreCase(channel)) {
return c;
}
}
return null;
}
}
/**
* Calculates files MD5 hash
*
* @param file The file to digest
* @return The MD5 hex or null, if the operation failed
*/
public String fileHash(File file) {
FileInputStream is;
try {
is = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = new byte[2048];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
md.update(bytes, 0, numBytes);
}
byte[] digest = md.digest();
char[] hexChars = new char[digest.length * 2];
for (int j = 0; j < digest.length; j++) {
int v = digest[j] & 0xFF;
hexChars[j * 2] = HEX_CHAR_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_CHAR_ARRAY[v & 0x0F];
}
is.close();
return new String(hexChars);
} catch (IOException | NoSuchAlgorithmException e) {
p.getLogger().log(Level.SEVERE, "Could not digest " + file.getPath(), e);
return null;
}
}
/**
* Called right after update is done
*
* @author Arsen
*/
public interface UpdateCallback {
void updated(UpdateResult updateResult, Updater updater);
}
private class SyncCallbackCaller extends BukkitRunnable {
private List<UpdateCallback> callbacks;
private UpdateResult updateResult;
private Updater updater;
public void run() {
for (UpdateCallback callback : callbacks) {
callback.updated(updateResult, updater);
}
}
void call(List<UpdateCallback> callbacks, UpdateResult updateResult, Updater updater) {
this.callbacks = callbacks;
this.updateResult = updateResult;
this.updater = updater;
if (!Bukkit.getServer().isPrimaryThread())
runTask(updater.p);
else run();
}
}
}

View File

@@ -0,0 +1,59 @@
package me.zombie_striker.tts;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class PlaySound {
// private final static Class<?> CRAFTPLAYERCLASS = ReflectionUtil
// .getCraftbukkitClass("CraftPlayer", "entity");
// private static final Class<?> PACKET_PLAY_OUT_NAMED_SOUND = /*ReflectionUtil
// .isVersionHigherThan(1, 7) ?*/ReflectionUtil
// .getNMSClass("PacketPlayOutNamedSoundEffect")/*: ReflectionUtil
// .getNMSClass("Packet201PlayerInfo")*/;
// private static final Class<?> MINECRAFT_KEY = ReflectionUtil
// .getNMSClass("MinecraftKey");
// private static final Class<?> SOUND_EFFECT = ReflectionUtil
// .getNMSClass("SoundEffect");
// private static final Class<?> PACKET_CLASS = ReflectionUtil
// .getNMSClass("Packet");
public static void playSound(Player p, Location l, String sound, float vol, float pitch){
// PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(new SoundEffect(new MinecraftKey(sound)), SoundCategory.VOICE, l.getX(), l.getY(), l.getZ(), vol, pitch);
/*Object packet = ReflectionUtil
.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(PACKET_PLAY_OUT_NAMED_SOUND)
.get());
try {
Object mckey = ReflectionUtil.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(MINECRAFT_KEY)
.get());
ReflectionUtil.setInstanceField(mckey, "a", sound);
Object sf = ReflectionUtil.instantiate((Constructor<?>) ReflectionUtil
.getConstructor(SOUND_EFFECT)
.get());
ReflectionUtil.setInstanceField(sf, "a", mckey);*
ReflectionUtil.setInstanceField(packet, "a", sf);
ReflectionUtil.setInstanceField(packet, "b", 1);
ReflectionUtil.setInstanceField(packet, "c", l.getBlockX()*32);
ReflectionUtil.setInstanceField(packet, "d", l.getBlockY()*32);
ReflectionUtil.setInstanceField(packet, "e", l.getBlockZ()*32);
ReflectionUtil.setInstanceField(packet, "f", vol);
ReflectionUtil.setInstanceField(packet, "g", pitch);
} catch (Exception e) {
e.printStackTrace();
}*/
// Object handle = ReflectionUtil.invokeMethod(
// CRAFTPLAYERCLASS.cast(p), "getHandle", null);
// Object playerConnection = ReflectionUtil.getInstanceField(handle,
// "playerConnection");
// ReflectionUtil.invokeMethod(playerConnection, "sendPacket",
// new Class[] { PACKET_CLASS }, packet);
}
}

View File

@@ -0,0 +1,12 @@
package me.zombie_striker.tts.data;
import java.util.HashMap;
import org.bukkit.Location;
public class PlayObject {
public HashMap<Location,Sound> sound = new HashMap<>();
public HashMap<Location,Integer> pitch = new HashMap<>();
public Location locationOfVoice;
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2016 Zombie_Striker
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package me.zombie_striker.tts.data;
public enum Sound {
a('a',1), b('b',1), c('c',1), d('d',1), e('e',1), f('f',0), g('g',0), h('h',0), i('i',1), j(
'j',0), l('l',1), m('m',1), n('n',1), o('o',1), p('p',1), q('q',0), r('r',1), s('s',0), t(
't',0), u('u',1), v('v',0), w('w',1), x('x',0), y('y',1), z('z',0), th('#',0), ch(
'~',1), E('&',1), A('@',1), I('!',1), oo('%',0), ow('(',1), oh(')',0), space(' ',-1);
public char chars;
public int pitch;
private Sound(char chars,int pitch) {
this.chars = chars;
this.pitch = pitch;
}
public static Sound getClosestChar(String chars) {
if(chars.equals("k"))return c;
for (Sound s : Sound.values()) {
if (chars.equals(s.chars + ""))
return s;
}
return space;
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2016 Zombie_Striker
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package me.zombie_striker.tts.data;
import java.util.ArrayList;
import java.util.List;
public class StoreableStrings {
static List<StoreableStrings> ls = new ArrayList<StoreableStrings>();
public String s;
private StoreableStrings(String b) {
this.s = b;
ls.add(this);
}
public static StoreableStrings getStoreableString(String s) {
for (StoreableStrings ss : ls) {
if (ss.s.equals(s))
return ss;
}
return new StoreableStrings(s);
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright (C) 2016 Zombie_Striker
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package me.zombie_striker.tts.data;
import java.util.ArrayList;
import java.util.List;
public class Word {
public List<Sound> ls = new ArrayList<Sound>();
public Word(String s) {
String[] g = s.replace(",", "").split("");
for (int i = 0; i < g.length; i++) {
ls.add(Sound.getClosestChar(g[i].toLowerCase()));
}
}
public Word(Object[] g) {
for (int i = 0; i < g.length; i++) {
ls.add((Sound) (g[i]));
}
}
public static Word parseString(String s1) {
List<Sound> so = new ArrayList<Sound>();
String s = s1
// four letters
.replaceAll("able", "@bl")
.replaceAll("que", "qu")
// Three letters
.replaceAll("awe", "aw")
.replaceFirst("age", "@j")
.replaceAll("ele", "el&")
.replaceAll("ght", "t")
// two letters
.replaceAll("kn", "n").replaceAll("ph", "f").replaceAll("en", "ehn")
.replaceAll("gh", "g").replaceAll("ch", "~")
.replaceAll("ee", "&").replaceAll("eo", "&")
.replaceAll("ea", "&").replaceAll("oo", "%")
.replaceAll("ou", "%").replaceAll("oi", "%!")
.replaceAll("ia", "!a").replaceAll("ou", ")")
.replaceAll("ow", "(").replaceAll("qu", "q%")
.replaceAll("oa", "%").replaceAll("th", "#")
.replaceAll("ai", "@").replaceAll("iece", "&s")
.replaceAll("ie", "&").replaceAll("ce", "s")
.replaceAll("gg", "g").replaceAll("nn", "n")
.replaceAll("wh", "w").replaceAll("tt", "t")
.replaceAll("le", "l").replaceAll("ll", "l")
.replaceAll("ow", "(").replaceAll("dd", "d")
.replaceAll("pp", "p").replaceAll("rr", "r")
.replaceAll("ey", "&").replaceAll("ay", "@")
.replaceAll("ck", "c")
// One letter.
.replaceAll("k", "c")
// For small sounds
// .replaceAll("x", "xx").replaceAll("v","vv")
// Make sure no existing, common letters are read
.replaceAll("!", "");
if (s.endsWith("o")) {
s = s.substring(0, s.length() - 1) + ")";
}
if ((s.length() - 3 >= 0 && (s.charAt(s.length() - 1) == 'e') && !(s
.equals("the")))
|| (s.length() - 4 >= 0 && (s.charAt(s.length() - 2) == 'e' && s
.charAt(s.length() - 1) == 'r'))) {
int er = 0;
if ((s.length() - 4 >= 0 && (s.charAt(s.length() - 2) == 'e' && s
.charAt(s.length() - 1) == 'r')))
er = 1;
s = s.substring(0, s.length() - 1-er);
if (s.charAt(s.length() - 2 ) == 'a')
s = s.substring(0, s.length() - 2 ) + "@"
+ s.substring(s.length() - 1);
else if (s.charAt(s.length() - 2) == 'e')
s = s.substring(0, s.length() - 2) + "&"
+ s.substring(s.length() - 1);
else if (s.charAt(s.length() - 2 ) == 'i')
s = s.substring(0, s.length() - 2 ) + "!"
+ s.substring(s.length() - 1 );
else if (s.charAt(s.length() - 2) == 'o')
s = s.substring(0, s.length() - 2 ) + ")"
+ s.substring(s.length() - 1 );
else if (s.charAt(s.length() - 2 ) == 'u')
s = s.substring(0, s.length() - 2 ) + "%"
+ s.substring(s.length() - 1 );
if(er==1)s=s+"er";
}
//Secondary stuff
s=s.replaceAll("er", "r");
for (int chars = 0; chars < s.length(); chars++) {
for (Sound s2 : Sound.values()) {
if (s.charAt(chars) == (s2.chars)) {
so.add(s2);
break;
}
}
}
return new Word(so.toArray());
}
}

View File

@@ -0,0 +1,425 @@
package me.zombie_striker.tts.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import me.zombie_striker.tts.CoreTTS;
import me.zombie_striker.tts.data.Sound;
import me.zombie_striker.tts.data.StoreableStrings;
import me.zombie_striker.tts.data.Word;
public class LangFile {
public static HashMap<StoreableStrings, Word> words = new HashMap<StoreableStrings, Word>();
static double currentVersion = 1.2;
public static void verify(File langFile) {
try {
boolean newFile = false;
if (!langFile.exists()) {
langFile.createNewFile();
newFile = true;
}
BufferedReader br = new BufferedReader(new FileReader(langFile));
if (newFile
|| Double.parseDouble(br.readLine().split(": ")[1].trim()) != currentVersion) {
for (int i = 0; i < 2000; i++) {
String word = br.readLine();
if (word == null)
break;
if (word.trim().length() == 0)
continue;
if (word.trim().startsWith("+"))
continue;
StoreableStrings ss = StoreableStrings
.getStoreableString(word.split(" : ")[0].trim());
words.put(ss, new Word(word.split(" : ")[1].trim()));
}
addWords();
BufferedWriter bw = new BufferedWriter(new FileWriter(langFile));
bw.write("+Version: " + currentVersion);
bw.newLine();
bw.write("+ This is a reminder that comments can be made by adding + to the beginning of a line.");
bw.newLine();
bw.write("+ ");
bw.newLine();
bw.write("+ To add a new word, create a new line starting with the word, in lower case, that you want MC to read out");
bw.newLine();
bw.write("+ and add a colon and then the sounds needed to read-out the word.");
bw.newLine();
bw.write("+ ");
bw.newLine();
bw.write("+ Known sounds : a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,#,~,&,@,!,%,( , )");
bw.newLine();
bw.write("+ '#' is 'th', '~' is 'ch', '& is 'E', '@' is A, '!' is 'I' '%' is 'oo' (as in Loot), '(' is 'ow', and ')' is 'oh' ");
bw.newLine();
bw.write("+ Below is an example of how to add a words, and how to use the extra characters");
bw.newLine();
for (Entry<StoreableStrings, Word> wo : words.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Sound s : wo.getValue().ls) {
sb.append(s.chars);
}
bw.write(wo.getKey().s + " : " + sb.toString());
bw.newLine();
}
bw.flush();
bw.close();
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
words.clear();
}
private static void addWords() {
words.put(StoreableStrings.getStoreableString("1"), new Word("won"));
words.put(StoreableStrings.getStoreableString("one"), new Word("won"));
words.put(StoreableStrings.getStoreableString("won"), new Word("won"));
words.put(StoreableStrings.getStoreableString("2"), new Word("t%"));
words.put(StoreableStrings.getStoreableString("to"), new Word("t%"));
words.put(StoreableStrings.getStoreableString("too"), new Word("t%"));
words.put(StoreableStrings.getStoreableString("two"), new Word("t%"));
words.put(StoreableStrings.getStoreableString("3"), new Word("#r&"));
words.put(StoreableStrings.getStoreableString("three"), new Word("#r&"));
words.put(StoreableStrings.getStoreableString("4"), new Word("f)r"));
words.put(StoreableStrings.getStoreableString("four"), new Word("f)r"));
words.put(StoreableStrings.getStoreableString("5"), new Word("f!vv"));
words.put(StoreableStrings.getStoreableString("five"), new Word("f!vv"));
words.put(StoreableStrings.getStoreableString("6"), new Word("sixx"));
words.put(StoreableStrings.getStoreableString("six"), new Word("sixx"));
words.put(StoreableStrings.getStoreableString("7"), new Word("seven"));
words.put(StoreableStrings.getStoreableString("seven"), new Word(
"seven"));
words.put(StoreableStrings.getStoreableString("8"), new Word("@t"));
words.put(StoreableStrings.getStoreableString("eight"), new Word("@t"));
words.put(StoreableStrings.getStoreableString("9"), new Word("n!nne"));
words.put(StoreableStrings.getStoreableString("nine"),
new Word("n!nne"));
words.put(StoreableStrings.getStoreableString("0"), new Word("z&ro"));
words.put(StoreableStrings.getStoreableString("zero"), new Word("z&ro"));
words.put(StoreableStrings.getStoreableString("10"), new Word("ten"));
words.put(StoreableStrings.getStoreableString("ten"), new Word("ten"));
words.put(StoreableStrings.getStoreableString("a"), new Word("a")); // Changed
// from
// @
// to
// a
// for
// multiple
// languages
words.put(StoreableStrings.getStoreableString("b"), new Word("b&"));
words.put(StoreableStrings.getStoreableString("c"), new Word("s&"));
words.put(StoreableStrings.getStoreableString("d"), new Word("d&"));
words.put(StoreableStrings.getStoreableString("e"), new Word("&"));
words.put(StoreableStrings.getStoreableString("f"), new Word("ef"));
words.put(StoreableStrings.getStoreableString("g"), new Word("j&"));
words.put(StoreableStrings.getStoreableString("h"), new Word("@~"));
words.put(StoreableStrings.getStoreableString("i"), new Word("!"));
words.put(StoreableStrings.getStoreableString("j"), new Word("j@"));
words.put(StoreableStrings.getStoreableString("k"), new Word("c@"));
words.put(StoreableStrings.getStoreableString("l"), new Word("el"));
words.put(StoreableStrings.getStoreableString("m"), new Word("em"));
words.put(StoreableStrings.getStoreableString("n"), new Word("en"));
words.put(StoreableStrings.getStoreableString("o"), new Word(")"));
words.put(StoreableStrings.getStoreableString("p"), new Word("p&"));
words.put(StoreableStrings.getStoreableString("q"), new Word("qy%"));
words.put(StoreableStrings.getStoreableString("r"), new Word("ar"));
words.put(StoreableStrings.getStoreableString("s"), new Word("es"));
words.put(StoreableStrings.getStoreableString("t"), new Word("t&"));
words.put(StoreableStrings.getStoreableString("u"), new Word("y%"));
words.put(StoreableStrings.getStoreableString("v"), new Word("v&"));
words.put(StoreableStrings.getStoreableString("w"), new Word("dubl y%"));
words.put(StoreableStrings.getStoreableString("x"), new Word("exx"));
words.put(StoreableStrings.getStoreableString("y"), new Word("w!"));
words.put(StoreableStrings.getStoreableString("z"), new Word("z&"));
words.put(StoreableStrings.getStoreableString("future"), new Word(
"f%~or"));
words.put(StoreableStrings.getStoreableString("damn"), new Word("dam"));
words.put(StoreableStrings.getStoreableString("dance"),
new Word("dans"));
words.put(StoreableStrings.getStoreableString("cat"), new Word("cat"));
words.put(StoreableStrings.getStoreableString("nice"), new Word("n!s"));
words.put(StoreableStrings.getStoreableString("high"), new Word("h!"));
words.put(StoreableStrings.getStoreableString("sky"), new Word("h!"));
words.put(StoreableStrings.getStoreableString("skyblock"), new Word(
"h!"));
words.put(StoreableStrings.getStoreableString("eye"), new Word("!"));
words.put(StoreableStrings.getStoreableString("eyes"), new Word("!s"));
words.put(StoreableStrings.getStoreableString("have"), new Word("hav"));
words.put(StoreableStrings.getStoreableString("fancy"), new Word(
"fanc&"));
words.put(StoreableStrings.getStoreableString("fantasy"), new Word(
"fantas&"));
words.put(StoreableStrings.getStoreableString("pineapple"), new Word(
"p!napl"));
words.put(StoreableStrings.getStoreableString("because"), new Word(
"b&cus"));
words.put(StoreableStrings.getStoreableString("makes"),
new Word("m@cs"));
words.put(StoreableStrings.getStoreableString("voice"),
new Word("v%!s"));
words.put(StoreableStrings.getStoreableString("thread"), new Word(
"#red"));
words.put(StoreableStrings.getStoreableString("easy"), new Word("&s&"));
words.put(StoreableStrings.getStoreableString("easier"), new Word(
"&s&r"));
words.put(StoreableStrings.getStoreableString("easiest"), new Word(
"&s&est"));
words.put(StoreableStrings.getStoreableString("beautiful"), new Word(
"b&yutiful"));
words.put(StoreableStrings.getStoreableString("beautifull"), new Word(
"b&yutiful"));
words.put(StoreableStrings.getStoreableString("secret"), new Word(
"s&cret"));
words.put(StoreableStrings.getStoreableString("iron"), new Word("!ron"));
words.put(StoreableStrings.getStoreableString("gold"), new Word("G)ld"));
words.put(StoreableStrings.getStoreableString("queue"), new Word("q%"));
words.put(StoreableStrings.getStoreableString("work"), new Word("wrc"));
words.put(StoreableStrings.getStoreableString("working"), new Word(
"wrcing"));
words.put(StoreableStrings.getStoreableString("robot"), new Word(
"r)bot"));
words.put(StoreableStrings.getStoreableString("loot"), new Word("l%t"));
words.put(StoreableStrings.getStoreableString("pi"), new Word("p!"));
words.put(StoreableStrings.getStoreableString("pie"), new Word("p!"));
words.put(StoreableStrings.getStoreableString("pizza"),
new Word("p&za"));
words.put(StoreableStrings.getStoreableString("lite"), new Word("l!t"));
words.put(StoreableStrings.getStoreableString("light"), new Word("l!t"));
words.put(StoreableStrings.getStoreableString("im"), new Word("!m"));
words.put(StoreableStrings.getStoreableString("he"), new Word("h&"));
words.put(StoreableStrings.getStoreableString("hes"), new Word("h&s"));
words.put(StoreableStrings.getStoreableString("life"), new Word("l!f"));
words.put(StoreableStrings.getStoreableString("man"), new Word("man"));
words.put(StoreableStrings.getStoreableString("human"), new Word(
"h%man"));
words.put(StoreableStrings.getStoreableString("you"), new Word("y%"));
words.put(StoreableStrings.getStoreableString("crazy"), new Word(
"cr@z&"));
words.put(StoreableStrings.getStoreableString("love"), new Word("luvv"));
words.put(StoreableStrings.getStoreableString("once"), new Word("wons"));
words.put(StoreableStrings.getStoreableString("me"), new Word("m&"));
words.put(StoreableStrings.getStoreableString("now"), new Word("n(w"));
words.put(StoreableStrings.getStoreableString("know"), new Word("n("));
words.put(StoreableStrings.getStoreableString("knowledge"), new Word(
"n(lej"));
words.put(StoreableStrings.getStoreableString("ledge"), new Word("lej"));
words.put(StoreableStrings.getStoreableString("edge"), new Word("ej"));
words.put(StoreableStrings.getStoreableString("baby"), new Word("b@b&"));
words.put(StoreableStrings.getStoreableString("like"), new Word("l!c"));
words.put(StoreableStrings.getStoreableString("any"), new Word("a,n,&"));
words.put(StoreableStrings.getStoreableString("anyway"), new Word(
"a,n,&,w,a,y"));
words.put(StoreableStrings.getStoreableString("anyways"), new Word(
"a,n,&,w,a,y,s"));
words.put(StoreableStrings.getStoreableString("were"),
new Word("w,e,r"));
words.put(StoreableStrings.getStoreableString("die"), new Word("d,!"));
words.put(StoreableStrings.getStoreableString("friend"), new Word(
"f,r,e,n,d"));
words.put(StoreableStrings.getStoreableString("friends"), new Word(
"f,r,e,n,d,s"));
words.put(StoreableStrings.getStoreableString("no"), new Word("n,)"));
words.put(StoreableStrings.getStoreableString("my"), new Word("m,!"));
words.put(StoreableStrings.getStoreableString("so"), new Word("s,)"));
words.put(StoreableStrings.getStoreableString("here"),
new Word("h,&,r"));
words.put(StoreableStrings.getStoreableString("some"),
new Word("s,o,m"));
words.put(StoreableStrings.getStoreableString("together"), new Word(
"t,%,g,e,#,e,r"));
words.put(StoreableStrings.getStoreableString("the"), new Word("#,&"));
words.put(StoreableStrings.getStoreableString("whole"), new Word(
"h,),l"));
words.put(StoreableStrings.getStoreableString("we"), new Word("w,&"));
words.put(StoreableStrings.getStoreableString("somebody"), new Word(
"s,o,m,b,o,d,&"));
words.put(StoreableStrings.getStoreableString("heres"), new Word(
"h,&,r,s"));
words.put(StoreableStrings.getStoreableString("over"), new Word(
"%,v,e,r"));
words.put(StoreableStrings.getStoreableString("what"), new Word(
"w,a,h,t"));
words.put(StoreableStrings.getStoreableString("angels"), new Word(
"a,n,j,e,l,s"));
words.put(StoreableStrings.getStoreableString("angel"), new Word(
"a,n,j,e,l"));
words.put(StoreableStrings.getStoreableString("are"), new Word("a,r"));
words.put(StoreableStrings.getStoreableString("go"), new Word("g,%"));
words.put(StoreableStrings.getStoreableString("sandstone"), new Word(
"s,a,n,d,s,t,),n"));
words.put(StoreableStrings.getStoreableString("stone"), new Word(
"s,t,),n"));
words.put(StoreableStrings.getStoreableString("going"), new Word(
"g,%,i,n,g"));
words.put(StoreableStrings.getStoreableString("oh"), new Word(")"));
words.put(StoreableStrings.getStoreableString("fire"),
new Word("f,!,r"));
words.put(StoreableStrings.getStoreableString("do"), new Word("d,%"));
words.put(StoreableStrings.getStoreableString("doing"), new Word(
"d,%,i,n,g"));
words.put(StoreableStrings.getStoreableString("people"), new Word(
"p,&,p,),l"));
words.put(StoreableStrings.getStoreableString("take"),
new Word("t,@,c"));
words.put(StoreableStrings.getStoreableString("sign"),
new Word("s,!,n"));
words.put(StoreableStrings.getStoreableString("town"),
new Word("t,(,n"));
words.put(StoreableStrings.getStoreableString("hi"), new Word("h,!"));
words.put(StoreableStrings.getStoreableString("hia"), new Word("h,!,a"));
words.put(StoreableStrings.getStoreableString("be"), new Word(
"b&"));
words.put(StoreableStrings.getStoreableString("cute"),
new Word("c,%,t"));
words.put(StoreableStrings.getStoreableString("maybe"), new Word(
"m,@,b,&,&"));
words.put(StoreableStrings.getStoreableString("wood"),
new Word("w,%,d"));
words.put(StoreableStrings.getStoreableString("ocean"), new Word(
"),s,u,n"));
words.put(StoreableStrings.getStoreableString("would"), new Word(
"w,%,d"));
words.put(StoreableStrings.getStoreableString("kind"), new Word(
"c,!,n,d"));
words.put(StoreableStrings.getStoreableString("kindly"), new Word(
"c,!,n,d,l,y"));
words.put(StoreableStrings.getStoreableString("omg"), new Word(
"),e,m,j,&"));
words.put(StoreableStrings.getStoreableString("lol"), new Word(
"e,l,),e,l"));
words.put(StoreableStrings.getStoreableString("gtfo"), new Word(
"j,&,t,&,e,f,)"));
words.put(StoreableStrings.getStoreableString("wtf"), new Word(
"w,u,t, ,#,e, ,e,f"));
words.put(StoreableStrings.getStoreableString("wth"), new Word(
"w,u,t, ,#,e, ,@,~"));
words.put(StoreableStrings.getStoreableString("wrench"), new Word(
"w,r,e,n,~"));
words.put(StoreableStrings.getStoreableString("makes"), new Word(
"m,@,c,s"));
words.put(StoreableStrings.getStoreableString("laugh"), new Word(
"l,a,f"));
words.put(StoreableStrings.getStoreableString("photo"), new Word(
"f,),t,)"));
words.put(StoreableStrings.getStoreableString("photograph"), new Word(
"f,),t,),g,r,a,f"));
// Italian
words.put(StoreableStrings.getStoreableString("ciao"), new Word("sao"));
words.put(StoreableStrings.getStoreableString("tutti"),
new Word("t%t&"));
words.put(StoreableStrings.getStoreableString("mi"), new Word("m&"));
words.put(StoreableStrings.getStoreableString("chiamo"), new Word(
"~amo"));
words.put(StoreableStrings.getStoreableString("mio"), new Word("m&o"));
words.put(StoreableStrings.getStoreableString("giocatore"), new Word(
"z%gator@"));
words.put(StoreableStrings.getStoreableString("moderatore"), new Word(
"moderator@"));
words.put(StoreableStrings.getStoreableString("amministratore"),
new Word("aministrator@"));
words.put(StoreableStrings.getStoreableString("passeggio"), new Word(
"passezz)"));
words.put(StoreableStrings.getStoreableString("esecuzione"), new Word(
"esec%zune"));
words.put(StoreableStrings.getStoreableString("collegare"), new Word(
"c)legare"));
words.put(StoreableStrings.getStoreableString("pelle"), new Word(
"pel@"));
words.put(StoreableStrings.getStoreableString("diamante"), new Word(
"d&amonte"));
words.put(StoreableStrings.getStoreableString("oro"), new Word(
"or)"));
words.put(StoreableStrings.getStoreableString("ferro"), new Word(
"fe#ro"));
words.put(StoreableStrings.getStoreableString("mela"), new Word(
"mela"));
words.put(StoreableStrings.getStoreableString("melone"), new Word(
"mel)ne"));
words.put(StoreableStrings.getStoreableString("rotaia"), new Word(
"rotaia"));
words.put(StoreableStrings.getStoreableString("pietra"), new Word(
"p&etra"));
words.put(StoreableStrings.getStoreableString("sporco"), new Word(
"sporco"));
words.put(StoreableStrings.getStoreableString("los"), new Word(
"l)s"));
words.put(StoreableStrings.getStoreableString("lo"), new Word(
"l)s"));
words.put(StoreableStrings.getStoreableString("granito"), new Word(
"gran&to"));
words.put(StoreableStrings.getStoreableString("ossidiana"), new Word(
")sidana"));
words.put(StoreableStrings.getStoreableString("letto"), new Word(
"let)"));
words.put(StoreableStrings.getStoreableString("uomini"), new Word(
"%amin&"));
words.put(StoreableStrings.getStoreableString("uomo"), new Word(
"%om)"));
words.put(StoreableStrings.getStoreableString("cane"), new Word(
"cane"));
words.put(StoreableStrings.getStoreableString("gatto"), new Word(
"gat)"));
words.put(StoreableStrings.getStoreableString("lupo"), new Word(
"l%p)"));
words.put(StoreableStrings.getStoreableString("calamaro"), new Word(
"calamar)"));
words.put(StoreableStrings.getStoreableString("mucca"), new Word(
"m%ca"));
words.put(StoreableStrings.getStoreableString("mucche"), new Word(
"m%ce"));
words.put(StoreableStrings.getStoreableString("pollo"), new Word(
"p)lo"));
words.put(StoreableStrings.getStoreableString("polli"), new Word(
"poli"));
words.put(StoreableStrings.getStoreableString("bloccare"), new Word(
"blocare"));
words.put(StoreableStrings.getStoreableString("blocchi"), new Word(
"bloc&"));
words.put(StoreableStrings.getStoreableString("cielo"), new Word(
"~elo"));
words.put(StoreableStrings.getStoreableString("Luna"), new Word(
"l%na"));
words.put(StoreableStrings.getStoreableString("saluti"), new Word(
"sal%t&"));
words.put(StoreableStrings.getStoreableString("saluto"), new Word(
"saluto"));
words.put(StoreableStrings.getStoreableString("bene"), new Word(
"bene"));
words.put(StoreableStrings.getStoreableString("cattivo"), new Word(
"cat&v)"));
words.put(StoreableStrings.getStoreableString("peggio"), new Word(
"pedz)"));
}
}

View File

@@ -0,0 +1,81 @@
package me.zombie_striker.tts.util;
import me.zombie_striker.tts.CoreTTS;
import me.zombie_striker.tts.data.PlayObject;
import me.zombie_striker.tts.data.Sound;
import me.zombie_striker.tts.data.StoreableStrings;
import me.zombie_striker.tts.data.Word;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class TalkUtil {
private static CoreTTS core;
static{
core = (CoreTTS) Bukkit.getPluginManager().getPlugin("TextToSpeech");
}
public static void speakOut(String fullText, Player from){
int pitch = core.pitch.get(from.getUniqueId());
speakOut(fullText, from.getLocation(), pitch);
}
public static void speakOut(String fullText, Location from, int pitch){
String[] message = ChatColor.stripColor(fullText.toLowerCase()).split(" ");
long currentTick = core.getTick() + 3;
for (int i = 0; i < message.length; i++) {
int pause = 0;
String m = message[i];
//int pitch =core.pitch.get(e.getPlayer().getUniqueId());
if (m.startsWith("<") && m.contains(":")) {
pitch = Integer.parseInt(m.split(":")[1].replaceAll(">", ""));
m = m.substring(1);
}else{
m = m.replaceAll("9", " 9 ").replaceAll("8", " 8 ")
.replaceAll("7", " 7 ").replaceAll("6", " 6 ")
.replaceAll("5", " 5 ").replaceAll("4", " 4 ")
.replaceAll("3", " 3 ").replaceAll("2", " 2 ")
.replaceAll("1", " 1 ").replaceAll("0", " 0 ");
}
if (m.contains(",")) {
m = m.replaceAll(",", "");
pause += 2;
}
if (m.contains(".")) {
m = m.replaceAll(".", "");
pause += 3;
}
if (m.contains("'"))
m = m.replaceAll("'", "");
StoreableStrings ss = StoreableStrings.getStoreableString(m
.toLowerCase());
Word w = null;
if (core.words.containsKey(ss)) {
w = core.words.get(ss);
} else {
w = Word.parseString(ss.s.toLowerCase());
core.words.put(ss, w);
}
for (int l = 0; l < w.ls.size(); l++) {
PlayObject ls = core.map.get(currentTick);
if (ls == null)
ls = new PlayObject();
ls.sound.put(from, w.ls.get(l));
ls.pitch.put(from, pitch);
ls.locationOfVoice=from;
core.map.put(currentTick, ls);
currentTick++;
//Make the I sound longer
if (w.ls.get(l) == Sound.I)
currentTick++;
}
currentTick += 0 + pause;
}
}
}