From 60cd57f0bdc0c3b3fd1e5f8a6ee36c303d234d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9C=9F=E5=BF=83?= Date: Sat, 9 Jan 2021 22:57:34 +0800 Subject: [PATCH] =?UTF-8?q?QQ=E9=9F=B3=E4=B9=90API=E5=88=9D=E6=AD=A5?= =?UTF-8?q?=E5=AE=8C=E6=88=90=20=E6=8F=92=E4=BB=B6=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E5=8F=91=E9=80=81=E5=AE=8C=E6=88=90=20=E5=8D=87=E7=BA=A7Gradle?= =?UTF-8?q?=206.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle/wrapper/gradle-wrapper.properties | 2 +- .../me/zhenxin/zmusic/bstats/MetricsBC.java | 214 +++++++++--------- .../zhenxin/zmusic/bstats/MetricsBukkit.java | 202 ++++++++--------- src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt | 6 + src/main/kotlin/me/zhenxin/zmusic/ZMusicBC.kt | 1 + .../kotlin/me/zhenxin/zmusic/ZMusicBukkit.kt | 11 +- .../kotlin/me/zhenxin/zmusic/command/CmdEx.kt | 37 +-- .../kotlin/me/zhenxin/zmusic/config/Config.kt | 12 +- .../zhenxin/zmusic/module/api/BiliBiliApi.kt | 2 +- .../me/zhenxin/zmusic/module/api/KugouApi.kt | 1 - .../me/zhenxin/zmusic/module/api/KuwoApi.kt | 1 - .../zhenxin/zmusic/module/api/NeteaseApi.kt | 2 +- .../me/zhenxin/zmusic/module/api/QQApi.kt | 39 +++- .../zhenxin/zmusic/module/sender/SenderBC.kt | 10 +- .../zmusic/module/sender/SenderBukkit.kt | 13 +- .../zmusic/module/version/VersionBukkit.kt | 32 --- .../zhenxin/zmusic/util/ext/InputStreamExt.kt | 13 ++ 17 files changed, 297 insertions(+), 301 deletions(-) delete mode 100644 src/main/kotlin/me/zhenxin/zmusic/module/version/VersionBukkit.kt diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index be52383e..da9702f9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/me/zhenxin/zmusic/bstats/MetricsBC.java b/src/main/java/me/zhenxin/zmusic/bstats/MetricsBC.java index 5cf5b59c..b4dc0db5 100644 --- a/src/main/java/me/zhenxin/zmusic/bstats/MetricsBC.java +++ b/src/main/java/me/zhenxin/zmusic/bstats/MetricsBC.java @@ -31,6 +31,17 @@ @SuppressWarnings({"WeakerAccess", "unused"}) public class MetricsBC { + // 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/bungeecord"; + // A list with all known metrics class objects including this one + private static final List knownMetricsInstances = new ArrayList<>(); + // Should the sent data be logged? + private static boolean logSentData; + // Should the response text be logged? + private static boolean logResponseStatusText; + static { // You can use the property to disable the check in your test environment if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { @@ -45,43 +56,23 @@ public class MetricsBC { } } - // 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/bungeecord"; - // The plugin private final Plugin plugin; - // The plugin id private final int pluginId; - + // A list with all custom charts + private final List charts = new ArrayList<>(); // Is bStats enabled on this server? private boolean enabled; - // The uuid of the server private String serverUUID; - // Should failed requests be logged? private boolean logFailedRequests = false; - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // A list with all known metrics class objects including this one - private static final List knownMetricsInstances = new ArrayList<>(); - - // A list with all custom charts - private final List charts = new ArrayList<>(); - /** * Class constructor. * - * @param plugin The plugin which stats should be submitted. + * @param plugin The plugin which stats should be submitted. * @param pluginId The id of the plugin. * It can be found at What is my plugin id? */ @@ -123,6 +114,83 @@ public MetricsBC(Plugin plugin, int pluginId) { } } + /** + * Links an other metrics class with this class. + * This method is called using Reflection. + * + * @param metrics An object of the metrics class to link. + */ + public static void linkMetrics(Object metrics) { + knownMetricsInstances.add(metrics); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + + 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); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * 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(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + /** * Checks if bStats is enabled. * @@ -144,16 +212,6 @@ public void addCustomChart(CustomChart chart) { charts.add(chart); } - /** - * Links an other metrics class with this class. - * This method is called using Reflection. - * - * @param metrics An object of the metrics class to link. - */ - public static void linkMetrics(Object metrics) { - knownMetricsInstances.add(metrics); - } - /** * Gets the plugin specific data. * This method is called using Reflection. @@ -244,7 +302,8 @@ private void submitData() { if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } } data.add("plugins", pluginData); @@ -308,7 +367,8 @@ private Class getFirstBStatsClass() { try { // Let's check if a class with the given name exists. return Class.forName(className); - } catch (ClassNotFoundException ignored) { } + } catch (ClassNotFoundException ignored) { + } } writeFile(tempFile, getClass().getName()); return getClass(); @@ -339,7 +399,7 @@ private String readFile(File file) throws IOException { /** * Writes a String to a file. It also adds a note for the user, * - * @param file The file to write to. Cannot be null. + * @param file The file to write to. Cannot be null. * @param lines The lines to write. * @throws IOException If something did not work :( */ @@ -352,74 +412,6 @@ private void writeFile(File file, String... lines) throws IOException { } } - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - - 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); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * 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(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - - /** * Represents a custom chart. */ @@ -473,7 +465,7 @@ public static class SimplePie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimplePie(String chartId, Callable callable) { @@ -504,7 +496,7 @@ public static class AdvancedPie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedPie(String chartId, Callable> callable) { @@ -548,7 +540,7 @@ public static class DrilldownPie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public DrilldownPie(String chartId, Callable>> callable) { @@ -597,7 +589,7 @@ public static class SingleLineChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SingleLineChart(String chartId, Callable callable) { @@ -629,7 +621,7 @@ public static class MultiLineChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public MultiLineChart(String chartId, Callable> callable) { @@ -674,7 +666,7 @@ public static class SimpleBarChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimpleBarChart(String chartId, Callable> callable) { @@ -712,7 +704,7 @@ public static class AdvancedBarChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedBarChart(String chartId, Callable> callable) { diff --git a/src/main/java/me/zhenxin/zmusic/bstats/MetricsBukkit.java b/src/main/java/me/zhenxin/zmusic/bstats/MetricsBukkit.java index bb8ac1cc..81c3d85b 100644 --- a/src/main/java/me/zhenxin/zmusic/bstats/MetricsBukkit.java +++ b/src/main/java/me/zhenxin/zmusic/bstats/MetricsBukkit.java @@ -30,6 +30,19 @@ @SuppressWarnings({"WeakerAccess", "unused"}) public class MetricsBukkit { + // 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/bukkit"; + // Should failed requests be logged? + private static boolean logFailedRequests; + // Should the sent data be logged? + private static boolean logSentData; + // Should the response text be logged? + private static boolean logResponseStatusText; + // The uuid of the server + private static String serverUUID; + static { // You can use the property to disable the check in your test environment if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { @@ -44,40 +57,19 @@ public class MetricsBukkit { } } - // 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/bukkit"; - - // Is bStats enabled on this server? - private boolean enabled; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // Should the sent data be logged? - private static boolean logSentData; - - // Should the response text be logged? - private static boolean logResponseStatusText; - - // The uuid of the server - private static String serverUUID; - // The plugin private final Plugin plugin; - // The plugin id private final int pluginId; - // A list with all custom charts private final List charts = new ArrayList<>(); + // Is bStats enabled on this server? + private boolean enabled; /** * Class constructor. * - * @param plugin The plugin which stats should be submitted. + * @param plugin The plugin which stats should be submitted. * @param pluginId The id of the plugin. * It can be found at What is my plugin id? */ @@ -116,7 +108,8 @@ public MetricsBukkit(Plugin plugin, int pluginId) { ).copyDefaults(true); try { config.save(configFile); - } catch (IOException ignored) { } + } catch (IOException ignored) { + } } // Load the data @@ -134,7 +127,8 @@ public MetricsBukkit(Plugin plugin, int pluginId) { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } // Register our service Bukkit.getServicesManager().register(MetricsBukkit.class, this, plugin, ServicePriority.Normal); @@ -145,6 +139,74 @@ public MetricsBukkit(Plugin plugin, int pluginId) { } } + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, 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!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + 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); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * 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(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + /** * Checks if bStats is enabled. * @@ -298,9 +360,11 @@ private void submitData() { } } } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } } - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } data.add("plugins", pluginData); @@ -319,74 +383,6 @@ private void submitData() { }).start(); } - /** - * Sends the data to the bStats server. - * - * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(Plugin plugin, 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!"); - } - if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data); - } - 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); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - - if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } - - /** - * 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(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - /** * Represents a custom chart. */ @@ -440,7 +436,7 @@ public static class SimplePie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimplePie(String chartId, Callable callable) { @@ -471,7 +467,7 @@ public static class AdvancedPie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedPie(String chartId, Callable> callable) { @@ -515,7 +511,7 @@ public static class DrilldownPie extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public DrilldownPie(String chartId, Callable>> callable) { @@ -564,7 +560,7 @@ public static class SingleLineChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SingleLineChart(String chartId, Callable callable) { @@ -596,7 +592,7 @@ public static class MultiLineChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public MultiLineChart(String chartId, Callable> callable) { @@ -641,7 +637,7 @@ public static class SimpleBarChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimpleBarChart(String chartId, Callable> callable) { @@ -679,7 +675,7 @@ public static class AdvancedBarChart extends CustomChart { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedBarChart(String chartId, Callable> callable) { diff --git a/src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt b/src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt index 306a30ef..4b4bab45 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt @@ -9,6 +9,9 @@ import java.net.CookieHandler import java.net.CookieManager object ZMusic { + + var plugin = Any() + var isBC = false var isVIP = false var isEnable: Boolean = true @@ -26,6 +29,9 @@ object ZMusic { var thisVerCode = 202101060 fun enable() { + if (!dataFolder.exists()) dataFolder.mkdir() + val lang = File(dataFolder, "/language/") + if (!lang.exists()) lang.mkdir() (" ______ __ __ _ \n" + " |___ / | \\/ | (_) \n" + " / / | \\ / | _ _ ___ _ ___ \n" + diff --git a/src/main/kotlin/me/zhenxin/zmusic/ZMusicBC.kt b/src/main/kotlin/me/zhenxin/zmusic/ZMusicBC.kt index 46aea917..5653492f 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/ZMusicBC.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/ZMusicBC.kt @@ -13,6 +13,7 @@ import net.md_5.bungee.api.plugin.Plugin class ZMusicBC : Plugin() { override fun onEnable() { + ZMusic.plugin = this proxy.registerChannel("zmusic:channel") proxy.registerChannel("allmusic:channel") proxy.registerChannel("AudioBuffer") diff --git a/src/main/kotlin/me/zhenxin/zmusic/ZMusicBukkit.kt b/src/main/kotlin/me/zhenxin/zmusic/ZMusicBukkit.kt index b8a33d94..594ce3aa 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/ZMusicBukkit.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/ZMusicBukkit.kt @@ -5,7 +5,6 @@ import me.zhenxin.zmusic.command.CmdBukkit import me.zhenxin.zmusic.config.Lang import me.zhenxin.zmusic.module.logger.LoggerBukkit import me.zhenxin.zmusic.module.tasker.TaskerBukkit -import me.zhenxin.zmusic.module.version.VersionBukkit import me.zhenxin.zmusic.util.VersionCheck import org.bukkit.plugin.java.JavaPlugin @@ -13,16 +12,12 @@ import org.bukkit.plugin.java.JavaPlugin class ZMusicBukkit : JavaPlugin() { override fun onEnable() { + ZMusic.plugin = this getCommand("zm")?.setExecutor(CmdBukkit()) getCommand("zm")?.tabCompleter = CmdBukkit() MetricsBukkit(this, 7291) - val version = VersionBukkit() - server.messenger.registerOutgoingPluginChannel(this, "allmusic:channel") - if (!version.high("1.12")) { - server.messenger.registerOutgoingPluginChannel(this, "AudioBuffer") - } ZMusic.isBC = true ZMusic.logger = LoggerBukkit(server.consoleSender) ZMusic.thisVer = description.version @@ -39,6 +34,10 @@ class ZMusicBukkit : JavaPlugin() { ZMusic.logger.error(Lang.Loading.zLibNoOK.replace("%version%", ZMusic.zLibVer)) ZMusic.zLibIsOK = false } + server.messenger.registerOutgoingPluginChannel(this, "allmusic:channel") + if (!VersionCheck("1.12", server.bukkitVersion).isHigherThan()) { + server.messenger.registerOutgoingPluginChannel(this, "AudioBuffer") + } ZMusic.enable() } } diff --git a/src/main/kotlin/me/zhenxin/zmusic/command/CmdEx.kt b/src/main/kotlin/me/zhenxin/zmusic/command/CmdEx.kt index d112fb93..2e076baa 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/command/CmdEx.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/command/CmdEx.kt @@ -1,6 +1,5 @@ package me.zhenxin.zmusic.command -import com.alibaba.fastjson.JSONObject import me.zhenxin.zmusic.ZMusic import me.zhenxin.zmusic.config.Lang import me.zhenxin.zmusic.module.Sender @@ -38,31 +37,19 @@ object CmdEx { } "test" -> { - when (args[1].toLowerCase()) { - "qq" -> { - val api = ApiType.QQ.getApi() - val data = api.search("璃月", count = 8) - sender.sendMsg(data.toJSONString()) - } - "163" -> { - val api = ApiType.NETEASE.getApi() - val data = api.search("璃月", count = 8) - sender.sendMsg(data.toJSONString()) - data.getJSONArray("data").forEach { - it as JSONObject - sender.sendMsg(api.url(it.getString("id")).toJSONString()) - } - } - "bili" -> { - val api = ApiType.BILIBILI.getApi() - val data = api.search("璃月", count = 8) - sender.sendMsg(data.toJSONString()) - data.getJSONArray("data").forEach { - it as JSONObject - sender.sendMsg(api.url(it.getString("id")).toJSONString()) - } - } + val type = when (args[1].toLowerCase()) { + "qq" -> ApiType.QQ + "163" -> ApiType.NETEASE + "bili" -> ApiType.BILIBILI + else -> ApiType.NETEASE } + val api = type.getApi() + val data = api.search(args[2], count = 1) + val list = data.getJSONArray("data") + sender.sendMsg(data.toJSONString()) + val url = api.url(list.getJSONObject(0).getString("id")).getJSONObject("data").getString("url") + sender.sendMsg(url) + sender.sendPMsgToAM("[Play]$url") } else -> { sender.sendMsg(Lang.Help.tip) diff --git a/src/main/kotlin/me/zhenxin/zmusic/config/Config.kt b/src/main/kotlin/me/zhenxin/zmusic/config/Config.kt index 3273a669..eef486e4 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/config/Config.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/config/Config.kt @@ -1,7 +1,9 @@ package me.zhenxin.zmusic.config import me.zhenxin.zmusic.ZMusic +import me.zhenxin.zmusic.util.ext.InputStreamExt.saveData import org.yaml.snakeyaml.Yaml +import java.io.File object Config { @@ -57,9 +59,13 @@ object Config { fun load() { var temp: Any val yaml = Yaml() - val inputStream = this.javaClass.classLoader - .getResourceAsStream("config.yml") - val config: Map = yaml.load(inputStream) + var file = File(ZMusic.dataFolder, "/config.yml") + if (!file.exists()) { + val tmp = this.javaClass.classLoader.getResourceAsStream("config.yml") + tmp.saveData(file.absolutePath) + file = File(ZMusic.dataFolder, "/config.yml") + } + val config: Map = yaml.load(file.inputStream()) version = config["version"] as Int update = config["update"] as Boolean prefix = (config["prefix"] as String).replace("&", "§") diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/api/BiliBiliApi.kt b/src/main/kotlin/me/zhenxin/zmusic/module/api/BiliBiliApi.kt index 62ddf3d6..befc108a 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/api/BiliBiliApi.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/api/BiliBiliApi.kt @@ -67,7 +67,7 @@ class BiliBiliApi : Api { ) json["code"] = 200 val obj = JSONObject() - obj["url"] = url + obj["url"] = mp3Url json["data"] = obj return json } diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/api/KugouApi.kt b/src/main/kotlin/me/zhenxin/zmusic/module/api/KugouApi.kt index ebf487cf..6e5b39c9 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/api/KugouApi.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/api/KugouApi.kt @@ -1,7 +1,6 @@ package me.zhenxin.zmusic.module.api import com.alibaba.fastjson.JSONObject -import com.google.gson.JsonObject import me.zhenxin.zmusic.module.Api class KugouApi : Api { diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/api/KuwoApi.kt b/src/main/kotlin/me/zhenxin/zmusic/module/api/KuwoApi.kt index c945f51b..3cd3d3ee 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/api/KuwoApi.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/api/KuwoApi.kt @@ -1,7 +1,6 @@ package me.zhenxin.zmusic.module.api import com.alibaba.fastjson.JSONObject -import com.google.gson.JsonObject import me.zhenxin.zmusic.module.Api class KuwoApi : Api { diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/api/NeteaseApi.kt b/src/main/kotlin/me/zhenxin/zmusic/module/api/NeteaseApi.kt index c5e8d5ee..a8d89322 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/api/NeteaseApi.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/api/NeteaseApi.kt @@ -12,7 +12,7 @@ class NeteaseApi : Api { override fun search(key: String, page: Int, count: Int): JSONObject { val json = JSONObject() val array = JSONArray() - val data = JSON.parseObject(get("/search?keywords=${URLEncoder.encode(key, "UTF-8")}")) + val data = JSON.parseObject(get("/search?keywords=${URLEncoder.encode(key, "UTF-8")}&limit=$count")) val result = data.getJSONObject("result") val songs = result.getJSONArray("songs") songs.forEach { song -> diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/api/QQApi.kt b/src/main/kotlin/me/zhenxin/zmusic/module/api/QQApi.kt index 5186ef8a..5ff0b7ac 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/api/QQApi.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/api/QQApi.kt @@ -1,6 +1,7 @@ package me.zhenxin.zmusic.module.api import com.alibaba.fastjson.JSON +import com.alibaba.fastjson.JSONArray import com.alibaba.fastjson.JSONObject import me.zhenxin.zmusic.config.Config import me.zhenxin.zmusic.module.Api @@ -9,16 +10,48 @@ import java.net.URLEncoder class QQApi : Api { override val api = Config.Api.qq override fun search(key: String, page: Int, count: Int): JSONObject { + val json = JSONObject() + val array = JSONArray() val data = JSON.parseObject(get("/search?key=${URLEncoder.encode(key, "UTF-8")}&pageNo=$page&pageSize=$count")) - return data + val result = data.getJSONObject("data") + val list = result.getJSONArray("list") + list.forEach { + it as JSONObject + val obj = info(it.getString("songmid")) + array.add(obj) + } + json["code"] = 200 + json["data"] = array + return json } override fun info(id: String): JSONObject { - TODO("Not yet implemented") + val json = JSONObject() + val data = JSON.parseObject(get("/song?songmid=$id")) + val result = data.getJSONObject("data") + val info = result.getJSONObject("track_info") + json["id"] = info.getString("mid") + json["name"] = info.getString("name") + val singers = info.getJSONArray("singer") + var singer = "" + singers.forEach { + it as JSONObject + singer += it.getString("name") + "/" + } + singer = singer.substring(0, singer.length - 1) + json["singer"] = singer + json["time"] = info.getString("interval") + return json } override fun url(id: String): JSONObject { - TODO("Not yet implemented") + val json = JSONObject() + val data = JSON.parseObject(get("/song/url?id=$id")) + json["code"] = 200 + val obj = JSONObject() + obj["url"] = data.getString("data") + json["data"] = obj + return json } override fun lyric(id: String): JSONObject { diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBC.kt b/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBC.kt index 280f1157..57cb225a 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBC.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBC.kt @@ -29,12 +29,10 @@ class SenderBC(private val sender: Any) : Sender { val buf = Unpooled.buffer(bytes.size + 1) buf.writeByte(1024) buf.writeBytes(bytes) - ZMusic.tasker.async { - (sender as ProxiedPlayer).server.info.sendData( - channel, - buf.array() - ) - } + (sender as ProxiedPlayer).server.info.sendData( + channel, + buf.array() + ) } catch (e: Exception) { ZMusic.logger.debug("[Mod通信] 数据发送发生错误") } diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBukkit.kt b/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBukkit.kt index 6523bddc..3954b2c7 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBukkit.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/module/sender/SenderBukkit.kt @@ -10,6 +10,7 @@ import net.md_5.bungee.api.chat.TextComponent import org.bukkit.Bukkit import org.bukkit.ChatColor import org.bukkit.command.CommandSender +import org.bukkit.plugin.java.JavaPlugin class SenderBukkit(private val sender: CommandSender) : Sender { @@ -33,13 +34,11 @@ class SenderBukkit(private val sender: CommandSender) : Sender { val buf = Unpooled.buffer(bytes.size + 1) buf.writeByte(666) buf.writeBytes(bytes) - ZMusic.tasker.async { - (sender as org.bukkit.entity.Player).sendPluginMessage( - ZMusicBukkit(), - channel, - buf.array() - ) - } + (sender as org.bukkit.entity.Player).sendPluginMessage( + ZMusic.plugin as JavaPlugin, + channel, + buf.array() + ) } catch (e: Exception) { ZMusic.logger.debug("[Mod通信] 数据发送发生错误") } diff --git a/src/main/kotlin/me/zhenxin/zmusic/module/version/VersionBukkit.kt b/src/main/kotlin/me/zhenxin/zmusic/module/version/VersionBukkit.kt deleted file mode 100644 index 7722d9e9..00000000 --- a/src/main/kotlin/me/zhenxin/zmusic/module/version/VersionBukkit.kt +++ /dev/null @@ -1,32 +0,0 @@ -package me.zhenxin.zmusic.module.version - -import org.bukkit.Bukkit - -class VersionBukkit { - private val rawVersion: String = Bukkit.getBukkitVersion() - private val version: String = rawVersion.split("-")[0] - - //比目标版本低 - fun low(ver: String): Boolean { - val thisVersions = version.split(".") - val compareVersions = ver.split(".") - compareVersions.forEachIndexed { index, s -> - if (s.toInt() > thisVersions[index].toInt()) { - return true - } - } - return false - } - - //比目标版本高 - fun high(ver: String): Boolean { - val thisVersions = version.split(".") - val compareVersions = ver.split(".") - compareVersions.forEachIndexed { index, s -> - if (s.toInt() < thisVersions[index].toInt()) { - return true - } - } - return false - } -} diff --git a/src/main/kotlin/me/zhenxin/zmusic/util/ext/InputStreamExt.kt b/src/main/kotlin/me/zhenxin/zmusic/util/ext/InputStreamExt.kt index 745597bd..e847f623 100644 --- a/src/main/kotlin/me/zhenxin/zmusic/util/ext/InputStreamExt.kt +++ b/src/main/kotlin/me/zhenxin/zmusic/util/ext/InputStreamExt.kt @@ -1,5 +1,6 @@ package me.zhenxin.zmusic.util.ext +import java.io.FileOutputStream import java.io.InputStream import java.io.InputStreamReader import java.nio.charset.StandardCharsets @@ -24,4 +25,16 @@ object InputStreamExt { String(bytes, StandardCharsets.UTF_8) } } + + fun InputStream.saveData(path: String) { + var index: Int + val bytes = ByteArray(1024) + val outputStream = FileOutputStream(path) + while (this.read(bytes).also { index = it } != -1) { + outputStream.write(bytes, 0, index) + outputStream.flush() + } + this.close() + outputStream.close() + } }