diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8265a1d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,59 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2f50121..bc88aeb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,10 +16,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -41,10 +41,10 @@ jobs: needs: - build-gradle steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Download artifact - uses: actions/download-artifact@v3.0.0 + uses: actions/download-artifact@v3.0.2 with: # Artifact name name: claptrap_jar @@ -52,10 +52,10 @@ jobs: path: build/libs/ - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - name: Login to ghcr.io - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.repository_owner }} @@ -70,7 +70,7 @@ jobs: echo "tag=${{ steps.branch-name.outputs.current_branch }}" >> $GITHUB_ENV - name: Build and push Docker - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v5 with: push: true context: . diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c599ed1..e5af1ae 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,10 +14,10 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 @@ -39,10 +39,10 @@ jobs: needs: - build-gradle steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Download artifact - uses: actions/download-artifact@v3.0.0 + uses: actions/download-artifact@v3.0.2 with: # Artifact name name: claptrap_jar @@ -50,10 +50,10 @@ jobs: path: build/libs/ - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - name: Login to ghcr.io - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.repository_owner }} @@ -68,7 +68,7 @@ jobs: echo "tag=${{ steps.branch-name.outputs.tag }}" >> $GITHUB_ENV - name: Build and push Docker - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v5 with: push: true context: . diff --git a/.gitignore b/.gitignore index a951070..8265a1d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,36 +1,59 @@ -.idea/ -.gradle -config/ -lib/ -logs/ -out/ - -/build/ -*.iml -META-INF/ -*.uml - +# Compiled class file *.class +# Log file +*.log -classes/artifacts/Discord_Stroumpf_Beta_jar/ +# BlueJ files +*.ctxt -src/main/resources/templates/css +# Mobile Tools for Java (J2ME) +.mtj.tmp/ -src/main/resources/templates/js +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar -\.directory +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* -\.credentials/ +.gradle +**/build/ +!src/**/build/ -src/main/resources/static/error/css +# Ignore Gradle GUI config +gradle-app.setting -src/main/resources/static/error/js +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties -**.log -.jpb/ +# Cache of project +.gradletasknamecache -**/*.env +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath -bin/ +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix diff --git a/.vscode/settings.json b/.vscode/settings.json index 1133129..e788bfc 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,7 @@ { - "java.configuration.updateBuildConfiguration": "automatic" -} \ No newline at end of file + "java.configuration.updateBuildConfiguration": "automatic", + "java.compile.nullAnalysis.mode": "disabled", + "editor.codeActionsOnSave": { + "source.organizeImports": "explicit" + } +} diff --git a/.woodpecker/build_docker.yml b/.woodpecker/build_docker.yml new file mode 100644 index 0000000..2552177 --- /dev/null +++ b/.woodpecker/build_docker.yml @@ -0,0 +1,33 @@ +steps: + build-dev: + image: woodpeckerci/plugin-docker-buildx + settings: + repo: git.sebclem.fr/sebclem/${CI_REPO_NAME,,} + cache_from: git.sebclem.fr/sebclem/${CI_REPO_NAME,,} + registry: git.sebclem.fr + auto_tag: true + logins: + - registry: https://git.sebclem.fr + username: + from_secret: docker_user + password: + from_secret: docker_token + when: + event: [push, pull_request, manual] + + publish: + image: woodpeckerci/plugin-docker-buildx + settings: + platforms: linux/amd64 + auto_tag: true + repo: git.sebclem.fr/sebclem/${CI_REPO_NAME,,} + cache_from: git.sebclem.fr/sebclem/${CI_REPO_NAME,,} + logins: + - registry: https://git.sebclem.fr + username: + from_secret: docker_user + password: + from_secret: docker_token + when: + event: + - tag \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 9ae49ad..7afbf99 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,10 +1,15 @@ -FROM openjdk:18.0.1 -WORKDIR /bot_src -ARG BUILD_NBR -ARG BRANCH_NAME -ARG BRANCH_NAME -ARG GITHUB_RUN_NUMBER -ADD build/libs/ClaptrapBot.jar /bot_src/claptrapbot.jar -RUN java -version -CMD java -jar claptrapbot.jar -LABEL org.opencontainers.image.source=https://github.com/Sebclem/ClaptrapBot/ \ No newline at end of file +FROM eclipse-temurin:21-jdk-alpine AS build +WORKDIR /workspace/app +COPY . /workspace/app + +RUN ./gradlew clean build +RUN mkdir -p build/dependency && (cd build/dependency; jar -xf ../libs/*.jar) + + +FROM eclipse-temurin:21-jdk-alpine +ARG DEPENDENCY=/workspace/app/build/dependency +COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib +COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF +COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app +ENTRYPOINT ["java","-cp","app:app/lib/*","net.Broken.MainBot"] +LABEL org.opencontainers.image.source=https://git.sebclem.fr/sebclem/ClaptrapBot \ No newline at end of file diff --git a/build.gradle b/build.gradle index d7670c1..271e7b4 100644 --- a/build.gradle +++ b/build.gradle @@ -1,16 +1,16 @@ plugins { - id 'org.springframework.boot' version '2.7.2' - id 'io.spring.dependency-management' version '1.0.12.RELEASE' + id 'org.springframework.boot' version '3.2.1' + id 'io.spring.dependency-management' version '1.1.4' id 'java' id 'groovy' - id 'org.liquibase.gradle' version '2.1.1' - id "nebula.lint" version "17.7.0" + id 'org.liquibase.gradle' version '2.2.1' + id "nebula.lint" version "19.0.1" id "com.gorylenko.gradle-git-properties" version "2.4.1" } group = "net.broken" archivesBaseName = "ClaptrapBot" -sourceCompatibility = '17' +sourceCompatibility = JavaVersion.VERSION_21.toString() repositories { mavenCentral() @@ -33,38 +33,38 @@ dependencies { implementation("org.springframework.boot:spring-boot-starter-log4j2") implementation("org.springframework.boot:spring-boot-starter-oauth2-client") implementation('org.springframework.boot:spring-boot-starter-actuator') - implementation('io.micrometer:micrometer-registry-prometheus:1.9.2') + implementation('io.micrometer:micrometer-registry-prometheus:1.12.1') - implementation('org.springdoc:springdoc-openapi-ui:1.6.9') - implementation('org.springdoc:springdoc-openapi-security:1.6.9') + implementation('org.springdoc:springdoc-openapi-ui:1.7.0') + implementation('org.springdoc:springdoc-openapi-security:1.7.0') implementation('org.liquibase:liquibase-core') - implementation('io.jsonwebtoken:jjwt-api:0.11.5') - implementation('io.jsonwebtoken:jjwt-impl:0.11.5') - implementation('io.jsonwebtoken:jjwt-jackson:0.11.5') + implementation('io.jsonwebtoken:jjwt-api:0.12.3') + implementation('io.jsonwebtoken:jjwt-impl:0.12.3') + implementation('io.jsonwebtoken:jjwt-jackson:0.12.3') implementation('com.sedmelluq:lavaplayer:1.3.78') - implementation('net.dv8tion:JDA:4.4.1_353') + implementation('net.dv8tion:JDA:5.0.0-beta.18') - implementation(platform("org.apache.logging.log4j:log4j-bom:2.18.0")) - implementation group: 'org.hibernate', name: 'hibernate-validator', version: '7.0.4.Final' + implementation(platform("org.apache.logging.log4j:log4j-bom:2.22.1")) + implementation group: 'org.hibernate', name: 'hibernate-validator', version: '8.0.1.Final' // Use MySQL Connector-J - implementation('mysql:mysql-connector-java:8.0.30') + implementation('mysql:mysql-connector-java:8.0.33') implementation('org.reflections:reflections:0.10.2') - implementation('org.apache.commons:commons-lang3:3.12.0') + implementation('org.apache.commons:commons-lang3:3.14.0') - liquibaseRuntime('org.liquibase:liquibase-core:4.14.0') - liquibaseRuntime('org.liquibase:liquibase-groovy-dsl:3.0.2') - liquibaseRuntime('mysql:mysql-connector-java:8.0.30') + liquibaseRuntime('org.liquibase:liquibase-core:4.25.1') + liquibaseRuntime('org.liquibase:liquibase-groovy-dsl:3.0.3') + liquibaseRuntime('mysql:mysql-connector-java:8.0.33') liquibaseRuntime group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' - liquibaseRuntime group: 'org.liquibase.ext', name: 'liquibase-hibernate5', version: '4.14.0' + liquibaseRuntime group: 'org.liquibase.ext', name: 'liquibase-hibernate5', version: '4.25.1' liquibaseRuntime 'org.springframework.boot:spring-boot-starter-data-jpa' liquibaseRuntime 'org.springframework.data:spring-data-jpa' liquibaseRuntime 'org.springframework:spring-beans' - liquibaseRuntime 'net.dv8tion:JDA:4.4.0_352' + liquibaseRuntime 'net.dv8tion:JDA:5.0.0-beta.18' liquibaseRuntime 'com.sedmelluq:lavaplayer:1.3.78' liquibaseRuntime sourceSets.main.output diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..d64cd49 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 8049c68..1af9e09 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 index 4f906e0..1aa94a4 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 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. @@ -17,67 +17,99 @@ # ############################################################################## -## -## 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/subprojects/plugins/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='"-Xmx64m" "-Xms64m"' +# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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 @@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 @@ -98,88 +130,120 @@ 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 -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 - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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\"" - fi - i=`expr $i + 1` - 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" ;; +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 -# 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, 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. -# 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" +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + 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 + # 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 +fi + + +# 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, 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" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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 107acd3..6689b85 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,89 +1,92 @@ -@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 - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -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="-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 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. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -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. - -goto fail - -: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 %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="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 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@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 + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +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="-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% 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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +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. + +goto fail + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +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! +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 + +:omega diff --git a/src/main/java/net/Broken/Api/Controllers/AudioController.java b/src/main/java/net/Broken/Api/Controllers/AudioController.java index ee7bce0..c0cf857 100644 --- a/src/main/java/net/Broken/Api/Controllers/AudioController.java +++ b/src/main/java/net/Broken/Api/Controllers/AudioController.java @@ -23,60 +23,60 @@ public class AudioController { this.audioService = audioService; } - @GetMapping("/{guildId}/status") - @PreAuthorize("isInGuild(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId)") public Status getMusicStatus(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.getGuildAudioStatus(guildId, principal.user().getDiscordId()); } - @PostMapping("/{guildId}/connect") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId, #body)") - public ResponseEntity connect(@PathVariable String guildId, @RequestBody Connect body, Authentication authentication) { + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId, #body)") + public ResponseEntity connect(@PathVariable String guildId, @RequestBody Connect body, + Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.connect(guildId, body, principal.user().getDiscordId()); } @PostMapping("/{guildId}/disconnect") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") public ResponseEntity disconnect(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.disconnect(guildId, principal.user().getDiscordId()); } @PostMapping("/{guildId}/resume") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") public ResponseEntity resume(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.resume(guildId, principal.user().getDiscordId()); } @PostMapping("/{guildId}/pause") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") public ResponseEntity pause(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.pause(guildId, principal.user().getDiscordId()); } @PostMapping("/{guildId}/skip") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") public ResponseEntity skip(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.skip(guildId, principal.user().getDiscordId()); } @PostMapping("/{guildId}/stop") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") public ResponseEntity stop(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.stop(guildId, principal.user().getDiscordId()); } @PostMapping("/{guildId}/add") - @PreAuthorize("isInGuild(#guildId) && canInteractWithVoiceChannel(#guildId)") - public ResponseEntity add(@PathVariable String guildId, @RequestBody Add body, Authentication authentication) throws ExecutionException, InterruptedException { + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canInteractWithVoiceChannel(#guildId)") + public ResponseEntity add(@PathVariable String guildId, @RequestBody Add body, + Authentication authentication) throws ExecutionException, InterruptedException { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return audioService.add(guildId, principal.user().getDiscordId(), body); } diff --git a/src/main/java/net/Broken/Api/Controllers/AuthController.java b/src/main/java/net/Broken/Api/Controllers/AuthController.java index 75d6c43..89795c5 100644 --- a/src/main/java/net/Broken/Api/Controllers/AuthController.java +++ b/src/main/java/net/Broken/Api/Controllers/AuthController.java @@ -19,7 +19,8 @@ public class AuthController { private final JwtService jwtService; - public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, JwtService jwtService) { + public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, + JwtService jwtService) { this.authenticationManager = authenticationManager; this.jwtService = jwtService; } @@ -27,14 +28,12 @@ public class AuthController { @PostMapping("/discord") public JwtResponse loginDiscord(@Validated @RequestBody Login login) { Authentication authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken(login.redirectUri(), login.code()) - ); + new UsernamePasswordAuthenticationToken(login.redirectUri(), login.code())); UserEntity user = (UserEntity) authentication.getPrincipal(); String jwt = jwtService.buildJwt(user); - return new JwtResponse(jwt); } } diff --git a/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java b/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java index 69b7b24..fd45139 100644 --- a/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java +++ b/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java @@ -8,7 +8,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; - @RestController @RequestMapping("/api/v2") @CrossOrigin(origins = "*", maxAge = 3600) @@ -16,13 +15,10 @@ import org.springframework.web.bind.annotation.RestController; public class CrossOptionController { /** - * For cross preflight request send by axios + * For cross preflight request send by axios */ - @RequestMapping( - value = "/**", - method = RequestMethod.OPTIONS - ) + @RequestMapping(value = "/**", method = RequestMethod.OPTIONS) public ResponseEntity handle() { - return new ResponseEntity<>("",HttpStatus.OK); + return new ResponseEntity<>("", HttpStatus.OK); } } diff --git a/src/main/java/net/Broken/Api/Controllers/GuildController.java b/src/main/java/net/Broken/Api/Controllers/GuildController.java index cf84cc1..9787d12 100644 --- a/src/main/java/net/Broken/Api/Controllers/GuildController.java +++ b/src/main/java/net/Broken/Api/Controllers/GuildController.java @@ -41,21 +41,21 @@ public class GuildController { } @GetMapping("/{guildId}/voiceChannels") - @PreAuthorize("isInGuild(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId)") public List getVoiceChannels(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return guildService.getVoiceChannel(guildId, principal.user().getDiscordId()); } @GetMapping("/{guildId}/textChannels") - @PreAuthorize("isInGuild(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId)") public List getTextChannels(@PathVariable String guildId, Authentication authentication) { JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); return guildService.getTextChannel(guildId, principal.user().getDiscordId()); } @GetMapping("/{guildId}/roles") - @PreAuthorize("isInGuild(#guildId)") + @PreAuthorize("@webSecurity.isInGuild(#guildId)") public List getRoles(@PathVariable String guildId) { return guildService.getRole(guildId); } diff --git a/src/main/java/net/Broken/Api/Controllers/SettingController.java b/src/main/java/net/Broken/Api/Controllers/SettingController.java index 2cbe1f6..a3fb742 100644 --- a/src/main/java/net/Broken/Api/Controllers/SettingController.java +++ b/src/main/java/net/Broken/Api/Controllers/SettingController.java @@ -1,14 +1,21 @@ package net.Broken.Api.Controllers; +import java.util.List; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + import net.Broken.Api.Data.Settings.SettingGroup; import net.Broken.Api.Data.Settings.Value; import net.Broken.Api.Services.SettingService; import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.Tools.Settings.SettingValueBuilder; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import java.util.List; @RestController @RequestMapping("/api/v2/setting") @@ -21,19 +28,19 @@ public class SettingController { } @GetMapping("description") - public List getSettingDescription(){ + public List getSettingDescription() { return settingService.getSettingDescription(); } @GetMapping("/{guildId}/values") - @PreAuthorize("isInGuild(#guildId) && canManageGuild(#guildId)") - public List getSettingValues(@PathVariable String guildId){ + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canManageGuild(#guildId)") + public List getSettingValues(@PathVariable String guildId) { return settingService.getValues(guildId); } @PostMapping("/{guildId}/values") - @PreAuthorize("isInGuild(#guildId) && canManageGuild(#guildId)") - public List getSettingValues(@PathVariable String guildId, @RequestBody List values){ + @PreAuthorize("@webSecurity.isInGuild(#guildId) && @webSecurity.canManageGuild(#guildId)") + public List getSettingValues(@PathVariable String guildId, @RequestBody List values) { GuildPreferenceEntity pref = settingService.saveValue(guildId, values); return new SettingValueBuilder(pref).build(); } diff --git a/src/main/java/net/Broken/Api/Data/Login.java b/src/main/java/net/Broken/Api/Data/Login.java index ffa13f1..7b9c6a1 100644 --- a/src/main/java/net/Broken/Api/Data/Login.java +++ b/src/main/java/net/Broken/Api/Data/Login.java @@ -1,6 +1,6 @@ package net.Broken.Api.Data; -import javax.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotBlank; public record Login( @NotBlank String code, @NotBlank String redirectUri) { diff --git a/src/main/java/net/Broken/Api/Data/Music/PlayBackInfo.java b/src/main/java/net/Broken/Api/Data/Music/PlayBackInfo.java index 67079a0..5c140f4 100644 --- a/src/main/java/net/Broken/Api/Data/Music/PlayBackInfo.java +++ b/src/main/java/net/Broken/Api/Data/Music/PlayBackInfo.java @@ -4,9 +4,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public record PlayBackInfo( - Boolean paused, - Boolean stopped, - Long progress, - TrackInfo trackInfo -) { + Boolean paused, + Boolean stopped, + Long progress, + TrackInfo trackInfo) { } diff --git a/src/main/java/net/Broken/Api/Data/Music/Status.java b/src/main/java/net/Broken/Api/Data/Music/Status.java index 99fafa9..da1625a 100644 --- a/src/main/java/net/Broken/Api/Data/Music/Status.java +++ b/src/main/java/net/Broken/Api/Data/Music/Status.java @@ -6,11 +6,10 @@ import net.dv8tion.jda.api.audio.hooks.ConnectionStatus; @JsonInclude(JsonInclude.Include.NON_NULL) public record Status( - Boolean connected, - ConnectionStatus connectionStatus, - Channel channel, - Boolean canView, - Boolean canInteract, - PlayBackInfo playBackInfo -) { + Boolean connected, + ConnectionStatus connectionStatus, + Channel channel, + Boolean canView, + Boolean canInteract, + PlayBackInfo playBackInfo) { } diff --git a/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java b/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java index 1d99679..749827a 100644 --- a/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java +++ b/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java @@ -7,7 +7,8 @@ import net.Broken.Audio.UserAudioTrack; public record TrackInfo(UserInfo submitter, AudioTrackInfo detail) { public TrackInfo(UserAudioTrack userAudioTrack) { - this(new UserInfo(userAudioTrack.getSubmittedUser().getId(), userAudioTrack.getSubmittedUser().getName(), userAudioTrack.getSubmittedUser().getAvatarUrl()), + this(new UserInfo(userAudioTrack.getSubmittedUser().getId(), userAudioTrack.getSubmittedUser().getName(), + userAudioTrack.getSubmittedUser().getAvatarUrl()), userAudioTrack.getAudioTrack().getInfo()); } } diff --git a/src/main/java/net/Broken/Api/Data/Settings/SettingDescriber.java b/src/main/java/net/Broken/Api/Data/Settings/SettingDescriber.java index 16dc5f8..65cfe70 100644 --- a/src/main/java/net/Broken/Api/Data/Settings/SettingDescriber.java +++ b/src/main/java/net/Broken/Api/Data/Settings/SettingDescriber.java @@ -7,8 +7,7 @@ public record SettingDescriber( String id, String name, String description, - TYPE type -) { + TYPE type) { public enum TYPE { BOOL, LIST, STRING, ROLE, TEXT_CHANNEL, VOICE_CHANNEL diff --git a/src/main/java/net/Broken/Api/Data/Settings/SettingGroup.java b/src/main/java/net/Broken/Api/Data/Settings/SettingGroup.java index a10180a..dd2000f 100644 --- a/src/main/java/net/Broken/Api/Data/Settings/SettingGroup.java +++ b/src/main/java/net/Broken/Api/Data/Settings/SettingGroup.java @@ -6,8 +6,7 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public record SettingGroup( - String name, - SettingDescriber mainField, - List fields -) { + String name, + SettingDescriber mainField, + List fields) { } diff --git a/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java b/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java index 681e437..66277b2 100644 --- a/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java +++ b/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java @@ -28,8 +28,8 @@ public class OpenApiConfig { new SecurityScheme().name(securitySchemeName) .type(SecurityScheme.Type.HTTP) .scheme("bearer") - .bearerFormat("JWT")) - ).addServersItem(new Server().url("/").description("Default")) + .bearerFormat("JWT"))) + .addServersItem(new Server().url("/").description("Default")) .info(new Info().title("ClaptrapBot API").version(versionLoader.getVersion())); } } \ No newline at end of file diff --git a/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java b/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java index 40b7bad..19f9cbc 100644 --- a/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java +++ b/src/main/java/net/Broken/Api/Security/Components/DiscordAuthenticationProvider.java @@ -29,10 +29,12 @@ public class DiscordAuthenticationProvider implements AuthenticationProvider { String token = discordOauthService.getAccessToken(code, redirectUri); DiscordOauthUserInfo discordOauthUserInfo = discordOauthService.getUserInfo(token); discordOauthService.revokeToken(token); - DiscordOauthService.LoginOrRegisterResponse loginOrRegisterResponse = discordOauthService.loginOrRegisterDiscordUser(discordOauthUserInfo); + DiscordOauthService.LoginOrRegisterResponse loginOrRegisterResponse = discordOauthService + .loginOrRegisterDiscordUser(discordOauthUserInfo); UserEntity userEntity = loginOrRegisterResponse.response(); - if(!loginOrRegisterResponse.created()){ - userEntity = discordOauthService.updateUserInfo(discordOauthUserInfo, loginOrRegisterResponse.response()); + if (!loginOrRegisterResponse.created()) { + userEntity = discordOauthService.updateUserInfo(discordOauthUserInfo, + loginOrRegisterResponse.response()); } return new UsernamePasswordAuthenticationToken(userEntity, null, new ArrayList<>()); } catch (OAuthLoginFail e) { diff --git a/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java b/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java index 0cb9d77..c5ea431 100644 --- a/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java +++ b/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java @@ -1,15 +1,17 @@ package net.Broken.Api.Security.Components; import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.MediaType; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -19,7 +21,9 @@ public class UnauthorizedHandler implements AuthenticationEntryPoint { private final Logger logger = LogManager.getLogger(); @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { + public void commence(HttpServletRequest request, + HttpServletResponse response, AuthenticationException authException) + throws IOException, ServletException { logger.error("[API] Unauthorized error: {}", authException.getMessage()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); diff --git a/src/main/java/net/Broken/Api/Security/Data/DiscordOauthUserInfo.java b/src/main/java/net/Broken/Api/Security/Data/DiscordOauthUserInfo.java index b1ffc0c..867ef4c 100644 --- a/src/main/java/net/Broken/Api/Security/Data/DiscordOauthUserInfo.java +++ b/src/main/java/net/Broken/Api/Security/Data/DiscordOauthUserInfo.java @@ -4,9 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public record DiscordOauthUserInfo( - String id, - String username, - String discriminator, - String avatar) { + String id, + String username, + String discriminator, + String avatar) { } - diff --git a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java deleted file mode 100644 index 87edfa8..0000000 --- a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.Broken.Api.Security.Expression; - -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; -import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; -import org.springframework.security.authentication.AuthenticationTrustResolver; -import org.springframework.security.authentication.AuthenticationTrustResolverImpl; -import org.springframework.security.core.Authentication; - -public class CustomMethodSecurityExpressionHandler - extends DefaultMethodSecurityExpressionHandler { - private final AuthenticationTrustResolver trustResolver = - new AuthenticationTrustResolverImpl(); - - @Override - protected MethodSecurityExpressionOperations createSecurityExpressionRoot( - Authentication authentication, MethodInvocation invocation) { - CustomMethodSecurityExpressionRoot root = - new CustomMethodSecurityExpressionRoot(authentication); - root.setPermissionEvaluator(getPermissionEvaluator()); - root.setTrustResolver(this.trustResolver); - root.setRoleHierarchy(getRoleHierarchy()); - return root; - } -} \ No newline at end of file diff --git a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java deleted file mode 100644 index 2bacdf8..0000000 --- a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.Broken.Api.Security.Expression; - -import net.Broken.Api.Data.Music.Connect; -import net.Broken.Api.Security.Data.JwtPrincipal; -import net.Broken.Audio.GuildAudioBotService; -import net.Broken.MainBot; -import net.Broken.Tools.CacheTools; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.VoiceChannel; -import org.springframework.security.access.expression.SecurityExpressionRoot; -import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; -import org.springframework.security.core.Authentication; - -public class CustomMethodSecurityExpressionRoot - extends SecurityExpressionRoot - implements MethodSecurityExpressionOperations { - private Object filterObject; - private Object returnObject; - /** - * Creates a new instance - * - * @param authentication the {@link Authentication} to use. Cannot be null. - */ - public CustomMethodSecurityExpressionRoot(Authentication authentication) { - super(authentication); - } - - public boolean isInGuild(String guildId){ - JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal(); - Guild guild = MainBot.jda.getGuildById(guildId); - return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild); - } - - public boolean canManageGuild(String guildId){ - JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal(); - Member member = MainBot.jda.getGuildById(guildId).getMemberById(jwtPrincipal.user().getDiscordId()); - return member.hasPermission( - Permission.MANAGE_SERVER, - Permission.MANAGE_PERMISSIONS, - Permission.MANAGE_CHANNEL - ); - } - - public boolean canInteractWithVoiceChannel(String guildId, Connect connectPayload){ - JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal(); - Guild guild = MainBot.jda.getGuildById(guildId); - Member member = guild.getMemberById(jwtPrincipal.user().getDiscordId()); - VoiceChannel channel = guild.getVoiceChannelById(connectPayload.channelId()); - if( channel == null){ - return false; - } - - return (member.hasPermission(channel, Permission.VOICE_CONNECT) - || member.getVoiceState() != null - && member.getVoiceState().getChannel() == channel) - && member.hasPermission(channel, Permission.VOICE_SPEAK); - } - - public boolean canInteractWithVoiceChannel(String guildId) { - JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal(); - Guild guild = MainBot.jda.getGuildById(guildId); - GuildAudioBotService guildAudioBotService = GuildAudioBotService.getInstance(guild); - VoiceChannel channel = guild.getAudioManager().getConnectedChannel(); - - if (channel == null) { - return false; - } - - Member member = guild.getMemberById(jwtPrincipal.user().getDiscordId()); - return (member.hasPermission(channel, Permission.VOICE_CONNECT) - || member.getVoiceState() != null - && member.getVoiceState().getChannel() == channel) - && member.hasPermission(channel, Permission.VOICE_SPEAK); - } - - @Override - public void setFilterObject(Object filterObject) { - this.filterObject = filterObject; - } - - @Override - public Object getFilterObject() { - return this.filterObject; - } - - @Override - public void setReturnObject(Object returnObject) { - this.returnObject = returnObject; - } - - @Override - public Object getReturnObject() { - return this.returnObject; - } - - @Override - public Object getThis() { - return this; - } -} diff --git a/src/main/java/net/Broken/Api/Security/Expression/WebSecurity.java b/src/main/java/net/Broken/Api/Security/Expression/WebSecurity.java new file mode 100644 index 0000000..bea72af --- /dev/null +++ b/src/main/java/net/Broken/Api/Security/Expression/WebSecurity.java @@ -0,0 +1,69 @@ +package net.Broken.Api.Security.Expression; + +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +import net.Broken.MainBot; +import net.Broken.Api.Data.Music.Connect; +import net.Broken.Api.Security.Data.JwtPrincipal; +import net.Broken.Tools.CacheTools; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; +import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion; + +@Service +public class WebSecurity { + public boolean isInGuild(String guildId) { + + JwtPrincipal jwtPrincipal = (JwtPrincipal) SecurityContextHolder.getContext().getAuthentication() + .getPrincipal(); + Guild guild = MainBot.jda.getGuildById(guildId); + return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild); + } + + public boolean canManageGuild(String guildId) { + JwtPrincipal jwtPrincipal = (JwtPrincipal) SecurityContextHolder.getContext().getAuthentication() + .getPrincipal(); + Member member = MainBot.jda.getGuildById(guildId).getMemberById(jwtPrincipal.user().getDiscordId()); + return member.hasPermission( + Permission.MANAGE_SERVER, + Permission.MANAGE_PERMISSIONS, + Permission.MANAGE_CHANNEL); + } + + public boolean canInteractWithVoiceChannel(String guildId, Connect connectPayload) { + JwtPrincipal jwtPrincipal = (JwtPrincipal) SecurityContextHolder.getContext().getAuthentication() + .getPrincipal(); + Guild guild = MainBot.jda.getGuildById(guildId); + Member member = guild.getMemberById(jwtPrincipal.user().getDiscordId()); + VoiceChannel channel = guild.getVoiceChannelById(connectPayload.channelId()); + if (channel == null) { + return false; + } + + return (member.hasPermission(channel, Permission.VOICE_CONNECT) + || member.getVoiceState() != null + && member.getVoiceState().getChannel() == channel) + && member.hasPermission(channel, Permission.VOICE_SPEAK); + } + + public boolean canInteractWithVoiceChannel(String guildId) { + JwtPrincipal jwtPrincipal = (JwtPrincipal) SecurityContextHolder.getContext().getAuthentication() + .getPrincipal(); + Guild guild = MainBot.jda.getGuildById(guildId); + AudioChannelUnion channel = guild.getAudioManager().getConnectedChannel(); + + if (channel == null) { + return false; + } + + Member member = guild.getMemberById(jwtPrincipal.user().getDiscordId()); + return (member.hasPermission(channel, Permission.VOICE_CONNECT) + || member.getVoiceState() != null + && member.getVoiceState().getChannel() == channel) + && member.hasPermission(channel, Permission.VOICE_SPEAK); + } + +} diff --git a/src/main/java/net/Broken/Api/Security/Filters/JwtFilter.java b/src/main/java/net/Broken/Api/Security/Filters/JwtFilter.java index 771cadd..43e931b 100644 --- a/src/main/java/net/Broken/Api/Security/Filters/JwtFilter.java +++ b/src/main/java/net/Broken/Api/Security/Filters/JwtFilter.java @@ -2,6 +2,10 @@ package net.Broken.Api.Security.Filters; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Security.Services.JwtService; import net.Broken.BotConfigLoader; @@ -15,10 +19,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; @@ -32,23 +32,24 @@ public class JwtFilter extends OncePerRequestFilter { private final Logger logger = LogManager.getLogger(); @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { String authHeader = request.getHeader("Authorization"); if (authHeader != null && authHeader.startsWith("Bearer ")) { String token = authHeader.replace("Bearer ", ""); try { UserEntity user; JwtPrincipal principal; - if(config.mode().equals("DEV")){ + if (config.mode().equals("DEV")) { user = userRepository.findByDiscordId(token).orElseThrow(); principal = new JwtPrincipal("DEV", user); - } - else { + } else { Jws jwt = jwtService.verifyAndParseJwt(token); user = jwtService.getUserWithJwt(jwt); - principal = new JwtPrincipal(jwt.getBody().getId(), user); + principal = new JwtPrincipal(jwt.getPayload().getId(), user); } - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, null, new ArrayList<>()); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + principal, null, new ArrayList<>()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } catch (Exception e) { diff --git a/src/main/java/net/Broken/Api/Security/MethodSecurityConfig.java b/src/main/java/net/Broken/Api/Security/MethodSecurityConfig.java deleted file mode 100644 index 129bfc4..0000000 --- a/src/main/java/net/Broken/Api/Security/MethodSecurityConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.Broken.Api.Security; - -import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionHandler; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - return new CustomMethodSecurityExpressionHandler(); - } -} diff --git a/src/main/java/net/Broken/Api/Security/SecurityConfig.java b/src/main/java/net/Broken/Api/Security/SecurityConfig.java index b2c0448..055259b 100644 --- a/src/main/java/net/Broken/Api/Security/SecurityConfig.java +++ b/src/main/java/net/Broken/Api/Security/SecurityConfig.java @@ -1,51 +1,57 @@ package net.Broken.Api.Security; -import net.Broken.Api.Security.Components.UnauthorizedHandler; -import net.Broken.Api.Security.Filters.JwtFilter; +import static org.springframework.security.config.Customizer.withDefaults; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import net.Broken.Api.Security.Components.UnauthorizedHandler; +import net.Broken.Api.Security.Filters.JwtFilter; + @EnableWebSecurity +@EnableMethodSecurity @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { private final UnauthorizedHandler unauthorizedHandler; + public SecurityConfig(UnauthorizedHandler unauthorizedHandler) { this.unauthorizedHandler = unauthorizedHandler; } - @Override - protected void configure(HttpSecurity http) throws Exception { - http.cors().and().csrf().disable() - .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() - .authorizeRequests() - .antMatchers("/api/v2/auth/**").permitAll() - .antMatchers("/api/v2/guild/inviteLink").permitAll() - .antMatchers("/swagger-ui/**").permitAll() - .antMatchers("/swagger-ui.html").permitAll() - .antMatchers("/v3/api-docs/**").permitAll() - .antMatchers("/actuator/**").permitAll() - .anyRequest().authenticated(); + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.cors(withDefaults()).csrf(csrf -> csrf.disable()) + .exceptionHandling(handling -> handling.authenticationEntryPoint(unauthorizedHandler)) + .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(requests -> requests + .requestMatchers("/api/v2/auth/**").permitAll() + .requestMatchers("/api/v2/guild/inviteLink").permitAll() + .requestMatchers("/swagger-ui/**").permitAll() + .requestMatchers("/swagger-ui.html").permitAll() + .requestMatchers("/v3/api-docs/**").permitAll() + .requestMatchers("/actuator/**").permitAll() + .anyRequest().authenticated()); http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); - + return http.build(); } @Bean - public JwtFilter jwtFilter(){ + public JwtFilter jwtFilter() { return new JwtFilter(); } - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); + public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { + return http.getSharedObject(AuthenticationManagerBuilder.class) + .build(); } } diff --git a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java index 5676833..139df42 100644 --- a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java +++ b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java @@ -58,11 +58,13 @@ public class DiscordOauthService { try { HttpResponse response = makeFormPost(this.tokenEndpoint, data); if (response.statusCode() != 200) { - logger.warn("[OAUTH] Invalid response while getting AccessToken: Status Code: " + response.statusCode() + " Body:" + response.body()); + logger.warn("[OAUTH] Invalid response while getting AccessToken: Status Code: " + response.statusCode() + + " Body:" + response.body()); throw new OAuthLoginFail(); } ObjectMapper objectMapper = new ObjectMapper(); - AccessTokenResponse accessTokenResponse = objectMapper.readValue(response.body(), AccessTokenResponse.class); + AccessTokenResponse accessTokenResponse = objectMapper.readValue(response.body(), + AccessTokenResponse.class); return accessTokenResponse.access_token(); } catch (IOException | InterruptedException e) { logger.catching(e); @@ -81,7 +83,8 @@ public class DiscordOauthService { HttpClient client = HttpClient.newHttpClient(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { - logger.warn("[OAUTH] Invalid response while getting UserInfo: Status Code: " + response.statusCode() + " Body:" + response.body()); + logger.warn("[OAUTH] Invalid response while getting UserInfo: Status Code: " + response.statusCode() + + " Body:" + response.body()); throw new OAuthLoginFail(); } ObjectMapper mapper = new ObjectMapper(); @@ -99,49 +102,49 @@ public class DiscordOauthService { try { HttpResponse response = makeFormPost(this.tokenRevokeEndpoint, data); if (response.statusCode() != 200) { - logger.warn("[OAUTH] Invalid response while token revocation: Status Code: " + response.statusCode() + " Body:" + response.body()); + logger.warn("[OAUTH] Invalid response while token revocation: Status Code: " + response.statusCode() + + " Body:" + response.body()); } } catch (IOException | InterruptedException e) { logger.catching(e); } } - public record LoginOrRegisterResponse(T response, boolean created) { } public LoginOrRegisterResponse loginOrRegisterDiscordUser(DiscordOauthUserInfo discordOauthUserInfo) { Optional optionalUserEntity = userRepository.findByDiscordId(discordOauthUserInfo.id()); return optionalUserEntity.map( - userEntity -> new LoginOrRegisterResponse<>(userEntity, false)) + userEntity -> new LoginOrRegisterResponse<>(userEntity, false)) .orElseGet(() -> { UserEntity created = userRepository.save(new UserEntity(discordOauthUserInfo)); return new LoginOrRegisterResponse<>(created, true); }); } - public UserEntity updateUserInfo(DiscordOauthUserInfo discordOauthUserInfo, UserEntity userEntity){ + public UserEntity updateUserInfo(DiscordOauthUserInfo discordOauthUserInfo, UserEntity userEntity) { boolean updated = false; - if(userEntity.getUsername() == null || !userEntity.getUsername().equals(discordOauthUserInfo.username())){ + if (userEntity.getUsername() == null || !userEntity.getUsername().equals(discordOauthUserInfo.username())) { userEntity.setUsername(discordOauthUserInfo.username()); updated = true; } - if(userEntity.getDiscriminator() == null || !userEntity.getDiscriminator().equals(discordOauthUserInfo.discriminator())){ + if (userEntity.getDiscriminator() == null + || !userEntity.getDiscriminator().equals(discordOauthUserInfo.discriminator())) { userEntity.setDiscriminator(discordOauthUserInfo.discriminator()); updated = true; } - if(userEntity.getAvatar() == null || !userEntity.getAvatar().equals(discordOauthUserInfo.avatar())){ + if (userEntity.getAvatar() == null || !userEntity.getAvatar().equals(discordOauthUserInfo.avatar())) { userEntity.setAvatar(discordOauthUserInfo.avatar()); updated = true; } - if(updated){ + if (updated) { return userRepository.save(userEntity); } return userEntity; } - private String getFormString(HashMap params) { StringBuilder result = new StringBuilder(); boolean first = true; @@ -157,7 +160,8 @@ public class DiscordOauthService { return result.toString(); } - private HttpResponse makeFormPost(String endpoint, HashMap data) throws IOException, InterruptedException { + private HttpResponse makeFormPost(String endpoint, HashMap data) + throws IOException, InterruptedException { HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(getFormString(data)); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(tokenEndpoint)) @@ -168,5 +172,4 @@ public class DiscordOauthService { return client.send(request, HttpResponse.BodyHandlers.ofString()); } - } diff --git a/src/main/java/net/Broken/Api/Security/Services/JwtService.java b/src/main/java/net/Broken/Api/Security/Services/JwtService.java index 1e4df47..8ae26c8 100644 --- a/src/main/java/net/Broken/Api/Security/Services/JwtService.java +++ b/src/main/java/net/Broken/Api/Security/Services/JwtService.java @@ -1,34 +1,33 @@ package net.Broken.Api.Security.Services; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.security.Keys; -import net.Broken.DB.Entity.UserEntity; -import net.Broken.DB.Repository.UserRepository; -import org.springframework.stereotype.Service; - -import java.security.Key; import java.util.Calendar; import java.util.Date; import java.util.NoSuchElementException; import java.util.UUID; +import javax.crypto.SecretKey; + +import org.springframework.stereotype.Service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import net.Broken.DB.Entity.UserEntity; +import net.Broken.DB.Repository.UserRepository; + @Service public class JwtService { - private final Key jwtKey; + private final SecretKey jwtKey; private final UserRepository userRepository; public JwtService(UserRepository userRepository) { this.userRepository = userRepository; - this.jwtKey = Keys.secretKeyFor(SignatureAlgorithm.HS256); + this.jwtKey = Jwts.SIG.HS256.key().build(); } - public String buildJwt(UserEntity user){ + public String buildJwt(UserEntity user) { Date iat = new Date(); Date nbf = new Date(); Calendar expCal = Calendar.getInstance(); @@ -36,33 +35,29 @@ public class JwtService { Date exp = expCal.getTime(); UUID uuid = UUID.randomUUID(); - return Jwts.builder() - .setSubject(user.getUsername()) + .subject(user.getUsername()) .claim("discord_id", user.getDiscordId()) .claim("avatar", user.getAvatar()) .claim("discriminator", user.getDiscriminator()) - .setId(uuid.toString()) - .setIssuedAt(iat) - .setNotBefore(nbf) - .setExpiration(exp) + .id(uuid.toString()) + .issuedAt(iat) + .notBefore(nbf) + .expiration(exp) .signWith(this.jwtKey) .compact(); - } - public Jws verifyAndParseJwt(String token) { - return Jwts.parserBuilder() - .setSigningKey(this.jwtKey) + return Jwts.parser() + .verifyWith(this.jwtKey) .build() - .parseClaimsJws(token); + .parseSignedClaims(token); } - public UserEntity getUserWithJwt(Jws jwt) throws NoSuchElementException { - String discordId = jwt.getBody().get("discord_id", String.class); + String discordId = jwt.getPayload().get("discord_id", String.class); return userRepository.findByDiscordId(discordId) .orElseThrow(); } diff --git a/src/main/java/net/Broken/Api/Services/AudioService.java b/src/main/java/net/Broken/Api/Services/AudioService.java index e3a5708..f182d68 100644 --- a/src/main/java/net/Broken/Api/Services/AudioService.java +++ b/src/main/java/net/Broken/Api/Services/AudioService.java @@ -9,7 +9,9 @@ import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audio.hooks.ConnectionStatus; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.VoiceChannel; +import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; +import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.HttpStatus; @@ -27,35 +29,35 @@ public class AudioService { Guild guild = MainBot.jda.getGuildById(guildId); Member member = guild.getMemberById(userId); - - VoiceChannel channel = guild.getAudioManager().getConnectedChannel(); + AudioChannelUnion channel = guild.getAudioManager().getConnectedChannel(); ConnectionStatus status = guild.getAudioManager().getConnectionStatus(); if (channel != null) { -// The user can view the audio status if: -// -> He can view the voice channel -// -> OR He can *not* view the voice channel, but he is connected to this voice channel + // The user can view the audio status if: + // -> He can view the voice channel + // -> OR He can *not* view the voice channel, but he is connected to this voice + // channel boolean canView = member.hasPermission(channel, Permission.VIEW_CHANNEL) || (member.getVoiceState() != null - && member.getVoiceState().getChannel() == channel); + && member.getVoiceState().getChannel() == channel); GuildAudioBotService guildAudioBotService = GuildAudioBotService.getInstance(guild); if (canView) { -// The user can interact with the audio if: -// -> He can connect to this voice channel -// -> OR he is connected to this voice channel -// -> AND He can speak in this voice channel + // The user can interact with the audio if: + // -> He can connect to this voice channel + // -> OR he is connected to this voice channel + // -> AND He can speak in this voice channel boolean canInteract = (member.hasPermission(channel, Permission.VOICE_CONNECT) || member.getVoiceState() != null - && member.getVoiceState().getChannel() == channel) + && member.getVoiceState().getChannel() == channel) && member.hasPermission(channel, Permission.VOICE_SPEAK); - boolean stopped = guildAudioBotService.getGuidAudioManager().player.getPlayingTrack() == null; PlayBackInfo playBackInfo; if (!stopped) { boolean paused = guildAudioBotService.getGuidAudioManager().player.isPaused(); long position = guildAudioBotService.getGuidAudioManager().player.getPlayingTrack().getPosition(); - UserAudioTrack userAudioTrack = guildAudioBotService.getGuidAudioManager().scheduler.getCurrentPlayingTrack(); + UserAudioTrack userAudioTrack = guildAudioBotService.getGuidAudioManager().scheduler + .getCurrentPlayingTrack(); playBackInfo = new PlayBackInfo(paused, false, position, new TrackInfo(userAudioTrack)); @@ -88,7 +90,6 @@ public class AudioService { return new ResponseEntity<>(status, HttpStatus.OK); } - public ResponseEntity pause(String guildId, String userId) { Guild guild = MainBot.jda.getGuildById(guildId); GuildAudioBotService.getInstance(guild).pause(); @@ -117,7 +118,8 @@ public class AudioService { return new ResponseEntity<>(status, HttpStatus.OK); } - public ResponseEntity add(String guildId, String userId, Add body) throws ExecutionException, InterruptedException { + public ResponseEntity add(String guildId, String userId, Add body) + throws ExecutionException, InterruptedException { Guild guild = MainBot.jda.getGuildById(guildId); boolean success = GuildAudioBotService.getInstance(guild).loadAndPlaySync(body.url(), userId); if (success) { diff --git a/src/main/java/net/Broken/Api/Services/GuildService.java b/src/main/java/net/Broken/Api/Services/GuildService.java index 867c086..3335f45 100644 --- a/src/main/java/net/Broken/Api/Services/GuildService.java +++ b/src/main/java/net/Broken/Api/Services/GuildService.java @@ -8,6 +8,9 @@ import net.Broken.MainBot; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; + import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -24,8 +27,7 @@ public class GuildService { boolean canManage = guild.getMember(discordUser).hasPermission( Permission.MANAGE_SERVER, Permission.MANAGE_PERMISSIONS, - Permission.MANAGE_CHANNEL - ); + Permission.MANAGE_CHANNEL); guildList.add(new Guild(guild.getId(), guild.getName(), guild.getIconUrl(), canManage)); } return guildList; @@ -35,7 +37,7 @@ public class GuildService { net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); Member member = guild.getMemberById(userId); List voiceChannels = new ArrayList<>(); - for (net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()) { + for (VoiceChannel voiceChannel : guild.getVoiceChannels()) { if (member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)) { voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); } @@ -47,7 +49,7 @@ public class GuildService { net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); Member member = guild.getMemberById(userId); List voiceChannels = new ArrayList<>(); - for (net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()) { + for (TextChannel textChannel : guild.getTextChannels()) { if (member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) { voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); } @@ -66,9 +68,9 @@ public class GuildService { return roles; } - - public String getInviteLink(){ - return MainBot.jda.setRequiredScopes("applications.commands").getInviteUrl(Permission.getPermissions(1644971949399L)); + public String getInviteLink() { + return MainBot.jda.setRequiredScopes("applications.commands") + .getInviteUrl(Permission.getPermissions(1644971949399L)); } } diff --git a/src/main/java/net/Broken/Api/Services/SettingService.java b/src/main/java/net/Broken/Api/Services/SettingService.java index 827597e..cafbafa 100644 --- a/src/main/java/net/Broken/Api/Services/SettingService.java +++ b/src/main/java/net/Broken/Api/Services/SettingService.java @@ -19,7 +19,6 @@ public class SettingService { public final GuildPreferenceRepository preferenceRepository; private final Logger logger = LogManager.getLogger(); - public SettingService(GuildPreferenceRepository preferenceRepository) { this.preferenceRepository = preferenceRepository; } @@ -28,7 +27,6 @@ public class SettingService { return new SettingDescriptionBuilder().build(); } - public List getValues(String guildId) { GuildPreferenceEntity pref = preferenceRepository.findByGuildId(guildId).orElseGet(() -> { logger.info("[API] : Generate default guild pref"); @@ -37,7 +35,7 @@ public class SettingService { return new SettingValueBuilder(pref).build(); } - public GuildPreferenceEntity saveValue(String guildId, List values){ + public GuildPreferenceEntity saveValue(String guildId, List values) { GuildPreferenceEntity pref = preferenceRepository.findByGuildId(guildId).orElseGet(() -> { logger.info("[API] : Generate default guild pref"); return preferenceRepository.save(GuildPreferenceEntity.getDefault(guildId)); diff --git a/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java b/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java index 665d3aa..ef30ea5 100644 --- a/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java +++ b/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java @@ -1,14 +1,17 @@ package net.Broken.Audio; -import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; -import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame; -import net.dv8tion.jda.api.audio.AudioSendHandler; - import java.nio.ByteBuffer; +import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; +import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame; + +import net.dv8tion.jda.api.audio.AudioSendHandler; + /** - * This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide - * before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in + * This is a wrapper around AudioPlayer which makes it behave as an + * AudioSendHandler for JDA. As JDA calls canProvide + * before every call to provide20MsAudio(), we pull the frame in canProvide() + * and use the frame we already pulled in * provide20MsAudio(). */ public class AudioPlayerSendHandler implements AudioSendHandler { diff --git a/src/main/java/net/Broken/Audio/GuildAudioBotService.java b/src/main/java/net/Broken/Audio/GuildAudioBotService.java index b9cbbd4..0a88ad4 100644 --- a/src/main/java/net/Broken/Audio/GuildAudioBotService.java +++ b/src/main/java/net/Broken/Audio/GuildAudioBotService.java @@ -24,17 +24,19 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import net.Broken.Tools.EmbedMessageUtils; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.MessageBuilder; -import net.dv8tion.jda.api.entities.Emoji; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.entities.VoiceChannel; -import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; -import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel; +import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion; +import net.dv8tion.jda.api.entities.emoji.Emoji; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.components.ActionRow; -import net.dv8tion.jda.api.interactions.components.Button; +import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; +import net.dv8tion.jda.api.utils.messages.MessageCreateData; public class GuildAudioBotService { @@ -47,7 +49,7 @@ public class GuildAudioBotService { /** * Extrem limit for playlist */ - private final int listExtremLimit = 300; + private static final int LIST_EXTREM_LIMIT = 300; private final Guild guild; private final Logger logger = LogManager.getLogger(); @@ -66,9 +68,7 @@ public class GuildAudioBotService { } public static GuildAudioBotService getInstance(Guild guild) { - if (!INSTANCES.containsKey(guild)) { - INSTANCES.put(guild, new GuildAudioBotService(guild)); - } + INSTANCES.computeIfAbsent(guild, k -> new GuildAudioBotService(guild)); return INSTANCES.get(guild); } @@ -80,13 +80,14 @@ public class GuildAudioBotService { * @param playlistLimit Limit of playlist * @param onHead True for adding audio track on top of playlist */ - public void loadAndPlay(SlashCommandEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) { + public void loadAndPlay(SlashCommandInteractionEvent event, AudioChannel voiceChannel, final String trackUrl, + int playlistLimit, boolean onHead) { audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() { @Override public void trackLoaded(AudioTrack track) { - logger.info("[" + guild + "] Single Track detected!"); + logger.info("[{}] Single Track detected!", guild.getName()); UserAudioTrack uat = new UserAudioTrack(event.getUser(), track); - Message message = new MessageBuilder() + MessageCreateData message = new MessageCreateBuilder() .setEmbeds(EmbedMessageUtils.getMusicAdded(track.getInfo(), event.getMember(), -1)) .build(); clearLastButton(); @@ -96,10 +97,10 @@ public class GuildAudioBotService { @Override public void playlistLoaded(AudioPlaylist playlist) { - logger.info("[" + guild + "] Playlist detected! Limit: " + playlistLimit); + logger.info("[{}] Playlist detected! Limit: {}", guild, playlistLimit); AudioTrack firstTrack = playlist.getSelectedTrack(); int size = Math.min(playlist.getTracks().size(), playlistLimit); - Message message = new MessageBuilder() + MessageCreateData message = new MessageCreateBuilder() .setEmbeds(EmbedMessageUtils.getMusicAdded(firstTrack.getInfo(), event.getMember(), size)) .build(); clearLastButton(); @@ -109,16 +110,18 @@ public class GuildAudioBotService { @Override public void noMatches() { - logger.warn("[" + guild + "] Cant find media!"); - Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build(); + logger.warn("[{}] Cant find media!", guild); + MessageCreateData message = new MessageCreateBuilder() + .setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build(); event.getHook().setEphemeral(true).sendMessage(message).queue(); } @Override public void loadFailed(FriendlyException exception) { - logger.error("[" + guild + "] Can't load media!"); + logger.error("[{}] Can't load media!", guild); logger.error(exception.getMessage()); - Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build(); + MessageCreateData message = new MessageCreateBuilder() + .setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build(); event.getHook().setEphemeral(true).sendMessage(message).queue(); } }); @@ -126,44 +129,44 @@ public class GuildAudioBotService { public boolean loadAndPlaySync(String trackUrl, String userId) throws ExecutionException, InterruptedException { Member member = guild.getMemberById(userId); - VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel(); + AudioChannelUnion playedChanel = guild.getAudioManager().getConnectedChannel(); final String uuid = UUID.randomUUID().toString(); - Future future = audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() { - @Override - public void trackLoaded(AudioTrack track) { - logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist."); - UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); - play(guild, playedChanel, guildAudioManager, userAudioTrack, true); - addStatus.put(uuid, true); - } + Future future = audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, + new AudioLoadResultHandler() { + @Override + public void trackLoaded(AudioTrack track) { + logger.info("[{}] Auto add {} to playlist.", guild, track.getInfo().title); + UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); + play(guild, playedChanel, guildAudioManager, userAudioTrack, true); + addStatus.put(uuid, true); + } - @Override - public void playlistLoaded(AudioPlaylist playlist) { - AudioTrack track = playlist.getTracks().get(0); - logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist."); - UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); - play(guild, playedChanel, guildAudioManager, userAudioTrack, true); - addStatus.put(uuid, true); - } + @Override + public void playlistLoaded(AudioPlaylist playlist) { + AudioTrack track = playlist.getTracks().get(0); + logger.info("[{}] Auto add {} to playlist.", guild, track.getInfo().title); + UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); + play(guild, playedChanel, guildAudioManager, userAudioTrack, true); + addStatus.put(uuid, true); + } - @Override - public void noMatches() { - logger.warn("[" + guild + "] Track not found: " + trackUrl); - addStatus.put(uuid, false); - } + @Override + public void noMatches() { + logger.warn("[{}] Track not found: {}", guild, trackUrl); + addStatus.put(uuid, false); + } - @Override - public void loadFailed(FriendlyException exception) { - logger.error("[" + guild + "] Cant load media!"); - logger.error(exception.getMessage()); - addStatus.put(uuid, false); - } - }); + @Override + public void loadFailed(FriendlyException exception) { + logger.error("[{}] Cant load media!", guild); + logger.error(exception.getMessage()); + addStatus.put(uuid, false); + } + }); future.get(); return addStatus.remove(uuid); } - /** * Load playlist to playlist * @@ -174,7 +177,7 @@ public class GuildAudioBotService { */ public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead) { - VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel(); + AudioChannelUnion playedChanel = guild.getAudioManager().getConnectedChannel(); List tracks = playlist.getTracks(); if (onHead) Collections.reverse(tracks); @@ -183,13 +186,12 @@ public class GuildAudioBotService { for (AudioTrack track : playlist.getTracks()) { UserAudioTrack uat = new UserAudioTrack(user, track); play(guild, playedChanel, guildAudioManager, uat, onHead); - if ((playlistLimit != -1 && i >= playlistLimit) || i > listExtremLimit) + if ((playlistLimit != -1 && i >= playlistLimit) || i > LIST_EXTREM_LIMIT) break; i++; } } - /** * Add single track to playlist, auto-connect if not connected to vocal chanel * @@ -199,7 +201,8 @@ public class GuildAudioBotService { * @param track Track to add to playlist * @param onHead True for adding audio track on top of playlist */ - public void play(Guild guild, VoiceChannel channel, GuildAudioManager musicManager, UserAudioTrack track, boolean onHead) { + public void play(Guild guild, AudioChannel channel, GuildAudioManager musicManager, UserAudioTrack track, + boolean onHead) { if (!guild.getAudioManager().isConnected()) guild.getAudioManager().openAudioConnection(channel); if (!onHead) @@ -208,87 +211,88 @@ public class GuildAudioBotService { musicManager.scheduler.addNext(track); } - public void add(SlashCommandEvent event, String url, int playListLimit, boolean onHead) { + public void add(SlashCommandInteractionEvent event, String url, int playListLimit, boolean onHead) { if (guild.getAudioManager().isConnected()) { loadAndPlay(event, guild.getAudioManager().getConnectedChannel(), url, playListLimit, onHead); } else { - Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build(); + MessageCreateData message = new MessageCreateBuilder() + .setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build(); event.getHook().setEphemeral(true).sendMessage(message).queue(); } } - public void connect(VoiceChannel voiceChannel) { + public void connect(AudioChannel voiceChannel) { guild.getAudioManager().openAudioConnection(voiceChannel); } - public void pause(GenericInteractionCreateEvent event) { + public void pause(InteractionHook hook) { pause(); - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":pause_button: Playback paused") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } public void pause() { guildAudioManager.scheduler.pause(); } - public void resume(GenericInteractionCreateEvent event) { - Message message; + public void resume(InteractionHook hook) { + MessageCreateData message; if (guildAudioManager.player.getPlayingTrack() == null) { - message = new MessageBuilder().setEmbeds( + message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":warning: Nothing to play, playlist is empty !") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); } else { resume(); - message = new MessageBuilder().setEmbeds( + message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":arrow_forward: Playback resumed") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); } clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } public void resume() { guildAudioManager.scheduler.resume(); } - public void skipTrack(GenericInteractionCreateEvent event) { + public void skipTrack(InteractionHook hook) { skipTrack(); - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":track_next: Next Track") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } public void skipTrack() { guildAudioManager.scheduler.nextTrack(); } - public void stop(GenericInteractionCreateEvent event) { + public void stop(InteractionHook hook) { stop(); - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":stop_button: Playback stopped") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } @@ -298,16 +302,16 @@ public class GuildAudioBotService { clearLastButton(); } - public void disconnect(GenericInteractionCreateEvent event) { + public void disconnect(InteractionHook hook) { disconnect(); - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":eject: Disconnected") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); clearLastButton(); - event.getHook().sendMessage(message).queue(); + hook.sendMessage(message).queue(); } public void disconnect() { @@ -316,24 +320,26 @@ public class GuildAudioBotService { guild.getAudioManager().closeAudioConnection(); clearLastButton(); } - public void info(GenericInteractionCreateEvent event) { + + public void info(InteractionHook hook) { AudioTrackInfo info = guildAudioManager.scheduler.getInfo(); UserAudioTrack userAudioTrack = guildAudioManager.scheduler.getCurrentPlayingTrack(); - Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicInfo(info, userAudioTrack)).build(); + MessageCreateData message = new MessageCreateBuilder() + .setEmbeds(EmbedMessageUtils.getMusicInfo(info, userAudioTrack)).build(); clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } - public void flush(GenericInteractionCreateEvent event) { + public void flush(InteractionHook hook) { guildAudioManager.scheduler.flush(); - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":wastebasket: Playlist flushed") - .setColor(Color.green) - )).build(); + .setColor(Color.green))) + .build(); clearLastButton(); - lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); + lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete(); } /** @@ -341,18 +347,18 @@ public class GuildAudioBotService { * * @param event */ - public void list(GenericInteractionCreateEvent event) { + public void list(InteractionHook hook) { List list = guildAudioManager.scheduler.getList(); - if (list.size() == 0) { - Message message = new MessageBuilder().setEmbeds( + if (list.isEmpty()) { + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":scroll: Playlist") .setColor(Color.green) - .setDescription("Oh no ! The playlist is empty !") - )).build(); - event.getHook().sendMessage(message).queue(); + .setDescription("Oh no ! The playlist is empty !"))) + .build(); + hook.sendMessage(message).queue(); } else { StringBuilder resp = new StringBuilder(); int i = 0; @@ -370,14 +376,14 @@ public class GuildAudioBotService { } i++; } - Message message = new MessageBuilder().setEmbeds( + MessageCreateData message = new MessageCreateBuilder().setEmbeds( EmbedMessageUtils.buildStandar( new EmbedBuilder() .setTitle(":scroll: Playlist") .setColor(Color.green) - .setDescription(resp.toString()) - )).build(); - event.getHook().sendMessage(message).queue(); + .setDescription(resp.toString()))) + .build(); + hook.sendMessage(message).queue(); } } @@ -390,7 +396,6 @@ public class GuildAudioBotService { return guildAudioManager; } - public void clearLastButton() { if (lastMessageWithButton != null) { this.lastMessageWithButton.editMessageComponents(new ArrayList<>()).queue(); @@ -401,10 +406,10 @@ public class GuildAudioBotService { public void updateLastButton() { if (lastMessageWithButton != null) - lastMessageWithButton = lastMessageWithButton.editMessageComponents(ActionRow.of(getActionButton())).complete(); + lastMessageWithButton = lastMessageWithButton.editMessageComponents(ActionRow.of(getActionButton())) + .complete(); } - private List