diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..192221b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.gradle/ +build/ \ No newline at end of file diff --git a/build.gradle b/build.gradle index 023b55d..d112be3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,19 +1,22 @@ -group 'org.discordbots' +plugins { + id "java" +} -apply plugin: 'java' -apply plugin: 'maven' +group = 'org.discordbots' repositories { mavenCentral() } dependencies { - //Logger - compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' + implementation "org.slf4j:slf4j-api:2.0.17" - compile group: 'org.json', name: 'json', version: '20180130' - compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.11.0' - compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5' - compile group: 'com.fatboyindustrial.gson-javatime-serialisers', name: 'gson-javatime-serialisers', version: '1.1.1' -} + implementation "org.json:json:20250517" + implementation "com.squareup.okhttp3:okhttp:5.2.0" + implementation "com.google.code.gson:gson:2.13.2" + implementation "com.fatboyindustrial.gson-javatime-serialisers:gson-javatime-serialisers:1.1.2" + implementation "org.springframework.boot:spring-boot-starter-web:3.5.6" + implementation "jakarta.servlet:jakarta.servlet-api:6.1.0" + implementation "jakarta.ws.rs:jakarta.ws.rs-api:4.0.0" +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1948b90..8bdaf60 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3eba147..2e11132 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Sat Jul 14 00:30:34 EDT 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-all.zip diff --git a/gradlew b/gradlew index cccdd3d..adff685 100644 --- a/gradlew +++ b/gradlew @@ -1,78 +1,128 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index f955316..c4bdd3a 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,22 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -9,25 +27,29 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -35,48 +57,35 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/src/main/java/org/discordbots/api/client/DiscordBotListAPI.java b/src/main/java/org/discordbots/api/client/DiscordBotListAPI.java index 1dbd21c..f0d1b26 100644 --- a/src/main/java/org/discordbots/api/client/DiscordBotListAPI.java +++ b/src/main/java/org/discordbots/api/client/DiscordBotListAPI.java @@ -1,27 +1,39 @@ package org.discordbots.api.client; -import org.discordbots.api.client.entity.*; -import org.discordbots.api.client.impl.DiscordBotListAPIImpl; - import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; -public interface DiscordBotListAPI { +import org.discordbots.api.client.entity.Bot; +import org.discordbots.api.client.entity.BotResult; +import org.discordbots.api.client.entity.BotStats; +import org.discordbots.api.client.entity.SimpleUser; +import org.discordbots.api.client.entity.User; +import org.discordbots.api.client.entity.VotingMultiplier; +import org.discordbots.api.client.impl.DiscordBotListAPIImpl; +public interface DiscordBotListAPI { CompletionStage setStats(int shardId, int shardTotal, int serverCount); CompletionStage setStats(List shardServerCounts); - CompletionStage setStats(int serverCount); + CompletionStage setStats(final long serverCount); + CompletionStage getStats(); CompletionStage getStats(String botId); @Deprecated CompletionStage> getVoters(String botId); + CompletionStage> getVoters(); + CompletionStage> getVoters(int page); CompletionStage hasVoted(String userId); CompletionStage getBots(Map search, int limit, int offset); CompletionStage getBots(Map search, int limit, int offset, String sort); CompletionStage getBots(Map search, int limit, int offset, String sort, List fields); + CompletionStage getBots(); + CompletionStage getBots(int limit); + CompletionStage getBots(int limit, int offset); + CompletionStage getBots(int limit, int offset, String sort); + CompletionStage getBot(String botId); CompletionStage getUser(String userId); @@ -45,10 +57,10 @@ public Builder botId(String botId) { } public DiscordBotListAPI build() { - if(token == null) + if (token == null) throw new IllegalArgumentException("The provided token cannot be null!"); - if(botId == null) + if (botId == null) throw new IllegalArgumentException("The provided bot ID cannot be null!"); return new DiscordBotListAPIImpl(token, botId); diff --git a/src/main/java/org/discordbots/api/client/entity/Bot.java b/src/main/java/org/discordbots/api/client/entity/Bot.java index 0576dd9..2fdaf75 100644 --- a/src/main/java/org/discordbots/api/client/entity/Bot.java +++ b/src/main/java/org/discordbots/api/client/entity/Bot.java @@ -1,21 +1,19 @@ package org.discordbots.api.client.entity; -import com.google.gson.annotations.SerializedName; - import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.List; +import com.google.gson.annotations.SerializedName; + public class Bot { private String id; @SerializedName("clientid") private String clientId; private String username; - private String discriminator; private String avatar; - @SerializedName("defAvatar") - private String defaultAvatar; private String prefix; private String invite; @@ -23,31 +21,26 @@ public class Bot { private String vanity; private String support; private List tags; + private List owners; @SerializedName("longdesc") private String longDescription; @SerializedName("shortdesc") private String shortDescription; - @SerializedName("betadesc") - private String betaDescription; - @SerializedName("certifiedBot") - private boolean certified; + @SerializedName("github") + private String githubRepository; @SerializedName("date") // rename so that the naming actually makes sense - private OffsetDateTime approvalTime; + private OffsetDateTime submissionTime; @SerializedName("server_count") - private long serverCount; + private Long serverCount; - private List guilds; - private List shards; private int monthlyPoints; private int points; - - private boolean legacy; - - + + private Reviews reviews; public String getId() { return id; @@ -62,7 +55,7 @@ public String getUsername() { } public String getDiscriminator() { - return discriminator; + return "0"; } public String getAvatar() { @@ -70,7 +63,7 @@ public String getAvatar() { } public String getDefaultAvatar() { - return defaultAvatar; + return ""; } public String getPrefix() { @@ -97,6 +90,10 @@ public List getTags() { return tags; } + public List getOwners() { + return owners; + } + public String getLongDescription() { return longDescription; } @@ -106,27 +103,36 @@ public String getShortDescription() { } public String getBetaDescription() { - return betaDescription; + return ""; } public boolean isCertified() { - return certified; + return false; } + @Deprecated(since = "2.2", forRemoval = true) public OffsetDateTime getApprovalTime() { - return approvalTime; + return submissionTime; + } + + public String getGithubRepository() { + return githubRepository; } - public long getServerCount() { + public OffsetDateTime getSubmissionTime() { + return submissionTime; + } + + public Long getServerCount() { return serverCount; } public List getGuilds() { - return guilds; + return new ArrayList<>(); } public List getShards() { - return shards; + return new ArrayList<>(); } public int getMonthlyPoints() { @@ -138,7 +144,10 @@ public int getPoints() { } public boolean isLegacy() { - return legacy; + return false; } + public Reviews getReviews() { + return reviews; + } } diff --git a/src/main/java/org/discordbots/api/client/entity/BotStats.java b/src/main/java/org/discordbots/api/client/entity/BotStats.java index 209edfd..0ab5aec 100644 --- a/src/main/java/org/discordbots/api/client/entity/BotStats.java +++ b/src/main/java/org/discordbots/api/client/entity/BotStats.java @@ -1,16 +1,15 @@ package org.discordbots.api.client.entity; -import com.google.gson.annotations.SerializedName; - -import java.util.Collections; +import java.util.ArrayList; import java.util.List; +import com.google.gson.annotations.SerializedName; + public class BotStats { @SerializedName("server_count") - private int serverCount; - private List shards; + private Long serverCount; - public int getServerCount() { return serverCount; } - public List getShards() { return Collections.unmodifiableList(shards); } + public Long getServerCount() { return serverCount; } + public List getShards() { return new ArrayList<>(); } } diff --git a/src/main/java/org/discordbots/api/client/entity/Reviews.java b/src/main/java/org/discordbots/api/client/entity/Reviews.java new file mode 100644 index 0000000..76ffd3b --- /dev/null +++ b/src/main/java/org/discordbots/api/client/entity/Reviews.java @@ -0,0 +1,7 @@ +package org.discordbots.api.client.entity; + +public class Reviews { + public double averageScore; + + public int count; +} \ No newline at end of file diff --git a/src/main/java/org/discordbots/api/client/entity/SimpleUser.java b/src/main/java/org/discordbots/api/client/entity/SimpleUser.java index 562f0ed..e9edc4f 100644 --- a/src/main/java/org/discordbots/api/client/entity/SimpleUser.java +++ b/src/main/java/org/discordbots/api/client/entity/SimpleUser.java @@ -4,12 +4,9 @@ public class SimpleUser { private String id; private String username; - private String discriminator; private String avatar; - - public String getId() { return id; } @@ -19,7 +16,7 @@ public String getUsername() { } public String getDiscriminator() { - return discriminator; + return "0"; } public String getAvatar() { diff --git a/src/main/java/org/discordbots/api/client/entity/Social.java b/src/main/java/org/discordbots/api/client/entity/Social.java index d7a64e0..f92a5e2 100644 --- a/src/main/java/org/discordbots/api/client/entity/Social.java +++ b/src/main/java/org/discordbots/api/client/entity/Social.java @@ -4,4 +4,4 @@ public class Social { String youtube, reddit, twitter, instagram, github; -} +} \ No newline at end of file diff --git a/src/main/java/org/discordbots/api/client/entity/User.java b/src/main/java/org/discordbots/api/client/entity/User.java index bfed556..6d637d7 100644 --- a/src/main/java/org/discordbots/api/client/entity/User.java +++ b/src/main/java/org/discordbots/api/client/entity/User.java @@ -12,8 +12,6 @@ public class User extends SimpleUser { private Social social; - - public String getDefaultAvatar() { return defaultAvatar; } @@ -45,5 +43,4 @@ public boolean isSupporter() { public Social getSocial() { return social; } - -} +} \ No newline at end of file diff --git a/src/main/java/org/discordbots/api/client/entity/Vote.java b/src/main/java/org/discordbots/api/client/entity/Vote.java index 047f6de..08f92bd 100644 --- a/src/main/java/org/discordbots/api/client/entity/Vote.java +++ b/src/main/java/org/discordbots/api/client/entity/Vote.java @@ -6,6 +6,10 @@ public class Vote { @SerializedName("bot") private String botId; + + @SerializedName("guild") + private String serverId; + @SerializedName("user") private String userId; @@ -16,12 +20,14 @@ public class Vote { @SerializedName("isWeekend") private boolean weekend; - - public String getBotId() { return botId; } + public String getServerId() { + return serverId; + } + public String getUserId() { return userId; } diff --git a/src/main/java/org/discordbots/api/client/entity/VotingMultiplier.java b/src/main/java/org/discordbots/api/client/entity/VotingMultiplier.java index 6f927fe..bfdc936 100644 --- a/src/main/java/org/discordbots/api/client/entity/VotingMultiplier.java +++ b/src/main/java/org/discordbots/api/client/entity/VotingMultiplier.java @@ -7,8 +7,6 @@ public class VotingMultiplier { @SerializedName("is_weekend") private boolean weekend; - - public boolean isWeekend() { return weekend; } diff --git a/src/main/java/org/discordbots/api/client/entity/Widget.java b/src/main/java/org/discordbots/api/client/entity/Widget.java new file mode 100644 index 0000000..543f30c --- /dev/null +++ b/src/main/java/org/discordbots/api/client/entity/Widget.java @@ -0,0 +1,26 @@ +package org.discordbots.api.client.entity; + +public final class Widget { + private final static String BASE_URL = "https://top.gg/api/v1"; + + public static enum Type { + DISCORD_BOT, + DISCORD_SERVER, + } + + public static String large(Type ty, String id) { + return BASE_URL + "/widgets/large/" + ty.name().toLowerCase().replace('_', '/') + "/" + id; + } + + public static String votes(Type ty, String id) { + return BASE_URL + "/widgets/small/votes/" + ty.name().toLowerCase().replace('_', '/') + "/" + id; + } + + public static String owner(Type ty, String id) { + return BASE_URL + "/widgets/small/owner/" + ty.name().toLowerCase().replace('_', '/') + "/" + id; + } + + public static String social(Type ty, String id) { + return BASE_URL + "/widgets/small/social/" + ty.name().toLowerCase().replace('_', '/') + "/" + id; + } +} \ No newline at end of file diff --git a/src/main/java/org/discordbots/api/client/impl/DiscordBotListAPIImpl.java b/src/main/java/org/discordbots/api/client/impl/DiscordBotListAPIImpl.java index 546df9a..f423a07 100644 --- a/src/main/java/org/discordbots/api/client/impl/DiscordBotListAPIImpl.java +++ b/src/main/java/org/discordbots/api/client/impl/DiscordBotListAPIImpl.java @@ -1,16 +1,5 @@ package org.discordbots.api.client.impl; -import com.fatboyindustrial.gsonjavatime.OffsetDateTimeConverter; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import okhttp3.*; -import org.discordbots.api.client.DiscordBotListAPI; -import org.discordbots.api.client.entity.*; -import org.discordbots.api.client.io.DefaultResponseTransformer; -import org.discordbots.api.client.io.ResponseTransformer; -import org.discordbots.api.client.io.UnsuccessfulHttpException; -import org.json.JSONObject; - import java.io.IOException; import java.time.OffsetDateTime; import java.util.Arrays; @@ -18,7 +7,34 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; -import java.util.stream.Collectors; + +import org.discordbots.api.client.DiscordBotListAPI; +import org.discordbots.api.client.entity.Bot; +import org.discordbots.api.client.entity.BotResult; +import org.discordbots.api.client.entity.BotStats; +import org.discordbots.api.client.entity.SimpleUser; +import org.discordbots.api.client.entity.User; +import org.discordbots.api.client.entity.VotingMultiplier; +import org.discordbots.api.client.io.DefaultResponseTransformer; +import org.discordbots.api.client.io.EmptyResponseTransformer; +import org.discordbots.api.client.io.ResponseTransformer; +import org.discordbots.api.client.io.UnsuccessfulHttpException; +import org.json.JSONException; +import org.json.JSONObject; + +import com.fatboyindustrial.gsonjavatime.OffsetDateTimeConverter; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class DiscordBotListAPIImpl implements DiscordBotListAPI { @@ -44,61 +60,72 @@ public DiscordBotListAPIImpl(String token, String botId) { this.httpClient = new OkHttpClient.Builder() .addInterceptor((chain) -> { Request req = chain.request().newBuilder() - .addHeader("Authorization", this.token) + .addHeader("Authorization", "Bearer " + this.token) .build(); return chain.proceed(req); }) .build(); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage setStats(int shardId, int shardTotal, int serverCount) { - JSONObject json = new JSONObject() - .put("shard_id", shardId) - .put("shard_count", shardTotal) - .put("server_count", serverCount); - - return setStats(json); + return setStats(serverCount); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage setStats(List shardServerCounts) { - JSONObject json = new JSONObject() - .put("shards", shardServerCounts); - - return setStats(json); + return setStats(shardServerCounts.stream().mapToInt(Integer::intValue).sum()); } - public CompletionStage setStats(int serverCount) { - JSONObject json = new JSONObject() - .put("server_count", serverCount); - - return setStats(json); - } - - private CompletionStage setStats(JSONObject jsonBody) { - HttpUrl url = baseUrl.newBuilder() + @Override + public CompletionStage setStats(final long serverCount) { + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("bots") - .addPathSegment(botId) .addPathSegment("stats") .build(); - - return post(url, jsonBody, Void.class); + + final JSONObject json = new JSONObject() + .put("server_count", serverCount); + + return post(url, json, new EmptyResponseTransformer()); } - public CompletionStage getStats(String botId) { - HttpUrl url = baseUrl.newBuilder() + @Override + public CompletionStage getStats() { + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("bots") - .addPathSegment(botId) .addPathSegment("stats") .build(); return get(url, BotStats.class); } + @Override + @Deprecated(since = "2.2", forRemoval = true) + public CompletionStage getStats(String botId) { + return getStats(); + } + + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage> getVoters(String botId) { - HttpUrl url = baseUrl.newBuilder() + return getVoters(); + } + + @Override + public CompletionStage> getVoters() { + return getVoters(1); + } + + @Override + public CompletionStage> getVoters(int page) { + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("bots") .addPathSegment(botId) .addPathSegment("votes") + .addQueryParameter("page", String.valueOf(page <= 0 ? 1 : page)) .build(); return get(url, resp -> { @@ -109,8 +136,9 @@ public CompletionStage> getVoters(String botId) { }); } + @Override public CompletionStage getBot(String botId) { - HttpUrl url = baseUrl.newBuilder() + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("bots") .addPathSegment(botId) .build(); @@ -118,76 +146,104 @@ public CompletionStage getBot(String botId) { return get(url, Bot.class); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage getBots(Map search, int limit, int offset) { - return getBots(search, limit, offset, null); + return getBots(limit, offset); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage getBots(Map search, int limit, int offset, String sort) { - return getBots(search, limit, offset, sort, null); + return getBots(limit, offset, sort); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage getBots(Map search, int limit, int offset, String sort, List fields) { - // DBL search uses this format: field1: value1 field2: value2 - String searchString = search.entrySet().stream() - .map(entry -> entry.getKey() + ": " + entry.getValue()) - .collect(Collectors.joining(" ")); + return getBots(limit, offset, sort); + } + + @Override + public CompletionStage getBots() { + return getBots(50); + } + + @Override + public CompletionStage getBots(int limit) { + return getBots(limit, 0); + } + + @Override + public CompletionStage getBots(int limit, int offset) { + return getBots(limit, offset, null); + } + + @Override + public CompletionStage getBots(int limit, int offset, String sort) { + if (limit > 500) { + limit = 500; + } else if (limit <= 0) { + limit = 50; + } + + if (offset <= 0) { + offset = 0; + } HttpUrl.Builder urlBuilder = baseUrl.newBuilder() .addPathSegment("bots") - .addQueryParameter("search", searchString) .addQueryParameter("limit", String.valueOf(limit)) .addQueryParameter("offset", String.valueOf(offset)); - if(sort != null) { + if (sort != null && (sort.equals("monthlyPoints") || sort.equals("id") || sort.equals("date"))) { urlBuilder.addQueryParameter("sort", sort); } - if(fields != null) { - String fieldsString = fields.stream() - .collect(Collectors.joining(" ")); - - urlBuilder.addQueryParameter("fields", fieldsString); - } - return get(urlBuilder.build(), BotResult.class); } + @Override + @Deprecated(since = "2.2", forRemoval = true) public CompletionStage getUser(String userId) { - HttpUrl url = baseUrl.newBuilder() - .addPathSegment("users") - .addPathSegment(userId) - .build(); - - return get(url, User.class); + return CompletableFuture.completedFuture(null); } + @Override public CompletionStage hasVoted(String userId) { - HttpUrl url = baseUrl.newBuilder() + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("bots") - .addPathSegment(botId) .addPathSegment("check") .addQueryParameter("userId", userId) .build(); return get(url, (resp) -> { - JSONObject json = new JSONObject(resp.body().string()); + final ResponseBody body = resp.body(); + + if (body == null) { + return false; + } + + final JSONObject json = new JSONObject(body.string()); + return json.getInt("voted") == 1; }); } + @Override public CompletionStage getVotingMultiplier() { - HttpUrl url = baseUrl.newBuilder() + final HttpUrl url = baseUrl.newBuilder() .addPathSegment("weekend") .build(); return get(url, VotingMultiplier.class); } - private CompletionStage get(HttpUrl url, Class aClass) { + private CompletionStage get(final HttpUrl url, Class aClass) { return get(url, new DefaultResponseTransformer<>(aClass, gson)); } - private CompletionStage get(HttpUrl url, ResponseTransformer responseTransformer) { + private CompletionStage get(final HttpUrl url, ResponseTransformer responseTransformer) { Request req = new Request.Builder() .get() .url(url) @@ -199,13 +255,13 @@ private CompletionStage get(HttpUrl url, ResponseTransformer responseT // The class provided in this is kinda unneeded because the only thing ever given to it // is Void, but I wanted to make it expandable (maybe some post methods will return objects // in the future) - private CompletionStage post(HttpUrl url, JSONObject jsonBody, Class aClass) { - return post(url, jsonBody, new DefaultResponseTransformer<>(aClass, gson)); - } + // private CompletionStage post(final HttpUrl url, JSONObject jsonBody, Class aClass) { + // return post(url, jsonBody, new DefaultResponseTransformer<>(aClass, gson)); + // } - private CompletionStage post(HttpUrl url, JSONObject jsonBody, ResponseTransformer responseTransformer) { + private CompletionStage post(final HttpUrl url, JSONObject jsonBody, ResponseTransformer responseTransformer) { MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, jsonBody.toString()); + RequestBody body = RequestBody.create(jsonBody.toString(), mediaType); Request req = new Request.Builder() .post(body) @@ -239,11 +295,14 @@ public void onResponse(Call call, Response response) { // DBL sends error messages as part of the body and leaves the // actual message blank so this will just pull that instead because // it's 1000x more useful than the actual message - if (message == null || message.isEmpty()) { + if (message.isEmpty()) { try { - JSONObject body = new JSONObject(response.body().string()); - message = body.getString("error"); - } catch (Exception ignored) {} + final ResponseBody body = response.body(); + + if (body != null) { + message = (new JSONObject(body)).getString("error"); + } + } catch (final JSONException ignored) {} } Exception e = new UnsuccessfulHttpException(response.code(), message); @@ -253,7 +312,11 @@ public void onResponse(Call call, Response response) { } catch (Exception e) { future.completeExceptionally(e); } finally { - response.body().close(); + final ResponseBody body = response.body(); + + if (body != null) { + body.close(); + } } } }); @@ -261,4 +324,4 @@ public void onResponse(Call call, Response response) { return future; } -} +} \ No newline at end of file diff --git a/src/main/java/org/discordbots/api/client/io/DefaultResponseTransformer.java b/src/main/java/org/discordbots/api/client/io/DefaultResponseTransformer.java index 8639e10..0ee54df 100644 --- a/src/main/java/org/discordbots/api/client/io/DefaultResponseTransformer.java +++ b/src/main/java/org/discordbots/api/client/io/DefaultResponseTransformer.java @@ -1,9 +1,11 @@ package org.discordbots.api.client.io; +import java.io.IOException; + import com.google.gson.Gson; -import okhttp3.Response; -import java.io.IOException; +import okhttp3.Response; +import okhttp3.ResponseBody; public class DefaultResponseTransformer implements ResponseTransformer { @@ -17,8 +19,13 @@ public DefaultResponseTransformer(Class aClass, Gson gson) { @Override public E transform(Response response) throws IOException { - String body = response.body().string(); - return gson.fromJson(body, aClass); + try (ResponseBody responseBody = response.body()) { + if (responseBody != null) { + return gson.fromJson(responseBody.charStream(), aClass); + } + } + + throw new IOException("Unable to parse JSON because of malformed response body."); } } diff --git a/src/main/java/org/discordbots/api/client/io/EmptyResponseTransformer.java b/src/main/java/org/discordbots/api/client/io/EmptyResponseTransformer.java new file mode 100644 index 0000000..55eff44 --- /dev/null +++ b/src/main/java/org/discordbots/api/client/io/EmptyResponseTransformer.java @@ -0,0 +1,10 @@ +package org.discordbots.api.client.io; + +import okhttp3.Response; + +public class EmptyResponseTransformer implements ResponseTransformer { + @Override + public Void transform(Response response) { + return null; + } +} \ No newline at end of file