diff --git a/.gitignore b/.gitignore index 584060d1..14ea7962 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ lib **/allmusic/comm/ **/allmusic/buffercodec/ **/allmusic/server/core/ +**/allmusic/server/netapi/ **/allmusic/server/bstats/ **/allmusic/client/core/ **/allmusic/client/core/player/decoder/mp3/ diff --git a/bstats/MetricsBase.java b/bstats/MetricsBase.java deleted file mode 100644 index 63d28fc7..00000000 --- a/bstats/MetricsBase.java +++ /dev/null @@ -1,269 +0,0 @@ -package com.coloryr.allmusic.server.bstats; - -import com.coloryr.allmusic.server.bstats.charts.CustomChart; -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import javax.net.ssl.HttpsURLConnection; -import java.io.*; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.zip.GZIPOutputStream; - -public class MetricsBase { - - /** - * The version of the Metrics class. - */ - public static final String METRICS_VERSION = "3.0.3-SNAPSHOT"; - - private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; - - private final ScheduledExecutorService scheduler; - - private final String platform; - private final String serverUuid; - private final int serviceId; - private final Consumer appendPlatformDataConsumer; - private final Consumer appendServiceDataConsumer; - private final Consumer submitTaskConsumer; - private final Supplier checkServiceEnabledSupplier; - - private final BiConsumer errorLogger; - private final Consumer infoLogger; - - private final boolean logErrors; - private final boolean logSentData; - private final boolean logResponseStatusText; - - private final Set customCharts = new HashSet<>(); - private final boolean enabled; - - /** - * Creates a new MetricsBase class instance. - * - * @param platform The platform of the service. - * @param serviceId The id of the service. - * @param serverUuid The server uuid. - * @param enabled Whether or not data sending is enabled. - * @param appendPlatformDataConsumer A consumer that receives a - * {@code JsonObjectBuilder} and appends all - * platform-specific data. - * @param appendServiceDataConsumer A consumer that receives a - * {@code JsonObjectBuilder} and appends all - * service-specific data. - * @param submitTaskConsumer A consumer that takes a runnable with the - * submit task. - * This can be used to delegate the data - * collection to a another thread to prevent - * errors caused by concurrency. Can be - * {@code null}. - * @param checkServiceEnabledSupplier A supplier to check if the service is - * still enabled. - * @param errorLogger A consumer that accepts log message and an - * error. - * @param infoLogger A consumer that accepts info log messages. - * @param logErrors Whether or not errors should be logged. - * @param logSentData Whether or not the sent data should be - * logged. - * @param logResponseStatusText Whether or not the response status text - * should be logged. - */ - public MetricsBase( - String platform, - String serverUuid, - int serviceId, - boolean enabled, - Consumer appendPlatformDataConsumer, - Consumer appendServiceDataConsumer, - Consumer submitTaskConsumer, - Supplier checkServiceEnabledSupplier, - BiConsumer errorLogger, - Consumer infoLogger, - boolean logErrors, - boolean logSentData, - boolean logResponseStatusText) { - ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, - task -> new Thread(task, "bStats-Metrics")); - // We want delayed tasks (non-periodic) that will execute in the future to be - // cancelled when the scheduler is shutdown. - // Otherwise, we risk preventing the server from shutting down even when - // MetricsBase#shutdown() is called - scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - this.scheduler = scheduler; - - this.platform = platform; - this.serverUuid = serverUuid; - this.serviceId = serviceId; - this.enabled = enabled; - this.appendPlatformDataConsumer = appendPlatformDataConsumer; - this.appendServiceDataConsumer = appendServiceDataConsumer; - this.submitTaskConsumer = submitTaskConsumer; - this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; - this.errorLogger = errorLogger; - this.infoLogger = infoLogger; - this.logErrors = logErrors; - this.logSentData = logSentData; - this.logResponseStatusText = logResponseStatusText; - - checkRelocation(); - - if (enabled) { // WARNING: Removing the option to opt-out will get your plugin banned from - // bStats - startSubmitting(); - } - } - - /** - * Gzips the given string. - * - * @param str The string to gzip. - * @return The gzipped string. - */ - 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(); - } - - public void addCustomChart(CustomChart chart) { - this.customCharts.add(chart); - } - - public void shutdown() { - scheduler.shutdown(); - } - - private void startSubmitting() { - final Runnable submitTask = () -> { - if (!enabled || !checkServiceEnabledSupplier.get()) { // Submitting data or service is disabled - scheduler.shutdown(); - return; - } - if (submitTaskConsumer != null) { - submitTaskConsumer.accept(this::submitData); - } else { - this.submitData(); - } - }; - - // Many servers tend to restart at a fixed time at xx:00 which causes an uneven - // distribution of requests on the - // bStats backend. To circumvent this problem, we introduce some randomness into - // the initial and second delay. - // WARNING: You must not modify and part of this Metrics class, including the - // submit delay or frequency! - // WARNING: Modifying this code will get your plugin banned on bStats. Just - // don't do it! - long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); - long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); - scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); - scheduler.scheduleAtFixedRate(submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); - } - - private void submitData() { - final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); - appendPlatformDataConsumer.accept(baseJsonBuilder); - - final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); - appendServiceDataConsumer.accept(serviceJsonBuilder); - - JsonObjectBuilder.JsonObject[] chartData = customCharts.stream() - .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) - .filter(Objects::nonNull) - .toArray(JsonObjectBuilder.JsonObject[]::new); - - serviceJsonBuilder.appendField("id", serviceId); - serviceJsonBuilder.appendField("customCharts", chartData); - baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); - baseJsonBuilder.appendField("serverUUID", serverUuid); - baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); - - JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); - - scheduler.execute(() -> { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logErrors) { - errorLogger.accept("Could not submit bStats metrics data", e); - } - } - }); - } - - private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { - if (logSentData) { - infoLogger.accept("Sent bStats metrics data: " + data.toString()); - } - - String url = String.format(REPORT_URL, platform); - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setRequestProperty("User-Agent", "Metrics-Service/1"); - - 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) { - infoLogger.accept("Sent data to bStats and received response: " + builder); - } - } - - /** - * Checks that the class was properly relocated. - */ - private void checkRelocation() { - // 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")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this - // little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); - final String examplePackage = new String( - new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure no one just copy & pastes the example and uses the wrong - // package names - if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) - || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - -} \ No newline at end of file diff --git a/bstats/charts/AdvancedBarChart.java b/bstats/charts/AdvancedBarChart.java deleted file mode 100644 index c36e776e..00000000 --- a/bstats/charts/AdvancedBarChart.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - - return new JsonObjectBuilder() - .appendField("values", valuesBuilder.build()) - .build(); - } -} \ No newline at end of file diff --git a/bstats/charts/AdvancedPie.java b/bstats/charts/AdvancedPie.java deleted file mode 100644 index 0fb00fef..00000000 --- a/bstats/charts/AdvancedPie.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - - return new JsonObjectBuilder() - .appendField("values", valuesBuilder.build()) - .build(); - } -} diff --git a/bstats/charts/CustomChart.java b/bstats/charts/CustomChart.java deleted file mode 100644 index e1595e0c..00000000 --- a/bstats/charts/CustomChart.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.function.BiConsumer; - -public abstract class CustomChart { - - private final String chartId; - - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } - - public JsonObjectBuilder.JsonObject getRequestJsonObject(BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObjectBuilder.JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } - - protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; - -} diff --git a/bstats/charts/DrilldownPie.java b/bstats/charts/DrilldownPie.java deleted file mode 100644 index 43dbfaa3..00000000 --- a/bstats/charts/DrilldownPie.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - - return new JsonObjectBuilder() - .appendField("values", valuesBuilder.build()) - .build(); - } -} \ No newline at end of file diff --git a/bstats/charts/MultiLineChart.java b/bstats/charts/MultiLineChart.java deleted file mode 100644 index fac5d969..00000000 --- a/bstats/charts/MultiLineChart.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - - return new JsonObjectBuilder() - .appendField("values", valuesBuilder.build()) - .build(); - } - -} \ No newline at end of file diff --git a/bstats/charts/SimpleBarChart.java b/bstats/charts/SimpleBarChart.java deleted file mode 100644 index 184b5546..00000000 --- a/bstats/charts/SimpleBarChart.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); - } - - return new JsonObjectBuilder() - .appendField("values", valuesBuilder.build()) - .build(); - } - -} \ No newline at end of file diff --git a/bstats/charts/SimplePie.java b/bstats/charts/SimplePie.java deleted file mode 100644 index 41923e63..00000000 --- a/bstats/charts/SimplePie.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.concurrent.Callable; - -public class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder() - .appendField("value", value) - .build(); - } -} \ No newline at end of file diff --git a/bstats/charts/SingleLineChart.java b/bstats/charts/SingleLineChart.java deleted file mode 100644 index ea4ae553..00000000 --- a/bstats/charts/SingleLineChart.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.coloryr.allmusic.server.bstats.charts; - -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; - -import java.util.concurrent.Callable; - -public class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @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) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder() - .appendField("value", value) - .build(); - } - -} \ No newline at end of file diff --git a/bstats/config/MetricsConfig.java b/bstats/config/MetricsConfig.java deleted file mode 100644 index 148c5c3a..00000000 --- a/bstats/config/MetricsConfig.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.coloryr.allmusic.server.bstats.config; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -public class MetricsConfig { - private final File file; - private final boolean defaultEnabled; - - private String serverUUID; - private boolean enabled; - private boolean logErrors; - private boolean logSentData; - private boolean logResponseStatusText; - - private boolean didExistBefore = true; - - public MetricsConfig(File file, boolean defaultEnabled) throws IOException { - this.file = file; - this.defaultEnabled = defaultEnabled; - - setupConfig(); - } - - public String getServerUUID() { - return serverUUID; - } - - public boolean isEnabled() { - return enabled; - } - - public boolean isLogErrorsEnabled() { - return logErrors; - } - - public boolean isLogSentDataEnabled() { - return logSentData; - } - - public boolean isLogResponseStatusTextEnabled() { - return logResponseStatusText; - } - - /** - * Checks whether the config file did exist before or not. - * - * @return If the config did exist before. - */ - public boolean didExistBefore() { - return didExistBefore; - } - - /** - * Creates the config file if it does not exist and read its content. - */ - private void setupConfig() throws IOException { - if (!file.exists()) { - didExistBefore = false; // Looks like it's the first time we create it (or someone deleted it). - writeConfig(); - } - readConfig(); - if (serverUUID == null) { - // Found a malformed config file with no UUID. Let's recreate it. - writeConfig(); - readConfig(); - } - } - - /** - * Creates a config file with teh default content. - */ - private void writeConfig() throws IOException { - List configContent = new ArrayList<>(); - configContent.add("# bStats (https://bStats.org) collects some basic information for plugin authors, like"); - configContent.add("# how many people use their plugin and their total player count. It's recommended to keep"); - configContent.add("# bStats enabled, but if you're not comfortable with this, you can turn this setting off."); - configContent.add("# There is no performance penalty associated with having metrics enabled, and data sent to"); - configContent.add("# bStats is fully anonymous."); - configContent.add("enabled=" + defaultEnabled); - configContent.add("server-uuid=" + UUID.randomUUID()); - configContent.add("log-errors=false"); - configContent.add("log-sent-data=false"); - configContent.add("log-response-status-text=false"); - writeFile(file, configContent); - } - - /** - * Reads the content of the config file. - */ - private void readConfig() throws IOException { - List lines = readFile(file); - if (lines == null) { - throw new AssertionError("Content of newly created file is null"); - } - - enabled = getConfigValue("enabled", lines).map("true"::equals).orElse(true); - serverUUID = getConfigValue("server-uuid", lines).orElse(null); - logErrors = getConfigValue("log-errors", lines).map("true"::equals).orElse(false); - logSentData = getConfigValue("log-sent-data", lines).map("true"::equals).orElse(false); - logResponseStatusText = getConfigValue("log-response-status-text", lines).map("true"::equals).orElse(false); - } - - /** - * Gets a config setting from the given list of lines of the file. - * - * @param key The key for the setting. - * @param lines The lines of the file. - * @return The value of the setting. - */ - private Optional getConfigValue(String key, List lines) { - return lines.stream() - .filter(line -> line.startsWith(key + "=")) - .map(line -> line.replaceFirst(Pattern.quote(key + "="), "")) - .findFirst(); - } - - /** - * Reads the text content of the given file. - * - * @param file The file to read. - * @return The lines of the given file. - */ - private List readFile(File file) throws IOException { - if (!file.exists()) { - return null; - } - try ( - FileReader fileReader = new FileReader(file); - BufferedReader bufferedReader = new BufferedReader(fileReader) - ) { - return bufferedReader.lines().collect(Collectors.toList()); - } - } - - /** - * Writes the given lines to the given file. - * - * @param file The file to write to. - * @param lines The lines to write. - */ - private void writeFile(File file, List lines) throws IOException { - if (!file.exists()) { - file.getParentFile().mkdirs(); - file.createNewFile(); - } - try ( - FileWriter fileWriter = new FileWriter(file); - BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) - ) { - for (String line : lines) { - bufferedWriter.write(line); - bufferedWriter.newLine(); - } - } - } -} diff --git a/bstats/json/JsonObjectBuilder.java b/bstats/json/JsonObjectBuilder.java deleted file mode 100644 index 17130eb7..00000000 --- a/bstats/json/JsonObjectBuilder.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.coloryr.allmusic.server.bstats.json; - -import java.util.Arrays; -import java.util.stream.Collectors; - -/** - * An extremely simple JSON builder. - * - *

While this class is neither feature-rich nor the most performant one, - * it's sufficient enough for its use-case. - */ -public class JsonObjectBuilder { - - private StringBuilder builder = new StringBuilder(); - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = Arrays.stream(values) - .mapToObj(String::valueOf) - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = Arrays.stream(values) - .map(JsonObject::toString) - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and - * not allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - -} \ No newline at end of file diff --git a/core/AllMusic.java b/core/AllMusic.java index 2a082b90..2296ecd6 100644 --- a/core/AllMusic.java +++ b/core/AllMusic.java @@ -1,9 +1,9 @@ package com.coloryr.allmusic.server.core; -import com.coloryr.allmusic.server.core.music.api.APIMain; -import com.coloryr.allmusic.server.core.music.play.MusicSearch; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; -import com.coloryr.allmusic.server.core.music.play.PlayRuntime; +import com.coloryr.allmusic.server.core.music.MusicHttpClient; +import com.coloryr.allmusic.server.core.music.MusicSearch; +import com.coloryr.allmusic.server.core.music.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayRuntime; import com.coloryr.allmusic.server.core.objs.CookieObj; import com.coloryr.allmusic.server.core.objs.config.ConfigObj; import com.coloryr.allmusic.server.core.objs.message.MessageObj; @@ -13,6 +13,7 @@ import com.coloryr.allmusic.server.core.side.BaseSide; import com.coloryr.allmusic.server.core.side.IMyLogger; import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.sql.IEconomy; +import com.coloryr.allmusic.server.netapi.NetiApiMain; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; @@ -27,6 +28,8 @@ public class AllMusic { public static final Gson gson = new Gson(); public static final Random random = new Random(); + public static final Map MUSIC_APIS = new HashMap<>(); + /** * 客户端插件信道名 */ @@ -38,15 +41,15 @@ public class AllMusic { /** * 插件版本号 */ - public static final String version = "3.6.0"; + public static final String version = "3.7.0"; /** * 配置文件版本号 */ - public static final String configVersion = "204"; + public static final String configVersion = "205"; /** * 语言文件配置版本号 */ - public static final String messageVersion = "208"; + public static final String messageVersion = "209"; /** * 搜歌结果 * 玩家名 结果 @@ -76,10 +79,6 @@ public class AllMusic { * 经济插件对象 */ public static IEconomy economy; - /** - * 网易API - */ - private static APIMain apiMusic; /** * 配置对象 */ @@ -333,7 +332,11 @@ public class AllMusic { * 启动插件 */ public static void start() { - AllMusic.apiMusic = new APIMain(); + MusicHttpClient.init(); + + IMusicApi api = new NetiApiMain(); + MUSIC_APIS.put(api.getId(), api); + PlayMusic.start(); PlayRuntime.start(); MusicSearch.start(); @@ -356,15 +359,6 @@ public class AllMusic { log.info("§d[AllMusic3]§2§e已停止,感谢使用"); } - /** - * 获取音乐API - * - * @return 音乐API - */ - public static APIMain getMusicApi() { - return apiMusic; - } - /** * 加载配置文件 */ diff --git a/core/AllMusicAPI.java b/core/AllMusicAPI.java index 97ba556a..229a89f8 100644 --- a/core/AllMusicAPI.java +++ b/core/AllMusicAPI.java @@ -4,7 +4,35 @@ import com.coloryr.allmusic.codec.HudPosObj; import com.coloryr.allmusic.codec.HudType; import com.coloryr.allmusic.server.core.utils.HudUtils; -public class AllMusicAPI { +public class AllMusicApi { + + /** + * 注册音乐API + * @param api 音乐API + * @return 返回序号 + */ + public static int registerApi(IMusicApi api) { + AllMusic.MUSIC_APIS.put(api.getId(), api); + return AllMusic.MUSIC_APIS.size() - 1; + } + + /** + * 获取默认音乐API + * @return 音乐API + */ + public static IMusicApi getApiMusic() { + return AllMusic.MUSIC_APIS.get(AllMusic.getConfig().defaultApi); + } + + /** + * 获取某个音乐API + * @param api 音乐API + * @return 音乐API + */ + public static IMusicApi getApiMusic(String api) { + return AllMusic.MUSIC_APIS.get(api); + } + /** * 发送播放音乐 * diff --git a/core/IMusicApi.java b/core/IMusicApi.java new file mode 100644 index 00000000..0ea41a44 --- /dev/null +++ b/core/IMusicApi.java @@ -0,0 +1,19 @@ +package com.coloryr.allmusic.server.core; + +import com.coloryr.allmusic.server.core.music.LyricSave; +import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; +import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; + +public interface IMusicApi { + String getId(); + SongInfoObj getMusic(String id, String player, boolean isList); + SearchPageObj search(String[] args, boolean isDefault); + void setList(String id, Object sender); + LyricSave getLyric(String id); + String getPlayUrl(String id); + + boolean isBusy(); + + String getMusicId(String arg); + boolean checkId(String id); +} diff --git a/core/command/CommandEX.java b/core/command/CommandEX.java index 0a1ca93a..e055ff44 100644 --- a/core/command/CommandEX.java +++ b/core/command/CommandEX.java @@ -1,11 +1,12 @@ package com.coloryr.allmusic.server.core.command; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.sub.*; -import com.coloryr.allmusic.server.core.music.play.MusicSearch; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.MusicSearch; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.utils.Function; @@ -56,7 +57,6 @@ public class CommandEX { commandAdminList.put("unban", new CommandUnban()); commandAdminList.put("banplayer", new CommandBanPlayer()); commandAdminList.put("unbanplayer", new CommandUnbanPlayer()); - commandAdminList.put("url", new CommandUrl()); commandAdminList.put("delete", new CommandDelete()); commandAdminList.put("addlist", new CommandAddList()); commandAdminList.put("clearlist", new CommandClearList()); @@ -74,7 +74,7 @@ public class CommandEX { * @param isDefault 是否是默认点歌方式 */ public static void searchMusic(Object sender, String name, String[] args, boolean isDefault) { - MusicObj obj = new MusicObj(); + PlayerAddMusicObj obj = new PlayerAddMusicObj(); obj.sender = sender; obj.name = name; obj.args = args; @@ -137,30 +137,25 @@ public class CommandEX { * * @param sender 发送者 * @param name 用户名 - * @param args 参数 + * @param arg 参数 */ - public static void addMusic(Object sender, String name, String[] args) { + public static void addMusic(Object sender, String name, String api, String arg) { String musicID; - if (args[0].contains("id=") && !args[0].contains("/?userid")) { - if (args[0].contains("&uct2")) { - musicID = Function.getString(args[0], "id=", "&uct2"); - } else if (args[0].contains("&user")) - musicID = Function.getString(args[0], "id=", "&user"); - else - musicID = Function.getString(args[0], "id=", null); - } else if (args[0].contains("song/")) { - if (args[0].contains("/?userid")) - musicID = Function.getString(args[0], "song/", "/?userid"); - else - musicID = Function.getString(args[0], "song/", null); - } else - musicID = args[0]; - if (Function.isInteger(musicID)) { + + IMusicApi api1 = AllMusic.MUSIC_APIS.get(api); + if (api1 == null) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + musicID = api1.getMusicId(arg); + + if (api1.checkId(musicID)) { if (PlayMusic.getListSize() >= AllMusic.getConfig().maxPlayList) { AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().addMusic.listFull); } else if (DataSql.checkBanMusic(musicID)) { AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().addMusic.banMusic); - } else if (PlayMusic.haveMusic(musicID)) { + } else if (PlayMusic.haveMusic(musicID, api)) { AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().addMusic.existMusic); } else if (PlayMusic.isPlayerMax(name)) { AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().addMusic.playerToMany); @@ -176,7 +171,7 @@ public class CommandEX { } DataSql.removeMutePlayer(name); if (AllMusic.side.needPlay(false)) { - MusicObj obj = new MusicObj(); + PlayerAddMusicObj obj = new PlayerAddMusicObj(); obj.sender = sender; obj.id = musicID; obj.name = name; @@ -241,7 +236,7 @@ public class CommandEX { break; case 0: default: - DataSql.task(() -> addMusic(sender, name, args)); + DataSql.task(() -> addMusic(sender, name, AllMusic.getConfig().defaultApi, args[0])); } } } catch (Exception e) { diff --git a/core/command/sub/CommandAddList.java b/core/command/sub/CommandAddList.java index 2f20434e..b35b9272 100644 --- a/core/command/sub/CommandAddList.java +++ b/core/command/sub/CommandAddList.java @@ -1,29 +1,40 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.utils.Function; public class CommandAddList extends ACommand { @Override public void execute(Object sender, String name, String[] args) { - if (args.length != 2) { + if (args.length < 2) { AllMusic.side.sendMessage(sender, AllMusic.getMessage().command.error); return; } - String musicID; + String musicID = null; + IMusicApi api = null; - if (args[1].contains("id=") && !args[1].contains("/?userid")) { - if (args[1].contains("&user")) - musicID = Function.getString(args[1], "id=", "&user"); - else - musicID = Function.getString(args[1], "id=", null); - } else + if (args.length == 2) { + api = AllMusic.MUSIC_APIS.get(AllMusic.getConfig().defaultApi); musicID = args[1]; + } else if (args.length == 3) { + api = AllMusic.MUSIC_APIS.get(args[1]); + musicID = args[2]; + } else { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2错误的指令"); + } - if (Function.isInteger(musicID)) { - AllMusic.getMusicApi().setList(musicID, sender); + if (api == null) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + musicID = api.getMusicId(musicID); + + if (api.checkId(musicID)) { + api.setList(musicID, sender); AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2添加空闲音乐列表" + musicID); } else { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2请输入有效的音乐列表ID"); diff --git a/core/command/sub/CommandBan.java b/core/command/sub/CommandBan.java index 419a7650..a5f60d3a 100644 --- a/core/command/sub/CommandBan.java +++ b/core/command/sub/CommandBan.java @@ -1,8 +1,9 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.utils.Function; @@ -14,13 +15,32 @@ import java.util.List; public class CommandBan extends ACommand { @Override public void execute(Object sender, String name, String[] args) { - if (args.length != 2) { + if (args.length < 2) { AllMusic.side.sendMessage(sender, AllMusic.getMessage().command.error); return; } - if (Function.isInteger(args[1])) { - DataSql.addBanMusic(args[1]); - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2已禁止点歌" + args[1]); + + String musicID = null; + IMusicApi api = null; + + if (args.length == 2) { + api = AllMusic.MUSIC_APIS.get(AllMusic.getConfig().defaultApi); + musicID = args[1]; + } else if (args.length == 3) { + api = AllMusic.MUSIC_APIS.get(args[1]); + musicID = args[2]; + } else { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2错误的指令"); + } + + if (api == null) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + if (api.checkId(musicID)) { + DataSql.addBanMusic(musicID, api.getId()); + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐API " + api.getId() + " 已禁止点歌" + musicID); } else { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2请输入有效的ID"); } diff --git a/core/command/sub/CommandCancel.java b/core/command/sub/CommandCancel.java index 1044d269..b0a1dc61 100644 --- a/core/command/sub/CommandCancel.java +++ b/core/command/sub/CommandCancel.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ICommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; diff --git a/core/command/sub/CommandClearList.java b/core/command/sub/CommandClearList.java index 7e2b0b3e..da96b668 100644 --- a/core/command/sub/CommandClearList.java +++ b/core/command/sub/CommandClearList.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; public class CommandClearList extends ACommand { @Override diff --git a/core/command/sub/CommandDelete.java b/core/command/sub/CommandDelete.java index 59482383..291b8038 100644 --- a/core/command/sub/CommandDelete.java +++ b/core/command/sub/CommandDelete.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.utils.Function; import java.util.ArrayList; diff --git a/core/command/sub/CommandHelp.java b/core/command/sub/CommandHelp.java index 1b0a7063..02c72200 100644 --- a/core/command/sub/CommandHelp.java +++ b/core/command/sub/CommandHelp.java @@ -63,18 +63,20 @@ public class CommandHelp extends ACommand { AllMusic.getMessage().click.clickRun, "/music next"); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.ban, AllMusic.getMessage().click.clickCheck, "/music ban "); + AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.ban1, + AllMusic.getMessage().click.clickCheck, "/music ban "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.banPlayer, AllMusic.getMessage().click.clickCheck, "/music banplayer "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.unban, AllMusic.getMessage().click.clickCheck, "/music unban "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.unbanPlayer, AllMusic.getMessage().click.clickCheck, "/music unbanplayer "); - AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.url, - AllMusic.getMessage().click.clickCheck, "/music url "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.delete, AllMusic.getMessage().click.clickCheck, "/music delete "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.addList, AllMusic.getMessage().click.clickCheck, "/music addlist "); + AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.addList1, + AllMusic.getMessage().click.clickCheck, "/music addlist "); AllMusic.side.sendMessageRun(sender, AllMusic.getMessage().help.admin.clearList, AllMusic.getMessage().click.clickRun, "/music clearlist"); AllMusic.side.sendMessageRun(sender, AllMusic.getMessage().help.admin.clearBanList, @@ -85,6 +87,8 @@ public class CommandHelp extends ACommand { AllMusic.getMessage().click.clickCheck, "/music cookie "); AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.test, AllMusic.getMessage().click.clickCheck, "/music test "); + AllMusic.side.sendMessageSuggest(sender, AllMusic.getMessage().help.admin.test1, + AllMusic.getMessage().click.clickCheck, "/music test "); } } } diff --git a/core/command/sub/CommandLastPage.java b/core/command/sub/CommandLastPage.java index 90ba03e1..7b4e49db 100644 --- a/core/command/sub/CommandLastPage.java +++ b/core/command/sub/CommandLastPage.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.command.PermissionList; -import com.coloryr.allmusic.server.core.music.play.MusicSearch; +import com.coloryr.allmusic.server.core.music.MusicSearch; import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; public class CommandLastPage extends ACommand { diff --git a/core/command/sub/CommandList.java b/core/command/sub/CommandList.java index fd0b124a..7694b90c 100644 --- a/core/command/sub/CommandList.java +++ b/core/command/sub/CommandList.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; public class CommandList extends ACommand { diff --git a/core/command/sub/CommandMute.java b/core/command/sub/CommandMute.java index 85e4d3b9..3e97b2d0 100644 --- a/core/command/sub/CommandMute.java +++ b/core/command/sub/CommandMute.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.command.CommandEX; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.sql.DataSql; import java.util.ArrayList; diff --git a/core/command/sub/CommandNext.java b/core/command/sub/CommandNext.java index 4f6b95da..d1e495ad 100644 --- a/core/command/sub/CommandNext.java +++ b/core/command/sub/CommandNext.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.sql.DataSql; public class CommandNext extends ACommand { diff --git a/core/command/sub/CommandNextPage.java b/core/command/sub/CommandNextPage.java index fb89132f..481e6554 100644 --- a/core/command/sub/CommandNextPage.java +++ b/core/command/sub/CommandNextPage.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.command.PermissionList; -import com.coloryr.allmusic.server.core.music.play.MusicSearch; +import com.coloryr.allmusic.server.core.music.MusicSearch; import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; public class CommandNextPage extends ACommand { diff --git a/core/command/sub/CommandPush.java b/core/command/sub/CommandPush.java index c83ba9a7..76dc2d3d 100644 --- a/core/command/sub/CommandPush.java +++ b/core/command/sub/CommandPush.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.command.PermissionList; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; diff --git a/core/command/sub/CommandSelect.java b/core/command/sub/CommandSelect.java index a5e21cd2..f39ffb19 100644 --- a/core/command/sub/CommandSelect.java +++ b/core/command/sub/CommandSelect.java @@ -30,11 +30,10 @@ public class CommandSelect extends ACommand { AllMusic.side.sendMessage(sender, AllMusic.getMessage().search.errorNum); return; } - String[] ID = new String[1]; - ID[0] = obj.getSong((obj.getPage() * 10) + (a - 1)); + String id = obj.getSong((obj.getPage() * 10) + (a - 1)); AllMusic.side.sendMessage(sender, AllMusic.getMessage().search.choice.replace(ARG.index, "" + a)); - DataSql.task(() -> CommandEX.addMusic(sender, name, ID)); + DataSql.task(() -> CommandEX.addMusic(sender, name, obj.getApi(), id)); AllMusic.removeSearch(name); } else { AllMusic.side.sendMessage(sender, AllMusic.getMessage().search.errorNum); diff --git a/core/command/sub/CommandTest.java b/core/command/sub/CommandTest.java index 953d6cd7..168cb930 100644 --- a/core/command/sub/CommandTest.java +++ b/core/command/sub/CommandTest.java @@ -1,50 +1,52 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.api.APIMain; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; -import com.coloryr.allmusic.server.core.utils.Function; public class CommandTest extends ACommand { @Override public void execute(Object sender, String name, String[] args) { - if (args.length != 2) { + if (args.length < 2) { AllMusic.side.sendMessage(sender, AllMusic.getMessage().command.error); return; } - if (Function.isInteger(args[1])) { + + String musicID = null; + IMusicApi api = null; + + if (args.length == 2) { + api = AllMusic.MUSIC_APIS.get(AllMusic.getConfig().defaultApi); + musicID = args[1]; + } else if (args.length == 3) { + api = AllMusic.MUSIC_APIS.get(args[1]); + musicID = args[2]; + } else { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2错误的指令"); + } + + if (api == null) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + if (api.checkId(musicID)) { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2正在测试解析" + args[1]); try { - SongInfoObj info = AllMusic.getMusicApi().getMusic(args[1], "test", false); + SongInfoObj info = api.getMusic(args[1], "test", false); if (info == null) { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2测试解析失败"); return; } AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐名称 " + info.getName()); AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐作者 " + info.getAuthor()); - String url = AllMusic.getMusicApi().getPlayUrl(args[1]); + String url = api.getPlayUrl(args[1]); AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2播放地址 " + url); } catch (Exception e) { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2测试解析错误"); e.printStackTrace(); } - } else { - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2正在测试解析" + args[1]); - - new Thread(() -> { - try { - SongInfoObj info = APIMain.getUrlMusic(args[1]); - AllMusic.side.runTask(() -> { - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐解析类型:" + info.getMediaType() + " 音乐长度:" + info.getLength() / 1000); - }); - } catch (Exception e) { - AllMusic.side.runTask(() -> { - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2测试解析错误"); - e.printStackTrace(); - }); - } - }).start(); } } } diff --git a/core/command/sub/CommandUnban.java b/core/command/sub/CommandUnban.java index 8e665263..02f1b22c 100644 --- a/core/command/sub/CommandUnban.java +++ b/core/command/sub/CommandUnban.java @@ -1,6 +1,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.sql.Cache; import com.coloryr.allmusic.server.core.sql.DataSql; @@ -13,13 +14,35 @@ import java.util.List; public class CommandUnban extends ACommand { @Override public void execute(Object sender, String name, String[] args) { - if (args.length != 2) { + if (args.length < 2) { AllMusic.side.sendMessage(sender, AllMusic.getMessage().command.error); return; } - if (Function.isInteger(args[1])) { + + String musicID = null; + IMusicApi api = null; + + if (args.length == 2) { + api = AllMusic.MUSIC_APIS.get(AllMusic.getConfig().defaultApi); + musicID = args[1]; + } else if (args.length == 3) { + api = AllMusic.MUSIC_APIS.get(args[1]); + musicID = args[2]; + } else { + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2错误的指令"); + } + + if (api == null) { + AllMusic.side.sendMessage(sender, AllMusic.getMessage().musicPlay.error2); + return; + } + + musicID = api.getMusicId(musicID); + + if (api.checkId(musicID)) { + api.setList(musicID, sender); DataSql.removeBanMusic(args[1]); - AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2已解封点歌" + args[1]); + AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2音乐API " + api.getId() + "已解封点歌" + musicID); } else { AllMusic.side.sendMessage(sender, "§d[AllMusic3]§2请输入有效的ID"); } diff --git a/core/command/sub/CommandUrl.java b/core/command/sub/CommandUrl.java deleted file mode 100644 index f6dfb02a..00000000 --- a/core/command/sub/CommandUrl.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.coloryr.allmusic.server.core.command.sub; - -import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.command.ACommand; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; - -public class CommandUrl extends ACommand { - @Override - public void execute(Object sender, String name, String[] args) { - if (args.length != 2) { - AllMusic.side.sendMessage(sender, AllMusic.getMessage().command.error); - return; - } - MusicObj obj = new MusicObj(); - obj.sender = sender; - obj.isUrl = true; - obj.url = args[1]; - PlayMusic.addTask(obj); - AllMusic.side.sendMessage(sender, AllMusic.getMessage().addMusic.success); - } -} diff --git a/core/command/sub/CommandVote.java b/core/command/sub/CommandVote.java index 8cf97608..753ab57a 100644 --- a/core/command/sub/CommandVote.java +++ b/core/command/sub/CommandVote.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.core.command.sub; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.command.ACommand; import com.coloryr.allmusic.server.core.command.PermissionList; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.sql.DataSql; diff --git a/core/music/play/LyricSave.java b/core/music/LyricSave.java similarity index 97% rename from core/music/play/LyricSave.java rename to core/music/LyricSave.java index 4b629b69..6e8e6e22 100644 --- a/core/music/play/LyricSave.java +++ b/core/music/LyricSave.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.core.music; import com.coloryr.allmusic.server.core.objs.music.LyricItemObj; diff --git a/core/music/MusicHttpClient.java b/core/music/MusicHttpClient.java new file mode 100644 index 00000000..c9704eaf --- /dev/null +++ b/core/music/MusicHttpClient.java @@ -0,0 +1,112 @@ +package com.coloryr.allmusic.server.core.music; + +import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.decoder.flac.FlacDecoder; +import com.coloryr.allmusic.server.core.decoder.flac.StreamInfo; +import com.coloryr.allmusic.server.core.decoder.mp3.Bitstream; +import com.coloryr.allmusic.server.core.decoder.mp3.Header; +import com.coloryr.allmusic.server.core.objs.CookieObj; +import com.coloryr.allmusic.server.core.objs.MediaType; +import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.cookie.BasicCookieStore; +import org.apache.hc.client5.http.cookie.Cookie; +import org.apache.hc.client5.http.cookie.CookieStore; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.util.Timeout; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.Instant; +import java.util.List; + +public class MusicHttpClient { + private static final int CONNECT_TIMEOUT = 5; + private static final int READ_TIMEOUT = 7; + public static final String UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0"; + public static CloseableHttpClient client; + + public static void init() { + try { + synchronized (com.coloryr.allmusic.server.netapi.NetApiHttpClient.class) { + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(Timeout.ofSeconds(CONNECT_TIMEOUT)) + .setResponseTimeout(Timeout.ofSeconds(READ_TIMEOUT)) + .build(); + client = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static CookieStore createCookieStore() { + BasicCookieStore cookieStore = new BasicCookieStore(); + for (CookieObj cookie : AllMusic.cookie) { + BasicClientCookie cookie1 = new BasicClientCookie(cookie.name, cookie.value); + cookie1.setExpiryDate(Instant.MAX); + cookie1.setDomain(cookie.domain); + cookie1.setPath(cookie.path); + cookie1.setHttpOnly(cookie.hostOnly); + cookie1.setHttpOnly(cookie.httpOnly); + cookieStore.addCookie(cookie1); + } + return cookieStore; + } + + public static void saveCookies(CookieStore cookieStore) { + List cookies = cookieStore.getCookies(); + for (Cookie cookie : cookies) { + CookieObj obj = new CookieObj(); + obj.domain = cookie.getDomain(); + obj.hostOnly = cookie.isHttpOnly(); + obj.httpOnly = cookie.isHttpOnly(); + obj.name = cookie.getName(); + obj.value = cookie.getValue(); + } + AllMusic.saveCookie(); + } + + public static InputStream get(String path) { + try { + HttpGet request = new HttpGet(path); + request.setHeader("user-agent", UserAgent); + HttpClientContext context = HttpClientContext.create(); + CookieStore cookieStore = createCookieStore(); + context.setCookieStore(cookieStore); + CloseableHttpResponse response = client.execute(request, context); + int httpCode = response.getCode(); + HttpEntity entity = response.getEntity(); + if (entity == null) { + AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); + return null; + } + InputStream inputStream = entity.getContent(); + boolean ok = httpCode == 200; + if (!ok) { + EntityUtils.consume(entity); + inputStream.close(); + response.close(); + return null; + } + // 保存 cookies + saveCookies(cookieStore); + // 注意:需要调用者关闭 InputStream + return inputStream; + } catch (Exception e) { + AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); + e.printStackTrace(); + } + return null; + } +} diff --git a/core/music/play/MusicSearch.java b/core/music/MusicSearch.java similarity index 80% rename from core/music/play/MusicSearch.java rename to core/music/MusicSearch.java index b835db89..a56ddfc5 100644 --- a/core/music/play/MusicSearch.java +++ b/core/music/MusicSearch.java @@ -1,24 +1,29 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.core.music; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.objs.SearchMusicObj; import com.coloryr.allmusic.server.core.objs.message.ARG; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class MusicSearch { - private static final Queue tasks = new ConcurrentLinkedQueue<>(); + private static final Queue tasks = new ConcurrentLinkedQueue<>(); private static boolean isRun; private static void task() { while (isRun) { try { - MusicObj obj = tasks.poll(); + PlayerAddMusicObj obj = tasks.poll(); if (obj != null) { - SearchPageObj search = AllMusic.getMusicApi().search(obj.args, obj.isDefault); + IMusicApi api = AllMusic.MUSIC_APIS.get(obj.api); + if (api == null) { + AllMusic.side.sendMessageTask(obj.sender, AllMusic.getMessage().musicPlay.error2); + } + SearchPageObj search = api.search(obj.args, obj.isDefault); if (search == null) AllMusic.side.sendMessageTask(obj.sender, AllMusic.getMessage().search .cantSearch.replace(ARG.name, obj.isDefault ? obj.args[0] : obj.args[1])); @@ -46,7 +51,7 @@ public class MusicSearch { isRun = false; } - public static void addSearch(MusicObj obj) { + public static void addSearch(PlayerAddMusicObj obj) { tasks.add(obj); } diff --git a/core/music/play/PlayMusic.java b/core/music/PlayMusic.java similarity index 85% rename from core/music/play/PlayMusic.java rename to core/music/PlayMusic.java index d5cb999f..74376afa 100644 --- a/core/music/play/PlayMusic.java +++ b/core/music/PlayMusic.java @@ -1,10 +1,11 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.core.music; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.music.api.APIMain; +import com.coloryr.allmusic.server.core.IMusicApi; +import com.coloryr.allmusic.server.core.objs.music.MusicObj; import com.coloryr.allmusic.server.core.objs.config.LimitObj; import com.coloryr.allmusic.server.core.objs.message.ARG; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.sql.DataSql; import com.coloryr.allmusic.server.core.utils.HudUtils; @@ -18,8 +19,8 @@ public class PlayMusic { * 播放列表 */ private static final List playList = new ArrayList<>(); - private static final Queue tasks = new ConcurrentLinkedQueue<>(); - private static final Queue deep = new PriorityQueue<>(); + private static final Queue tasks = new ConcurrentLinkedQueue<>(); + private static final Queue deep = new PriorityQueue<>(); /** * 切歌投票的玩家 */ @@ -214,19 +215,18 @@ public class PlayMusic { * * @param obj 歌曲 */ - public static void addTask(MusicObj obj) { + public static void addTask(PlayerAddMusicObj obj) { tasks.add(obj); } private static void task() { while (isRun) { try { - MusicObj obj = tasks.poll(); + PlayerAddMusicObj obj = tasks.poll(); if (obj != null) { - if (obj.isUrl) { - addUrl(obj.url); - } else { - addMusic(obj.sender, obj.id, obj.name, obj.isDefault); + IMusicApi api = AllMusic.MUSIC_APIS.get(obj.api); + if(api != null) { + addMusic(obj.sender, obj.id, api, obj.name, obj.isDefault); } } Thread.sleep(10); @@ -245,8 +245,8 @@ public class PlayMusic { * @param player 用户名 * @param isList 是否是空闲歌单 */ - public static void addMusic(Object sender, String id, String player, boolean isList) { - if (haveMusic(id)) + public static void addMusic(Object sender, String id, IMusicApi api, String player, boolean isList) { + if (haveMusic(id, api.getId())) return; if (sender != null) { String text = AllMusic.getMessage().musicPlay.checkMusic @@ -255,7 +255,7 @@ public class PlayMusic { } AllMusic.log.info("玩家:" + player + " 点歌:" + id); try { - SongInfoObj info = AllMusic.getMusicApi().getMusic(id, player, isList); + SongInfoObj info = api.getMusic(id, player, isList); if (info == null) { if (sender != null) { String data = AllMusic.getMessage().musicPlay.emptyCanPlay; @@ -402,39 +402,36 @@ public class PlayMusic { /** * 是否在播放列表中 * - * @param id 音乐ID + * @param music 音乐 * @return 结果 */ - public static boolean haveMusic(String id) { - if (nowPlayMusic != null && nowPlayMusic.getID().equalsIgnoreCase(id)) - return true; - for (SongInfoObj item : playList) { - if (item.getID().equalsIgnoreCase(id)) - return true; - } - return false; + public static boolean haveMusic(MusicObj music) { + return haveMusic(music.id, music.api); } /** - * 添加Url歌曲 - * - * @param url 链接 + * 是否在播放列表中 + * @param id 音乐编号 + * @param api 音乐API编号 + * @return 是否在列表种 */ - private static void addUrl(String url) { - SongInfoObj info = APIMain.getUrlMusic(url); - if (info == null) { - AllMusic.side.broadcastInTask(AllMusic.getMessage().musicPlay.error1); - return; + public static boolean haveMusic(String id, String api) { + if (nowPlayMusic != null && nowPlayMusic.getID().equalsIgnoreCase(id) + && Objects.equals(nowPlayMusic.getApi(), api)) + return true; + for (SongInfoObj item : playList) { + if (item.getID().equalsIgnoreCase(id) && Objects.equals(item.getApi(), api)) { + return true; + } } - info.setName(AllMusic.getMessage().custom.info); - playList.add(info); + return false; } /** * 判断玩家点歌数量是否超上限 * * @param name 玩家名 - * @return + * @return 是否超过上限 */ public static boolean isPlayerMax(String name) { int list = AllMusic.getConfig().maxPlayerList; @@ -442,7 +439,7 @@ public class PlayMusic { return false; } int count = 0; - for (MusicObj obj : tasks) { + for (PlayerAddMusicObj obj : tasks) { if (obj.name.equalsIgnoreCase(name)) { count++; } @@ -460,16 +457,27 @@ public class PlayMusic { return DataSql.getListSize(); } + /** + * 检查这个空闲歌是否已经放了 + * @param music 空闲音乐 + * @return 是否已经放过了 + */ + private static boolean checkDeep(MusicObj music) { + for (MusicObj obj : deep) { + if (Objects.equals(obj.id, music.id) && obj.api == music.api) { + return true; + } + } + return false; + } + /** * 获取空闲歌单的一首歌 * * @return 结果 */ - public static String getIdleMusic() { - if (AllMusic.getMusicApi().isUpdate()) { - return null; - } - String id; + public static MusicObj getIdleMusic() { + MusicObj music; int len = DataSql.getListSize(); if (len == 0) return null; @@ -485,21 +493,21 @@ public class PlayMusic { deep.poll(); } do { - id = DataSql.readListItem(); + music = DataSql.readListItem(); } - while (deep.contains(id)); - deep.add(id); + while (checkDeep(music)); + deep.add(music); } else { - id = DataSql.readListItem(); + music = DataSql.readListItem(); } } else { - id = DataSql.readListItem(idleNow); + music = DataSql.readListItem(idleNow); idleNow++; if (idleNow >= len) { idleNow = 0; } } - return id; + return music; } public static SongInfoObj findPlayerMusic(String name) { diff --git a/core/music/play/PlayRuntime.java b/core/music/PlayRuntime.java similarity index 93% rename from core/music/play/PlayRuntime.java rename to core/music/PlayRuntime.java index c670b430..1c99e559 100644 --- a/core/music/play/PlayRuntime.java +++ b/core/music/PlayRuntime.java @@ -1,7 +1,9 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.core.music; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.objs.message.ARG; +import com.coloryr.allmusic.server.core.objs.music.MusicObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.utils.HudUtils; @@ -217,9 +219,12 @@ public class PlayRuntime { if (PlayMusic.error >= 10) { Thread.sleep(1000); } else if (AllMusic.side.needPlay(true) && PlayMusic.getIdleListSize() > 0) { - String id = PlayMusic.getIdleMusic(); - if (id != null) { - PlayMusic.addMusic(null, id, AllMusic.getMessage().custom.idle, true); + MusicObj music = PlayMusic.getIdleMusic(); + if (music != null) { + IMusicApi api = AllMusic.MUSIC_APIS.get(music.api); + if (api != null && !api.isBusy()) { + PlayMusic.addMusic(null, music.id, api, AllMusic.getMessage().custom.idle, true); + } } } Thread.sleep(1000); @@ -234,8 +239,10 @@ public class PlayRuntime { continue; } + IMusicApi api = AllMusic.MUSIC_APIS.get(PlayMusic.nowPlayMusic.getApi()); + PlayMusic.url = PlayMusic.nowPlayMusic.getPlayerUrl() == null ? - AllMusic.getMusicApi().getPlayUrl(PlayMusic.nowPlayMusic.getID()) : + api.getPlayUrl(PlayMusic.nowPlayMusic.getID()) : PlayMusic.nowPlayMusic.getPlayerUrl(); if (PlayMusic.url == null) { String data = AllMusic.getMessage().musicPlay.emptyCanPlay; @@ -245,7 +252,7 @@ public class PlayRuntime { } if (PlayMusic.nowPlayMusic.getPlayerUrl() == null) - PlayMusic.lyric = AllMusic.getMusicApi().getLyric(PlayMusic.nowPlayMusic.getID()); + PlayMusic.lyric = api.getLyric(PlayMusic.nowPlayMusic.getID()); else PlayMusic.lyric = new LyricSave(); diff --git a/core/music/play/TopLyricSave.java b/core/music/TopLyricSave.java similarity index 89% rename from core/music/play/TopLyricSave.java rename to core/music/TopLyricSave.java index a11e57e8..72d037b6 100644 --- a/core/music/play/TopLyricSave.java +++ b/core/music/TopLyricSave.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.core.music; public class TopLyricSave extends LyricSave { diff --git a/core/objs/config/ConfigObj.java b/core/objs/config/ConfigObj.java index 2573a028..fb5e057e 100644 --- a/core/objs/config/ConfigObj.java +++ b/core/objs/config/ConfigObj.java @@ -114,6 +114,10 @@ public class ConfigObj { * 花费点歌 */ public CostObj cost; + /** + * 默认音乐API + */ + public String defaultApi; /** * 信息更新延迟 */ @@ -179,6 +183,7 @@ public class ConfigObj { showInBar = false; defaultAddMusic = 0; musicBR = "320000"; + defaultApi = "netapi"; topPAPI = false; limit = LimitObj.make(); economy = EconomyObj.make(); diff --git a/core/objs/enums/EncryptType.java b/core/objs/enums/EncryptType.java deleted file mode 100644 index 9222b55b..00000000 --- a/core/objs/enums/EncryptType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.coloryr.allmusic.server.core.objs.enums; - -public enum EncryptType { - WEAPI, EAPI, API -} diff --git a/core/objs/message/HelpAdminObj.java b/core/objs/message/HelpAdminObj.java index d4a97a8b..5ea56352 100644 --- a/core/objs/message/HelpAdminObj.java +++ b/core/objs/message/HelpAdminObj.java @@ -4,15 +4,18 @@ public class HelpAdminObj { public String reload; public String next; public String ban; + public String ban1; public String banPlayer; - public String url; public String delete; public String addList; + public String addList1; public String clearList; public String cookie; public String test; + public String test1; public String unbanPlayer; public String unban; + public String unban1; public String clearBanList; public String clearBanPlayerList; @@ -30,16 +33,20 @@ public class HelpAdminObj { return true; if (ban == null) return true; + if (ban1 == null) + return true; if (unban == null) return true; - if (unbanPlayer == null) + if (unban1 == null) return true; - if (url == null) + if (unbanPlayer == null) return true; if (delete == null) return true; if (addList == null) return true; + if (addList1 == null) + return true; if (clearList == null) return true; if (banPlayer == null) @@ -60,18 +67,22 @@ public class HelpAdminObj { next = "§d[AllMusic3]§e使用/music next 强制切歌"; if (ban == null) ban = "§d[AllMusic3]§e使用/music ban [ID] 禁止点这首歌"; + if (ban1 == null) + ban1 = "§d[AllMusic3]§e使用/music ban [音乐API] [ID] 禁止点这首歌"; if (banPlayer == null) banPlayer = "§d[AllMusic3]§e使用/music banplayer [ID] 禁止某位玩家点歌"; if (unban == null) unban = "§d[AllMusic3]§e使用/music unban [ID] 解禁点这首歌"; + if (unban1 == null) + unban1 = "§d[AllMusic3]§e使用/music unban [音乐API] [ID] 解禁点这首歌"; if (unbanPlayer == null) unbanPlayer = "§d[AllMusic3]§e使用/music unbanplayer [ID] 解禁某位玩家点歌"; - if (url == null) - url = "§d[AllMusic3]§e使用/music url [url] 播放一首自定义歌曲"; if (delete == null) delete = "§d[AllMusic3]§e使用/music delete [序号] 删除队列中的歌曲"; if (addList == null) addList = "§d[AllMusic3]§e使用/music addlist [歌单ID] 添加歌单到空闲列表"; + if (addList1 == null) + addList1 = "§d[AllMusic3]§e使用/music addlist [音乐API] [歌单ID] 添加歌单到空闲列表"; if (clearList == null) clearList = "§d[AllMusic3]§e使用/music clearlist 清空空闲歌单"; if (clearBanList == null) @@ -81,6 +92,8 @@ public class HelpAdminObj { if (cookie == null) cookie = "§d[AllMusic3]§e使用/music cookie [cookie] 填写cookie"; if (test == null) - test = "§d[AllMusic3]§e使用/music test [音乐ID] 测试解析音乐"; + test = "§d[AllMusic3]§e使用/music test [ID] 测试解析音乐"; + if (test1 == null) + test1 = "§d[AllMusic3]§e使用/music test [音乐API] [ID] 测试解析音乐"; } } diff --git a/core/objs/message/MusicPlayObj.java b/core/objs/message/MusicPlayObj.java index b80385f6..a87094f6 100644 --- a/core/objs/message/MusicPlayObj.java +++ b/core/objs/message/MusicPlayObj.java @@ -18,6 +18,7 @@ public class MusicPlayObj { public String trail; public String cancel; public String error1; + public String error2; public static MusicPlayObj make() { MusicPlayObj obj = new MusicPlayObj(); @@ -60,6 +61,8 @@ public class MusicPlayObj { res = true; if (error1 == null) res = true; + if (error2 == null) + res = true; return res; } @@ -102,5 +105,7 @@ public class MusicPlayObj { cancel = "§d[AllMusic3]§e播放被取消"; if (error1 == null) error1 = "§d[AllMusic3]§c未知音乐类型"; + if (error2 == null) + error2 = "§d[AllMusic3]§c未知音乐API"; } } diff --git a/core/objs/music/MusicObj.java b/core/objs/music/MusicObj.java index 1eec7ef0..b227ce72 100644 --- a/core/objs/music/MusicObj.java +++ b/core/objs/music/MusicObj.java @@ -2,31 +2,11 @@ package com.coloryr.allmusic.server.core.objs.music; public class MusicObj { /** - * 发送者 - */ - public Object sender; - /** - * 歌曲ID + * 音乐编号 */ public String id; /** - * 用户名 + * 音乐API */ - public String name; - /** - * 参数 - */ - public String[] args; - /** - * 是否是默认点歌方式 - */ - public boolean isDefault; - /** - * 是否是Url歌曲 - */ - public boolean isUrl; - /** - * 歌曲Url - */ - public String url; + public String api; } diff --git a/core/objs/music/PlayerAddMusicObj.java b/core/objs/music/PlayerAddMusicObj.java new file mode 100644 index 00000000..0f187f35 --- /dev/null +++ b/core/objs/music/PlayerAddMusicObj.java @@ -0,0 +1,32 @@ +package com.coloryr.allmusic.server.core.objs.music; + +public class PlayerAddMusicObj { + /** + * 发送者 + */ + public Object sender; + /** + * 歌曲ID + */ + public String id; + /** + * 音乐API编号 + */ + public String api; + /** + * 用户名 + */ + public String name; + /** + * 参数 + */ + public String[] args; + /** + * 是否是默认点歌方式 + */ + public boolean isDefault; + /** + * 歌曲Url + */ + public String url; +} diff --git a/core/objs/music/SearchPageObj.java b/core/objs/music/SearchPageObj.java index deb527b4..54ddd059 100644 --- a/core/objs/music/SearchPageObj.java +++ b/core/objs/music/SearchPageObj.java @@ -8,10 +8,12 @@ public class SearchPageObj { private final List resData; private final int maxpage; private int page = 0; + private final String api; - public SearchPageObj(List resData, int maxpage) { + public SearchPageObj(List resData, int maxpage, String api) { this.resData = resData; this.maxpage = maxpage; + this.api = api; } public String getSong(int index) { @@ -52,4 +54,8 @@ public class SearchPageObj { public int getPage() { return page; } + + public String getApi() { + return api; + } } diff --git a/core/objs/music/SongInfoObj.java b/core/objs/music/SongInfoObj.java index 6f8631ce..5cb146b8 100644 --- a/core/objs/music/SongInfoObj.java +++ b/core/objs/music/SongInfoObj.java @@ -2,7 +2,7 @@ package com.coloryr.allmusic.server.core.objs.music; import com.coloryr.allmusic.server.core.AllMusic; import com.coloryr.allmusic.server.core.objs.MediaType; -import com.coloryr.allmusic.server.core.objs.api.music.trialinfo.freeTrialInfo; +import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.freeTrialInfo; import com.coloryr.allmusic.server.core.objs.message.ARG; public class SongInfoObj { @@ -65,6 +65,11 @@ public class SongInfoObj { */ protected MediaType mediaType; + /** + * 音乐API + */ + protected String api; + public SongInfoObj(String name, String url, int length, MediaType type) { this.length = length; playerUrl = url; @@ -164,4 +169,8 @@ public class SongInfoObj { public MediaType getMediaType() { return mediaType; } + + public String getApi() { + return api; + } } diff --git a/core/objs/music/TopSongInfoObj.java b/core/objs/music/TopSongInfoObj.java index c50eb487..5a088de2 100644 --- a/core/objs/music/TopSongInfoObj.java +++ b/core/objs/music/TopSongInfoObj.java @@ -1,7 +1,7 @@ package com.coloryr.allmusic.server.core.objs.music; import com.coloryr.allmusic.server.core.objs.MediaType; -import com.coloryr.allmusic.server.core.objs.api.music.trialinfo.freeTrialInfo; +import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.freeTrialInfo; public class TopSongInfoObj extends SongInfoObj { public TopSongInfoObj() { diff --git a/core/side/BaseSide.java b/core/side/BaseSide.java index 3fc75735..48160502 100644 --- a/core/side/BaseSide.java +++ b/core/side/BaseSide.java @@ -4,7 +4,7 @@ import com.coloryr.allmusic.codec.CommandType; import com.coloryr.allmusic.codec.HudPosObj; import com.coloryr.allmusic.codec.HudType; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.utils.HudUtils; @@ -159,7 +159,7 @@ public abstract class BaseSide { * @param music 歌曲信息 * @return 是否阻止添加 */ - public abstract boolean onMusicAdd(Object obj, MusicObj music); + public abstract boolean onMusicAdd(Object obj, PlayerAddMusicObj music); /** * 广播消息 diff --git a/core/sql/DataSql.java b/core/sql/DataSql.java index af0ab259..d634a69d 100644 --- a/core/sql/DataSql.java +++ b/core/sql/DataSql.java @@ -4,6 +4,7 @@ import com.coloryr.allmusic.codec.HudDirType; import com.coloryr.allmusic.codec.HudItemPosObj; import com.coloryr.allmusic.codec.HudPosObj; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.objs.music.MusicObj; import java.io.File; import java.sql.*; @@ -53,6 +54,7 @@ public class DataSql { private static final String table1 = "CREATE TABLE IF NOT EXISTS \"allmusic_list\" (\n" + " \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " \"sid\" TEXT(40)\n" + + " \"api\" TEXT(40)\n" + ");"; private static final String table2 = "CREATE TABLE IF NOT EXISTS \"allmusic_mute\" (\n" + @@ -68,6 +70,7 @@ public class DataSql { private static final String table4 = "CREATE TABLE IF NOT EXISTS \"allmusic_banlist\" (\n" + " \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " \"sid\" TEXT(40)\n" + + " \"api\" TEXT(40)\n" + ");"; private static final String table5 = "CREATE TABLE IF NOT EXISTS \"allmusic_banplayer\" (\n" + @@ -308,19 +311,24 @@ public class DataSql { /** * 随机获取空闲歌单歌曲 */ - public static String readListItem() { + public static MusicObj readListItem() { try { if (connection.isReadOnly() || connection.isClosed()) { init(); } Statement stat = connection.createStatement(); - ResultSet set = stat.executeQuery("SELECT sid FROM allmusic_list ORDER BY random() limit 1"); - String name = null; + ResultSet set = stat.executeQuery("SELECT sid,api FROM allmusic_list ORDER BY random() limit 1"); + String id = null; + String api = null; if (set.next()) { - name = set.getString(1); + id = set.getString(1); + api = set.getString(2); } stat.close(); - return name; + MusicObj obj = new MusicObj(); + obj.id = id; + obj.api = api; + return obj; } catch (Exception e) { AllMusic.log.warning("数据库读取错误,请删除关闭服务器删除数据库,在启动服务器"); e.printStackTrace(); @@ -331,19 +339,24 @@ public class DataSql { /** * 读取空闲歌单列表 */ - public static String readListItem(int index) { + public static MusicObj readListItem(int index) { try { if (connection.isReadOnly() || connection.isClosed()) { init(); } Statement stat = connection.createStatement(); - ResultSet set = stat.executeQuery("SELECT sid FROM allmusic_list limit 1 offset " + index); - String name = null; + ResultSet set = stat.executeQuery("SELECT sid,api FROM allmusic_list limit 1 offset " + index); + String id = null; + String index1 = null; if (set.next()) { - name = set.getString(1); + id = set.getString(1); + index1 = set.getString(2); } stat.close(); - return name; + MusicObj obj = new MusicObj(); + obj.id = id; + obj.api = index1; + return obj; } catch (Exception e) { AllMusic.log.warning("数据库读取错误,请删除关闭服务器删除数据库,在启动服务器"); e.printStackTrace(); @@ -376,17 +389,18 @@ public class DataSql { return 0; } - public static void addIdleList(List list) { + public static void addIdleList(List list, String api) { task(() -> { try { AllMusic.log.info("添加" + list.size() + "首歌到空闲歌单"); if (connection.isReadOnly() || connection.isClosed()) { init(); } - PreparedStatement pstmt = connection.prepareStatement("INSERT INTO allmusic_list (sid) VALUES (?)"); + PreparedStatement pstmt = connection.prepareStatement("INSERT INTO allmusic_list (sid,api) VALUES (?,?)"); // 遍历 List 并插入每个字符串 for (String str : list) { pstmt.setString(1, str); // 设置参数 + pstmt.setString(2, api); pstmt.addBatch(); // 添加到批处理 } pstmt.executeBatch(); @@ -412,14 +426,15 @@ public class DataSql { }); } - public static void addBanMusic(String music) { + public static void addBanMusic(String music, String api) { task(() -> { try { if (connection.isReadOnly() || connection.isClosed()) { init(); } - PreparedStatement pstmt = connection.prepareStatement("INSERT INTO allmusic_banlist (sid) VALUES (?)"); + PreparedStatement pstmt = connection.prepareStatement("INSERT INTO allmusic_banlist (sid,api) VALUES (?)"); pstmt.setString(1, music); // 设置参数 + pstmt.setString(2, api); pstmt.execute(); pstmt.close(); Cache.banMusic.add(music); diff --git a/core/utils/HudUtils.java b/core/utils/HudUtils.java index bdef2c68..de159966 100644 --- a/core/utils/HudUtils.java +++ b/core/utils/HudUtils.java @@ -5,8 +5,8 @@ import com.coloryr.allmusic.codec.HudItemPosObj; import com.coloryr.allmusic.codec.HudPosObj; import com.coloryr.allmusic.codec.HudType; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.music.play.LyricSave; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.LyricSave; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.core.objs.config.LimitObj; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; diff --git a/link.cmd b/link.cmd index 6aee53d8..ffa94fcd 100644 --- a/link.cmd +++ b/link.cmd @@ -11,6 +11,7 @@ neoforge_1_21 neoforge_1_21_6 neoforge_1_21_11 for %%i in (%array%) do ( if not exist "%%i\src\main\java\com\coloryr\allmusic\server\core" mklink /j "%%i\src\main\java\com\coloryr\allmusic\server\core" "core" + if not exist "%%i\src\main\java\com\coloryr\allmusic\server\netapi" mklink /j "%%i\src\main\java\com\coloryr\allmusic\server\netapi" "netapi" if not exist "%%i\src\main\java\com\coloryr\allmusic\codec" mklink /j "%%i\src\main\java\com\coloryr\allmusic\codec" "client\codec" if not exist "%%i\build" mkdir "%%i\build" && mklink /j "%%i\build\libs" "build\libs" ) @@ -24,12 +25,6 @@ for %%i in (%array1%) do ( if not exist "%%i\src\main\java\com\coloryr\allmusic\buffercodec" mklink /j "%%i\src\main\java\com\coloryr\allmusic\buffercodec" "client\buffercodec" ) -set array2=folia server_top server - -for %%i in (%array2%) do ( - if not exist "%%i\src\main\java\com\coloryr\allmusic\server\bstats" mklink /j "%%i\src\main\java\com\coloryr\allmusic\server\bstats" "bstats" -) - set array3=fabric_1_16_5 fabric_1_20_1 fabric_1_21 fabric_1_21_6 fabric_1_21_11 ^ neoforge_1_21 neoforge_1_21_6 neoforge_1_21_11 diff --git a/core/music/api/CryptoUtil.java b/netapi/CryptoUtil.java similarity index 97% rename from core/music/api/CryptoUtil.java rename to netapi/CryptoUtil.java index 8ae671c3..995f509b 100644 --- a/core/music/api/CryptoUtil.java +++ b/netapi/CryptoUtil.java @@ -1,7 +1,7 @@ -package com.coloryr.allmusic.server.core.music.api; +package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.api.EncResObj; +import com.coloryr.allmusic.server.netapi.obj.EncResObj; import com.google.gson.JsonObject; import javax.crypto.Cipher; diff --git a/netapi/EncryptType.java b/netapi/EncryptType.java new file mode 100644 index 00000000..a38cf206 --- /dev/null +++ b/netapi/EncryptType.java @@ -0,0 +1,5 @@ +package com.coloryr.allmusic.server.netapi; + +public enum EncryptType { + WEAPI, EAPI, API +} diff --git a/core/music/play/LyricDo.java b/netapi/LyricDecoder.java similarity index 97% rename from core/music/play/LyricDo.java rename to netapi/LyricDecoder.java index 5f2c96e0..d9891832 100644 --- a/core/music/play/LyricDo.java +++ b/netapi/LyricDecoder.java @@ -1,7 +1,7 @@ -package com.coloryr.allmusic.server.core.music.play; +package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.api.music.lyric.WLyricObj; +import com.coloryr.allmusic.server.netapi.obj.music.lyric.WLyricObj; import com.coloryr.allmusic.server.core.objs.music.LyricItemObj; import com.coloryr.allmusic.server.core.utils.Function; @@ -9,17 +9,15 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class LyricDo { +public class LyricDecoder { private static final Pattern p = Pattern.compile("\\(([0-9]+),[0-9]+.[0-9]\\)"); private final Map temp = new LinkedHashMap<>(); public boolean isHave = false; public boolean isHaveK = false; public Map kly = new LinkedHashMap<>(); - public Map getTemp() { return temp; } - public Map getKLyric() { return kly; } diff --git a/core/music/api/HttpClientUtil.java b/netapi/NetApiHttpClient.java similarity index 64% rename from core/music/api/HttpClientUtil.java rename to netapi/NetApiHttpClient.java index ffe70937..fab73eb8 100644 --- a/core/music/api/HttpClientUtil.java +++ b/netapi/NetApiHttpClient.java @@ -1,123 +1,34 @@ -package com.coloryr.allmusic.server.core.music.api; +package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.CookieObj; +import com.coloryr.allmusic.server.core.music.MusicHttpClient; import com.coloryr.allmusic.server.core.objs.HttpResObj; -import com.coloryr.allmusic.server.core.objs.api.EncResObj; -import com.coloryr.allmusic.server.core.objs.enums.EncryptType; +import com.coloryr.allmusic.server.netapi.obj.EncResObj; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.cookie.BasicCookieStore; import org.apache.hc.client5.http.cookie.Cookie; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClients; -import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicNameValuePair; -import org.apache.hc.core5.util.Timeout; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; -public class HttpClientUtil { - - private static final int CONNECT_TIMEOUT = 5; - private static final int READ_TIMEOUT = 7; - private static final String UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0"; - private static CloseableHttpClient client; - - public static void init() { - try { - synchronized (HttpClientUtil.class) { - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(Timeout.ofSeconds(CONNECT_TIMEOUT)) - .setResponseTimeout(Timeout.ofSeconds(READ_TIMEOUT)) - .build(); - client = HttpClients.custom() - .setDefaultRequestConfig(requestConfig) - .build(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static CookieStore createCookieStore() { - BasicCookieStore cookieStore = new BasicCookieStore(); - for (CookieObj cookie : AllMusic.cookie) { - BasicClientCookie cookie1 = new BasicClientCookie(cookie.name, cookie.value); - cookie1.setExpiryDate(Instant.MAX); - cookie1.setDomain(cookie.domain); - cookie1.setPath(cookie.path); - cookie1.setHttpOnly(cookie.hostOnly); - cookie1.setHttpOnly(cookie.httpOnly); - cookieStore.addCookie(cookie1); - } - return cookieStore; - } - - private static void saveCookies(CookieStore cookieStore) { - List cookies = cookieStore.getCookies(); - for (Cookie cookie : cookies) { - CookieObj obj = new CookieObj(); - obj.domain = cookie.getDomain(); - obj.hostOnly = cookie.isHttpOnly(); - obj.httpOnly = cookie.isHttpOnly(); - obj.name = cookie.getName(); - obj.value = cookie.getValue(); - } - AllMusic.saveCookie(); - } - - public static InputStream get(String path) { - try { - HttpGet request = new HttpGet(path); - request.setHeader("user-agent", UserAgent); - HttpClientContext context = HttpClientContext.create(); - CookieStore cookieStore = createCookieStore(); - context.setCookieStore(cookieStore); - CloseableHttpResponse response = client.execute(request, context); - int httpCode = response.getCode(); - HttpEntity entity = response.getEntity(); - if (entity == null) { - AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); - return null; - } - InputStream inputStream = entity.getContent(); - boolean ok = httpCode == 200; - if (!ok) { - EntityUtils.consume(entity); - inputStream.close(); - response.close(); - return null; - } - // 保存 cookies - saveCookies(cookieStore); - // 注意:需要调用者关闭 InputStream - return inputStream; - } catch (Exception e) { - AllMusic.log.warning("§d[AllMusic3]§c获取网页错误"); - e.printStackTrace(); - } - return null; - } +public class NetApiHttpClient { public static HttpResObj get(String path, String data) { try { @@ -125,11 +36,11 @@ public class HttpClientUtil { HttpGet request = new HttpGet(path + data); request.setHeader("referer", "https://music.163.com"); request.setHeader("content-type", "application/json;charset=UTF-8"); - request.setHeader("user-agent", UserAgent); + request.setHeader("user-agent", MusicHttpClient.UserAgent); HttpClientContext context = HttpClientContext.create(); - CookieStore cookieStore = createCookieStore(); + CookieStore cookieStore = MusicHttpClient.createCookieStore(); context.setCookieStore(cookieStore); - try (CloseableHttpResponse response = client.execute(request, context)) { + try (CloseableHttpResponse response = MusicHttpClient.client.execute(request, context)) { int httpCode = response.getCode(); HttpEntity entity = response.getEntity(); if (entity == null) { @@ -151,7 +62,7 @@ public class HttpClientUtil { AllMusic.log.warning("§d[AllMusic3]§c服务器返回错误:" + data1); } // 保存 cookies - saveCookies(cookieStore); + MusicHttpClient.saveCookies(cookieStore); return new HttpResObj(data1, ok); } } catch (Exception e) { @@ -167,13 +78,13 @@ public class HttpClientUtil { request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setHeader("Referer", "https://music.163.com"); HttpClientContext context = HttpClientContext.create(); - CookieStore cookieStore = createCookieStore(); + CookieStore cookieStore = MusicHttpClient.createCookieStore(); context.setCookieStore(cookieStore); EncResObj res; List cookies = cookieStore.getCookies(); // 注意:这里需要根据域名过滤,但为了简化,我们使用所有 cookies if (type == EncryptType.WEAPI) { - request.setHeader("User-Agent", UserAgent); + request.setHeader("User-Agent", MusicHttpClient.UserAgent); String csrfToken = ""; for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase("__csrf")) { @@ -228,7 +139,7 @@ public class HttpClientUtil { } request.setEntity(new UrlEncodedFormEntity(params)); } - try (CloseableHttpResponse response = client.execute(request, context)) { + try (CloseableHttpResponse response = MusicHttpClient.client.execute(request, context)) { int httpCode = response.getCode(); HttpEntity entity = response.getEntity(); if (entity == null) { @@ -249,7 +160,7 @@ public class HttpClientUtil { AllMusic.log.warning("§d[AllMusic3]§c服务器返回错误:" + data1); } // 保存 cookies - saveCookies(cookieStore); + MusicHttpClient.saveCookies(cookieStore); return new HttpResObj(data1, ok); } } catch (Exception e) { diff --git a/core/music/api/APIMain.java b/netapi/NetiApiMain.java similarity index 64% rename from core/music/api/APIMain.java rename to netapi/NetiApiMain.java index b3859962..463fe885 100644 --- a/core/music/api/APIMain.java +++ b/netapi/NetiApiMain.java @@ -1,23 +1,24 @@ -package com.coloryr.allmusic.server.core.music.api; +package com.coloryr.allmusic.server.netapi; import com.coloryr.allmusic.server.core.AllMusic; +import com.coloryr.allmusic.server.core.IMusicApi; import com.coloryr.allmusic.server.core.decoder.flac.FlacDecoder; import com.coloryr.allmusic.server.core.decoder.flac.StreamInfo; import com.coloryr.allmusic.server.core.decoder.mp3.Bitstream; import com.coloryr.allmusic.server.core.decoder.mp3.Header; -import com.coloryr.allmusic.server.core.music.play.LyricDo; -import com.coloryr.allmusic.server.core.music.play.LyricSave; +import com.coloryr.allmusic.server.core.music.LyricSave; +import com.coloryr.allmusic.server.core.music.MusicHttpClient; import com.coloryr.allmusic.server.core.objs.HttpResObj; import com.coloryr.allmusic.server.core.objs.MediaType; import com.coloryr.allmusic.server.core.objs.SearchMusicObj; -import com.coloryr.allmusic.server.core.objs.api.music.info.InfoObj; -import com.coloryr.allmusic.server.core.objs.api.music.list.DataObj; -import com.coloryr.allmusic.server.core.objs.api.music.lyric.WLyricObj; -import com.coloryr.allmusic.server.core.objs.api.music.search.SearchDataObj; -import com.coloryr.allmusic.server.core.objs.api.music.search.songs; -import com.coloryr.allmusic.server.core.objs.api.music.trialinfo.TrialInfoObj; -import com.coloryr.allmusic.server.core.objs.api.program.info.PrInfoObj; -import com.coloryr.allmusic.server.core.objs.enums.EncryptType; +import com.coloryr.allmusic.server.core.utils.Function; +import com.coloryr.allmusic.server.netapi.obj.music.info.InfoObj; +import com.coloryr.allmusic.server.netapi.obj.music.list.DataObj; +import com.coloryr.allmusic.server.netapi.obj.music.lyric.WLyricObj; +import com.coloryr.allmusic.server.netapi.obj.music.search.SearchDataObj; +import com.coloryr.allmusic.server.netapi.obj.music.search.songs; +import com.coloryr.allmusic.server.netapi.obj.music.trialinfo.TrialInfoObj; +import com.coloryr.allmusic.server.netapi.obj.program.info.PrInfoObj; import com.coloryr.allmusic.server.core.objs.message.ARG; import com.coloryr.allmusic.server.core.objs.music.SearchPageObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; @@ -30,93 +31,47 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.List; -public class APIMain { +public class NetiApiMain implements IMusicApi { private boolean isUpdate; - public APIMain() { + public NetiApiMain() { AllMusic.log.info("§d[AllMusic3]§e正在初始化网络爬虫"); - HttpClientUtil.init(); - HttpResObj res = HttpClientUtil.get("https://music.163.com", ""); + + HttpResObj res = NetApiHttpClient.get("https://music.163.com", ""); if (res == null || !res.ok) { - AllMusic.log.info("§d[AllMusic3]§c初始化网络爬虫连接失败"); + AllMusic.log.info("§d[AllMusic3]§c初始化net api失败"); } } - private static int toUnsignedInt(byte x) { - return ((int) x) & 0xff;//将高24位全部变成0,低8位保持不变 - } - - private static MediaType testMediaType(BufferedInputStream stream) throws IOException { - stream.mark(10); - byte[] temp = new byte[4]; - int res = stream.read(temp); - if (res != 4) { - return MediaType.Unknow; - } - if (temp[0] == 'R' && temp[1] == 'I' && temp[2] == 'F' && temp[3] == 'F') { - return MediaType.Wav; - } else if (temp[0] == 'f' && temp[1] == 'L' && temp[2] == 'a' && temp[3] == 'C') { - return MediaType.Flac; - } else if (temp[0] == 'I' && temp[1] == 'D' && temp[2] == '3') { - return MediaType.Mp3; - } else if (toUnsignedInt(temp[0]) == 0xFF && toUnsignedInt(temp[1]) == 0xE0) { - return MediaType.Mp3; - } - - return MediaType.Unknow; - } - - public static SongInfoObj getUrlMusic(String url) { - try { - InputStream stream = HttpClientUtil.get(url); - if (stream == null) { - return null; - } - BufferedInputStream in = new BufferedInputStream(stream); - MediaType type = testMediaType(in); - in.reset(); - float le = 0; - if (type == MediaType.Mp3) { - Bitstream bt = new Bitstream(in); - bt.readFrame(); - bt.closeFrame(); - Header h; - for (; ; ) { - h = bt.readFrame(); - if (h == null) { - break; - } - bt.closeFrame(); - le += h.ms_per_frame(); - } - bt.close(); - return new SongInfoObj(null, url, (int) le, type); - } else if (type == MediaType.Flac) { - FlacDecoder flac = new FlacDecoder(in); - for (; ; ) { - Object temp = flac.readAndHandleMetadataBlock(); - if (temp instanceof StreamInfo) { - StreamInfo info = (StreamInfo) temp; - le = (float) info.numSamples / info.sampleRate; - flac.close(); - return new SongInfoObj(null, url, (int) le, type); - } - } - } - stream.close(); - } catch (Exception e) { - AllMusic.log.warning("§d[AllMusic3]§c歌曲长度解析错误"); - e.printStackTrace(); - } - - return null; - } - - public boolean isUpdate() { + @Override + public boolean isBusy() { return isUpdate; } + @Override + public String getMusicId(String arg) { + if (arg.contains("id=") && !arg.contains("/?userid")) { + if (arg.contains("&uct2")) { + return Function.getString(arg, "id=", "&uct2"); + } else if (arg.contains("&user")) + return Function.getString(arg, "id=", "&user"); + else + return Function.getString(arg, "id=", null); + } else if (arg.contains("song/")) { + if (arg.contains("/?userid")) + return Function.getString(arg, "song/", "/?userid"); + else + return Function.getString(arg, "song/", null); + } else + return arg; + } + + @Override + public boolean checkId(String id) { + return Function.isInteger(id); + } + /** * 获取音乐详情 * @@ -129,14 +84,14 @@ public class APIMain { JsonObject params = new JsonObject(); params.addProperty("c", "[{\"id\":" + id + "}]"); - HttpResObj res = HttpClientUtil.post("https://music.163.com/api/v3/song/detail", params, EncryptType.WEAPI, null); + HttpResObj res = NetApiHttpClient.post("https://music.163.com/api/v3/song/detail", params, EncryptType.WEAPI, null); if (res != null && res.ok) { InfoObj temp = AllMusic.gson.fromJson(res.data, InfoObj.class); if (temp.isOk()) { params = new JsonObject(); params.addProperty("ids", "[" + id + "]"); params.addProperty("br", "320000"); - res = HttpClientUtil.post("https://music.163.com/weapi/song/enhance/player/url", params, EncryptType.WEAPI, null); + res = NetApiHttpClient.post("https://music.163.com/weapi/song/enhance/player/url", params, EncryptType.WEAPI, null); if (res == null || !res.ok) { AllMusic.log.warning("§d[AllMusic3]§c版权检索失败"); return null; @@ -150,6 +105,11 @@ public class APIMain { return null; } + @Override + public String getId() { + return "netapi"; + } + /** * 获取音乐数据 * @@ -164,7 +124,7 @@ public class APIMain { return info; JsonObject params = new JsonObject(); params.addProperty("id", id); - HttpResObj res = HttpClientUtil.post("https://music.163.com/api/dj/program/detail", params, EncryptType.WEAPI, null); + HttpResObj res = NetApiHttpClient.post("https://music.163.com/api/dj/program/detail", params, EncryptType.WEAPI, null); if (res != null && res.ok) { PrInfoObj temp = AllMusic.gson.fromJson(res.data, PrInfoObj.class); if (temp.isOk()) { @@ -189,7 +149,7 @@ public class APIMain { params.addProperty("ids", "[" + id + "]"); params.addProperty("level", "lossless"); params.addProperty("encodeType", "aac"); - HttpResObj res = HttpClientUtil.post("https://music.163.com/weapi/song/enhance/player/url/v1", params, EncryptType.WEAPI, null); + HttpResObj res = NetApiHttpClient.post("https://music.163.com/weapi/song/enhance/player/url/v1", params, EncryptType.WEAPI, null); if (res != null && res.ok) { try { TrialInfoObj obj = AllMusic.gson.fromJson(res.data, TrialInfoObj.class); @@ -214,12 +174,12 @@ public class APIMain { params.addProperty("id", id); params.addProperty("n", 100000); params.addProperty("s", 8); - HttpResObj res = HttpClientUtil.post("https://music.163.com/api/v6/playlist/detail", params, EncryptType.API, null); + HttpResObj res = NetApiHttpClient.post("https://music.163.com/api/v6/playlist/detail", params, EncryptType.API, null); if (res != null && res.ok) try { isUpdate = true; DataObj obj = AllMusic.gson.fromJson(res.data, DataObj.class); - DataSql.addIdleList(obj.getPlaylist()); + DataSql.addIdleList(obj.getPlaylist(), getId()); AllMusic.side.sendMessageTask(sender, AllMusic.getMessage().musicPlay.listMusic.get.replace(ARG.name, obj.getName())); } catch (Exception e) { AllMusic.log.warning("§d[AllMusic3]§c歌曲列表获取错误"); @@ -248,12 +208,12 @@ public class APIMain { params.addProperty("yv", 0); params.addProperty("ytv", 0); params.addProperty("rtv", 0); - HttpResObj res = HttpClientUtil.post("https://interface3.music.163.com/eapi/song/lyric/v1", + HttpResObj res = NetApiHttpClient.post("https://interface3.music.163.com/eapi/song/lyric/v1", params, EncryptType.EAPI, "/api/song/lyric/v1"); if (res != null && res.ok) { try { WLyricObj obj = AllMusic.gson.fromJson(res.data, WLyricObj.class); - LyricDo temp = new LyricDo(); + LyricDecoder temp = new LyricDecoder(); for (int times = 0; times < 3; times++) { if (temp.check(obj)) { AllMusic.log.warning("§d[AllMusic3]§c歌词解析错误,正在进行第" + times + "重试"); @@ -302,7 +262,7 @@ public class APIMain { params.addProperty("limit", 30); params.addProperty("offset", 0); - HttpResObj res = HttpClientUtil.post("https://music.163.com/weapi/search/get", params, EncryptType.WEAPI, null); + HttpResObj res = NetApiHttpClient.post("https://music.163.com/weapi/search/get", params, EncryptType.WEAPI, null); if (res != null && res.ok) { SearchDataObj obj = AllMusic.gson.fromJson(res.data, SearchDataObj.class); if (obj != null && obj.isOk()) { @@ -314,7 +274,7 @@ public class APIMain { resData.add(item); } maxpage = res1.size() / 10; - return new SearchPageObj(resData, maxpage); + return new SearchPageObj(resData, maxpage, getId()); } else { AllMusic.log.warning("§d[AllMusic3]§c歌曲搜索出现错误"); diff --git a/core/objs/api/EncResObj.java b/netapi/obj/EncResObj.java similarity index 80% rename from core/objs/api/EncResObj.java rename to netapi/obj/EncResObj.java index cd46e1ca..f85b9b79 100644 --- a/core/objs/api/EncResObj.java +++ b/netapi/obj/EncResObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api; +package com.coloryr.allmusic.server.netapi.obj; public class EncResObj { public String params; diff --git a/core/objs/api/music/info/InfoObj.java b/netapi/obj/music/info/InfoObj.java similarity index 97% rename from core/objs/api/music/info/InfoObj.java rename to netapi/obj/music/info/InfoObj.java index 20beff45..b103eecd 100644 --- a/core/objs/api/music/info/InfoObj.java +++ b/netapi/obj/music/info/InfoObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.info; +package com.coloryr.allmusic.server.netapi.obj.music.info; import java.util.List; diff --git a/core/objs/api/music/info/PlayObj.java b/netapi/obj/music/info/PlayObj.java similarity index 87% rename from core/objs/api/music/info/PlayObj.java rename to netapi/obj/music/info/PlayObj.java index f596ab27..fc0eded4 100644 --- a/core/objs/api/music/info/PlayObj.java +++ b/netapi/obj/music/info/PlayObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.info; +package com.coloryr.allmusic.server.netapi.obj.music.info; import java.util.List; diff --git a/core/objs/api/music/list/DataObj.java b/netapi/obj/music/list/DataObj.java similarity index 91% rename from core/objs/api/music/list/DataObj.java rename to netapi/obj/music/list/DataObj.java index 4f38e240..9c8f6e2e 100644 --- a/core/objs/api/music/list/DataObj.java +++ b/netapi/obj/music/list/DataObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.list; +package com.coloryr.allmusic.server.netapi.obj.music.list; import java.util.ArrayList; import java.util.List; diff --git a/core/objs/api/music/lyric/WLyricObj.java b/netapi/obj/music/lyric/WLyricObj.java similarity index 95% rename from core/objs/api/music/lyric/WLyricObj.java rename to netapi/obj/music/lyric/WLyricObj.java index 1d97ce4c..886fffd8 100644 --- a/core/objs/api/music/lyric/WLyricObj.java +++ b/netapi/obj/music/lyric/WLyricObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.lyric; +package com.coloryr.allmusic.server.netapi.obj.music.lyric; public class WLyricObj { private lrc lrc; diff --git a/core/objs/api/music/search/SearchDataObj.java b/netapi/obj/music/search/SearchDataObj.java similarity index 89% rename from core/objs/api/music/search/SearchDataObj.java rename to netapi/obj/music/search/SearchDataObj.java index ff1bc0b3..7050a370 100644 --- a/core/objs/api/music/search/SearchDataObj.java +++ b/netapi/obj/music/search/SearchDataObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.search; +package com.coloryr.allmusic.server.netapi.obj.music.search; import java.util.List; diff --git a/core/objs/api/music/search/songs.java b/netapi/obj/music/search/songs.java similarity index 89% rename from core/objs/api/music/search/songs.java rename to netapi/obj/music/search/songs.java index 97f13174..2d9a432b 100644 --- a/core/objs/api/music/search/songs.java +++ b/netapi/obj/music/search/songs.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.search; +package com.coloryr.allmusic.server.netapi.obj.music.search; import java.util.List; diff --git a/core/objs/api/music/trialinfo/TrialInfoObj.java b/netapi/obj/music/trialinfo/TrialInfoObj.java similarity index 93% rename from core/objs/api/music/trialinfo/TrialInfoObj.java rename to netapi/obj/music/trialinfo/TrialInfoObj.java index 69e2d177..329d2f5d 100644 --- a/core/objs/api/music/trialinfo/TrialInfoObj.java +++ b/netapi/obj/music/trialinfo/TrialInfoObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.trialinfo; +package com.coloryr.allmusic.server.netapi.obj.music.trialinfo; import java.util.List; diff --git a/core/objs/api/music/trialinfo/freeTrialInfo.java b/netapi/obj/music/trialinfo/freeTrialInfo.java similarity index 79% rename from core/objs/api/music/trialinfo/freeTrialInfo.java rename to netapi/obj/music/trialinfo/freeTrialInfo.java index 73be068d..954996c2 100644 --- a/core/objs/api/music/trialinfo/freeTrialInfo.java +++ b/netapi/obj/music/trialinfo/freeTrialInfo.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.music.trialinfo; +package com.coloryr.allmusic.server.netapi.obj.music.trialinfo; public class freeTrialInfo { private long start; diff --git a/core/objs/api/program/info/PrInfoObj.java b/netapi/obj/program/info/PrInfoObj.java similarity index 96% rename from core/objs/api/program/info/PrInfoObj.java rename to netapi/obj/program/info/PrInfoObj.java index c89c18e0..96729d46 100644 --- a/core/objs/api/program/info/PrInfoObj.java +++ b/netapi/obj/program/info/PrInfoObj.java @@ -1,4 +1,4 @@ -package com.coloryr.allmusic.server.core.objs.api.program.info; +package com.coloryr.allmusic.server.netapi.obj.program.info; public class PrInfoObj { diff --git a/remove.cmd b/remove.cmd index 0c1fba8c..9bb920e1 100644 --- a/remove.cmd +++ b/remove.cmd @@ -22,12 +22,6 @@ for %%i in (%array1%) do ( if exist "%%i\src\main\java\com\coloryr\allmusic\buffercodec" rmdir /s /q "%%i\src\main\java\com\coloryr\allmusic\buffercodec" ) -set array2=folia server_top server - -for %%i in (%array2%) do ( - if exist "%%i\src\main\java\com\coloryr\allmusic\server\bstats" rmdir /s /q "%%i\src\main\java\com\coloryr\allmusic\server\bstats" -) - set array3=fabric_1_16_5 fabric_1_20_1 fabric_1_21 fabric_1_21_6 fabric_1_21_11 ^ neoforge_1_21 neoforge_1_21_6 neoforge_1_21_11 diff --git a/server/build.gradle b/server/build.gradle index f9ac95dc..95f6810c 100644 --- a/server/build.gradle +++ b/server/build.gradle @@ -30,35 +30,15 @@ repositories { maven { url 'https://jitpack.io' } - maven { - url ' https://mvnrepository.com/artifact/mysql/mysql-connector-java' - } - maven { - url 'https://maven.citizensnpcs.co/repo' - } - maven { - name 'velocity' - url 'https://nexus.velocitypowered.com/repository/maven-public/' - } } dependencies { - //implementation "org.apache.commons:commons-dbcp2:2.9.0" - //implementation 'mysql:mysql-connector-java:8.0.31' - compileOnly 'org.spigotmc:spigot-api:1.20-R0.1-SNAPSHOT' - //compileOnly 'net.md-5:bungeecord-api:1.19-R0.1-SNAPSHOT' compileOnly "com.github.MilkBowl:VaultAPI:1.7.1" - //compileOnly 'com.velocitypowered:velocity-api:3.0.0' compileOnly 'me.clip:placeholderapi:2.11.6' - //compileOnly 'net.citizensnpcs:citizens-main:2.0.30-SNAPSHOT' -// compileOnly fileTree(dir:'lib',include:['*.jar']) - //implementation 'org.xerial:sqlite-jdbc:3.51.1.0' compile 'org.apache.httpcomponents.client5:httpclient5:5.6' compile 'com.google.code.gson:gson:2.10.1' - - //annotationProcessor 'com.velocitypowered:velocity-api:3.0.0' } shadowJar { diff --git a/server/src/main/java/com/coloryr/allmusic/server/AllMusicBukkit.java b/server/src/main/java/com/coloryr/allmusic/server/AllMusicBukkit.java index 735ed521..88b7d2f2 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/AllMusicBukkit.java +++ b/server/src/main/java/com/coloryr/allmusic/server/AllMusicBukkit.java @@ -1,8 +1,8 @@ package com.coloryr.allmusic.server; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; -import com.coloryr.allmusic.server.core.music.play.TopLyricSave; +import com.coloryr.allmusic.server.core.music.PlayMusic; +import com.coloryr.allmusic.server.core.music.TopLyricSave; import com.coloryr.allmusic.server.core.objs.music.TopSongInfoObj; import com.coloryr.allmusic.server.side.bukkit.*; import com.coloryr.allmusic.server.side.bukkit.hooks.AllMusicPAPI; @@ -17,7 +17,6 @@ public class AllMusicBukkit extends JavaPlugin { public static AllMusicPAPI PAPI; public static boolean spigotSet; private static PluginMessage pluginMessage; - private static MetricsBukkit metricsBukkit; @Override public void onEnable() { @@ -86,14 +85,11 @@ public class AllMusicBukkit extends JavaPlugin { Bukkit.getPluginManager().registerEvents(new ListenerBukkit(), this); AllMusic.start(); } - - metricsBukkit = new MetricsBukkit(this, 6720); } @Override public void onDisable() { AllMusic.isRun = false; - metricsBukkit.shutdown(); if (AllMusic.getConfig().topPAPI) pluginMessage.stop(); else diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/MetricsBukkit.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/MetricsBukkit.java deleted file mode 100644 index ad17297c..00000000 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/MetricsBukkit.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.coloryr.allmusic.server.side.bukkit; - -import com.coloryr.allmusic.server.bstats.MetricsBase; -import com.coloryr.allmusic.server.bstats.charts.CustomChart; -import com.coloryr.allmusic.server.bstats.json.JsonObjectBuilder; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.UUID; -import java.util.logging.Level; - -public class MetricsBukkit { - - private final Plugin plugin; - private final MetricsBase metricsBase; - - /** - * Creates a new Metrics instance. - * - * @param plugin Your plugin instance. - * @param serviceId The id of the service. - * It can be found at What is my plugin id? - */ - public MetricsBukkit(JavaPlugin plugin, int serviceId) { - 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); - - if (!config.isSet("serverUuid")) { - config.addDefault("enabled", true); - config.addDefault("serverUuid", UUID.randomUUID().toString()); - config.addDefault("logFailedRequests", false); - config.addDefault("logSentData", false); - config.addDefault("logResponseStatusText", false); - - // Inform the server owners about bStats - config.options().header( - "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + - "many people use their plugin and their total player count. It's recommended to keep bStats\n" + - "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + - "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + - "anonymous." - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } - - // Load the data - boolean enabled = config.getBoolean("enabled", true); - String serverUUID = config.getString("serverUuid"); - boolean logErrors = config.getBoolean("logFailedRequests", false); - boolean logSentData = config.getBoolean("logSentData", false); - boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); - - metricsBase = new MetricsBase( - "bukkit", - serverUUID, - serviceId, - enabled, - this::appendPlatformData, - this::appendServiceData, - submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), - plugin::isEnabled, - (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), - (message) -> this.plugin.getLogger().log(Level.INFO, message), - logErrors, - logSentData, - logResponseStatusText - ); - } - - /** - * Shuts down the underlying scheduler service. - */ - public void shutdown() { - metricsBase.shutdown(); - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - metricsBase.addCustomChart(chart); - } - - private void appendPlatformData(JsonObjectBuilder builder) { - builder.appendField("playerAmount", getPlayerAmount()); - builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); - builder.appendField("bukkitVersion", Bukkit.getVersion()); - builder.appendField("bukkitName", Bukkit.getName()); - - builder.appendField("javaVersion", System.getProperty("java.version")); - builder.appendField("osName", System.getProperty("os.name")); - builder.appendField("osArch", System.getProperty("os.arch")); - builder.appendField("osVersion", System.getProperty("os.version")); - builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); - } - - private void appendServiceData(JsonObjectBuilder builder) { - builder.appendField("pluginVersion", plugin.getDescription().getVersion()); - } - - private int getPlayerAmount() { - try { - // Around MC 1.8 the return type was changed from an array to a collection, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - return onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - return Bukkit.getOnlinePlayers().size(); // Just use the new method if the reflection failed - } - } - -} \ No newline at end of file diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/PluginMessage.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/PluginMessage.java index 20389f6b..9d22e355 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/PluginMessage.java +++ b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/PluginMessage.java @@ -2,8 +2,8 @@ package com.coloryr.allmusic.server.side.bukkit; import com.coloryr.allmusic.server.AllMusicBukkit; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; -import com.coloryr.allmusic.server.core.music.play.TopLyricSave; +import com.coloryr.allmusic.server.core.music.PlayMusic; +import com.coloryr.allmusic.server.core.music.TopLyricSave; import com.coloryr.allmusic.server.core.objs.music.TopSongInfoObj; import com.google.common.collect.Iterables; import com.google.common.io.ByteArrayDataInput; diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/SideBukkit.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/SideBukkit.java index 20b2eda4..c669c086 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/SideBukkit.java +++ b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/SideBukkit.java @@ -3,7 +3,7 @@ package com.coloryr.allmusic.server.side.bukkit; import com.coloryr.allmusic.codec.CommandType; import com.coloryr.allmusic.server.AllMusicBukkit; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import com.coloryr.allmusic.server.core.objs.music.SongInfoObj; import com.coloryr.allmusic.server.core.side.BaseSide; import com.coloryr.allmusic.server.side.bukkit.event.MusicAddEvent; @@ -249,7 +249,7 @@ public class SideBukkit extends BaseSide { } @Override - public boolean onMusicAdd(Object obj, MusicObj music) { + public boolean onMusicAdd(Object obj, PlayerAddMusicObj music) { MusicAddEvent event = new MusicAddEvent(music, (CommandSender) obj); Bukkit.getScheduler().callSyncMethod(AllMusicBukkit.plugin, () -> { Bukkit.getPluginManager().callEvent(event); diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/event/MusicAddEvent.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/event/MusicAddEvent.java index 712ee377..cf1ec7ba 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/event/MusicAddEvent.java +++ b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/event/MusicAddEvent.java @@ -1,6 +1,6 @@ package com.coloryr.allmusic.server.side.bukkit.event; -import com.coloryr.allmusic.server.core.objs.music.MusicObj; +import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj; import org.bukkit.command.CommandSender; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -14,7 +14,7 @@ public class MusicAddEvent extends Event { /** * 添加的音乐 */ - private final MusicObj music; + private final PlayerAddMusicObj music; /** * 添加者 */ @@ -24,7 +24,7 @@ public class MusicAddEvent extends Event { */ private boolean cancel = false; - public MusicAddEvent(MusicObj id, CommandSender player) { + public MusicAddEvent(PlayerAddMusicObj id, CommandSender player) { this.music = id; this.player = player; } @@ -45,7 +45,7 @@ public class MusicAddEvent extends Event { return player; } - public MusicObj getMusic() { + public PlayerAddMusicObj getMusic() { return music; } diff --git a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/hooks/AllMusicPAPI.java b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/hooks/AllMusicPAPI.java index daebc51f..c494370e 100644 --- a/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/hooks/AllMusicPAPI.java +++ b/server/src/main/java/com/coloryr/allmusic/server/side/bukkit/hooks/AllMusicPAPI.java @@ -1,7 +1,7 @@ package com.coloryr.allmusic.server.side.bukkit.hooks; import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.music.play.PlayMusic; +import com.coloryr.allmusic.server.core.music.PlayMusic; import com.coloryr.allmusic.server.side.bukkit.PluginMessage; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.OfflinePlayer; diff --git a/server/src/test/java/RunTest.java b/server/src/test/java/RunTest.java deleted file mode 100644 index d5214985..00000000 --- a/server/src/test/java/RunTest.java +++ /dev/null @@ -1,41 +0,0 @@ -import com.coloryr.allmusic.server.core.AllMusic; -import com.coloryr.allmusic.server.core.objs.CookieObj; -import com.coloryr.allmusic.server.core.objs.music.LyricItemObj; -import com.coloryr.allmusic.server.core.music.play.LyricSave; -import com.coloryr.allmusic.server.core.side.IMyLogger; - -public class RunTest implements IMyLogger { - public static void main(String[] arg) { - AllMusic.cookie = new CookieObj(); - AllMusic.log = new RunTest(); -// LyricSaveObj obj = AllMusic.getMusicApi().getLyric("2003496380"); -// if(obj.isHaveLyric()) -// { -// -// } - //https://music.163.com/song?id=1422767271&userid=124183854 - LyricSave obj = AllMusic.getMusicApi().getLyric("1449794087"); - if (obj.isHaveLyric()) { - int time = 0; - while (true) { - boolean res = obj.checkTime(time, true); - if (res) { - String temp = obj.getKly(); - if (temp != null) - System.out.println(temp); - } - time += 10; - } - } - } - - @Override - public void warning(String data) { - - } - - @Override - public void info(String data) { - - } -} diff --git a/version b/version index 77a069e3..240bba90 100644 --- a/version +++ b/version @@ -1 +1 @@ -3.6.2 \ No newline at end of file +3.7.0 \ No newline at end of file