Compare commits

..
10 Commits
Author SHA1 Message Date
stijn d7dadc6b6d Update velocity version 2025-06-28 04:40:27 +02:00
auto e8e3293416 Update Jenkinsfile to include Nexus credentials for Gradle build
Integrated `NEXUS_CREDS` environment variable for secure handling of Nexus credentials during the Gradle shadowJar task.
2025-06-21 00:59:42 +02:00
auto 34b8824d49 Update build files and listener behavior
Set project version to 1.0.1-SNAPSHOT, updated Maven repository URLs, and adjusted credentials handling for Nexus. Refactored dependency configurations and modified LiteBansBanListener to update the embed title from "Auto Discord ban" to "Evidence".
2025-03-22 18:53:05 +01:00
auto 8ddbfcd521 Add DiscordJoinListener to handle member join events
Introduced `DiscordJoinListener` to manage actions when a Discord user joins the server, ensuring linked players are assigned appropriate roles. Integrated the listener into the bot's event handlers in `Bot.java`. This enhances the user experience by maintaining role synchronization.
2025-01-24 20:28:02 +01:00
auto 7083235d68 Refactor account linking to use InteractionHook
Updated the account linking process to use `InteractionHook` for improved response handling and consistency. Replaced direct event replies with deferred interactions and streamlined role management and error messages. This ensures better compatibility with asynchronous operations and cleaner user feedback.
2025-01-24 20:23:08 +01:00
auto baf88ed43e Refactor logging and enhance bot features
Introduced detailed logging throughout the bot for better debugging and monitoring. Improved evidence folder handling in the ban listener and added error resilience. Added a new AnnouncementListener and implemented changes for command manager initialization. Disabled some obsolete or unused functionalities pending further review.
2025-01-17 20:09:16 +01:00
auto b54b3f9eaf Rename shadowJar output file to ProxyDiscordLink.jar
Updated the shadowJar configuration to output the JAR file as ProxyDiscordLink.jar instead of discordLink.jar. This change clarifies the file's purpose and aligns with naming conventions.
2025-01-03 23:53:10 +01:00
auto 40ded90edf Refactor folder handling and enhance ban duration reporting
Improved Nextcloud folder handling by checking for folder existence before creation, ensuring efficient operations. Updated LiteBansBanListener to include ban durations in Discord messages, adding clarity for temporary bans. Enhanced unit test structure for Evidence with simplified assertions.
2025-01-03 23:49:14 +01:00
Len 19e0760aa2 Update gradle shadow plugin to gradleup shadow plugin. 2025-01-03 16:42:44 +01:00
auto 35f34b2b71 Add evidence folder integration with Nextcloud support
Implemented an "Evidence" utility to manage evidence folders in Nextcloud and updated related classes to include evidence links in Discord ban messages. Refactored logging for better error handling and added unit tests for evidence folder creation.
2025-01-03 02:52:20 +01:00
23 changed files with 691 additions and 272 deletions
Vendored
+4 -1
View File
@@ -1,9 +1,12 @@
pipeline { pipeline {
agent any agent any
environment {
NEXUS_CREDS = credentials('alttd-snapshot-user')
}
stages { stages {
stage('Gradle') { stage('Gradle') {
steps { steps {
sh 'bash gradlew shadowJar -x test' sh './gradlew shadowJar -x test -PalttdSnapshotUsername=$NEXUS_CREDS_USR -PalttdSnapshotPassword=$NEXUS_CREDS_PSW'
} }
} }
stage('Archive') { stage('Archive') {
+29 -14
View File
@@ -1,27 +1,27 @@
plugins { plugins {
`java` `java`
`maven-publish` `maven-publish`
id("com.github.johnrengelman.shadow") version "7.0.0" id("com.gradleup.shadow") version "9.0.0-beta4"
} }
allprojects { allprojects {
val build = System.getenv("BUILD_NUMBER") ?: "SNAPSHOT"
group = "com.alttd.proxydiscordlink" group = "com.alttd.proxydiscordlink"
description = "A velocity plugin to link Discord and Minecraft accounts." description = "A velocity plugin to link Discord and Minecraft accounts."
version = "1.0.1-SNAPSHOT"
apply(plugin = "java") apply(plugin = "java")
apply(plugin = "maven-publish") apply(plugin = "maven-publish")
java { java {
toolchain { toolchain {
languageVersion.set(JavaLanguageVersion.of(16)) languageVersion.set(JavaLanguageVersion.of(21))
} }
} }
tasks { tasks {
withType<JavaCompile> { withType<JavaCompile> {
options.encoding = Charsets.UTF_8.name() options.encoding = Charsets.UTF_8.name()
options.release.set(16) options.release.set(21)
} }
withType<Javadoc> { withType<Javadoc> {
@@ -30,30 +30,40 @@ allprojects {
} }
} }
tasks.test {
useJUnitPlatform()
}
dependencies { dependencies {
// Minimessage // Minimessage
// implementation("net.kyori:adventure-text-minimessage:4.1.0-SNAPSHOT") // implementation("net.kyori:adventure-text-minimessage:4.1.0-SNAPSHOT")
// Velocity // Velocity
compileOnly("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT") // Velocity compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") // Velocity
annotationProcessor("com.velocitypowered:velocity-api:3.1.2-SNAPSHOT") annotationProcessor("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT")
// JDA // JDA
implementation("net.dv8tion:JDA:5.0.0-beta.2") { implementation("net.dv8tion:JDA:5.0.0-beta.2") {
shadow("net.dv8tion:JDA:5.0.0-beta.2") {
exclude("opus-java") // exclude audio exclude("opus-java") // exclude audio
} }
compileOnly("com.gitlab.ruany:LitebansAPI:0.3.5") compileOnly("com.gitlab.ruany:LitebansAPI:0.3.5")
// LuckPerms // LuckPerms
compileOnly("net.luckperms:api:5.3") compileOnly("net.luckperms:api:5.3")
// MySQL // MySQL
runtimeOnly("mysql:mysql-connector-java:8.0.23") runtimeOnly("mysql:mysql-connector-java:8.0.23")
// ShutdownInfo // ShutdownInfo
compileOnly("com.alttd:ShutdownInfo:1.0") compileOnly("com.alttd:shutdowninfo:1.0.0-SNAPSHOT")
}
implementation("org.aarboard.nextcloud:nextcloud-api:13.1.0") //NextCloud
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.10.0")
tasks { tasks {
shadowJar { shadowJar {
archiveFileName.set("discordLink.jar")
archiveFileName.set("ProxyDiscordLink.jar")
listOf( listOf(
"net.dv8tion.jda" "net.dv8tion.jda"
).forEach { relocate(it, "${rootProject.group}.lib.$it") } ).forEach { relocate(it, "${rootProject.group}.lib.$it") }
@@ -70,15 +80,20 @@ dependencies {
publishing { publishing {
publications { publications {
create<MavenPublication>("mavenJava") { create<MavenPublication>("mavenJava") {
from(components["java"]) artifact(tasks.shadowJar.get()) {
classifier = null
}
} }
} }
repositories{ repositories{
maven { maven {
name = "maven" name = "nexus"
url = uri("https://repo.destro.xyz/snapshots") url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials(PasswordCredentials::class) credentials {
username = project.property("alttdSnapshotUsername") as String
password = project.property("alttdSnapshotPassword") as String
}
} }
} }
} }
Binary file not shown.
+3 -1
View File
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+179 -115
View File
@@ -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"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with 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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 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." location of your Java installation."
fi fi
else else
JAVACMD="java" 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. 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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# 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" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --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 # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 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, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
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" "$@" exec "$JAVACMD" "$@"
Vendored
+9 -6
View File
@@ -14,7 +14,7 @@
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
+9 -3
View File
@@ -1,13 +1,19 @@
rootProject.name = "ProxyDiscordLink" rootProject.name = "ProxyDiscordLink"
val nexusUser = providers.gradleProperty("alttdSnapshotUsername").get()
val nexusPass = providers.gradleProperty("alttdSnapshotPassword").get()
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
mavenCentral() mavenCentral()
// Altitude // Altitude
maven { maven {
name = "maven" name = "nexus"
url = uri("https://repo.destro.xyz/snapshots") url = uri("https://repo.alttd.com/repository/alttd-snapshot/")
credentials(PasswordCredentials::class) credentials {
username = nexusUser
password = nexusPass
}
} }
// Velocity // Velocity
maven("https://nexus.velocitypowered.com/repository/maven-public/") maven("https://nexus.velocitypowered.com/repository/maven-public/")
@@ -41,8 +41,7 @@ public class DiscordLink {
private Bot bot; private Bot bot;
@Inject @Inject
public DiscordLink(ProxyServer proxyServer, Logger proxyLogger, @DataDirectory Path proxydataDirectory) public DiscordLink(ProxyServer proxyServer, Logger proxyLogger, @DataDirectory Path proxydataDirectory) {
{
plugin = this; plugin = this;
server = proxyServer; server = proxyServer;
logger = proxyLogger; logger = proxyLogger;
@@ -71,6 +70,12 @@ public class DiscordLink {
loadEvents(); loadEvents();
loadBot(); loadBot();
new LiteBansBanListener().registerEvents(); new LiteBansBanListener().registerEvents();
// try {
// WordPressDatabaseConnection.initialize();
// ALogger.error("*** Could not connect to the wordpress database. ***");
// } catch (SQLException e) {
// throw new RuntimeException(e);
// }
} }
public void reloadConfig() { public void reloadConfig() {
@@ -94,7 +99,6 @@ public class DiscordLink {
bot.connect(); bot.connect();
} }
public File getDataDirectory() { public File getDataDirectory() {
return dataDirectory.toFile(); return dataDirectory.toFile();
} }
@@ -1,6 +1,7 @@
package com.alttd.proxydiscordlink; package com.alttd.proxydiscordlink;
import com.alttd.proxydiscordlink.bot.commandManager.CommandManager; import com.alttd.proxydiscordlink.bot.commandManager.CommandManager;
import com.alttd.proxydiscordlink.util.ALogger;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.events.session.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
@@ -16,8 +17,9 @@ public class JDAListener extends ListenerAdapter {
@Override @Override
public void onReady(@NotNull ReadyEvent event) { public void onReady(@NotNull ReadyEvent event) {
CommandManager commandManager = new CommandManager(jda); // ALogger.info("JDA ready, loading command manager");
jda.addEventListener(commandManager); // CommandManager commandManager = new CommandManager(jda);
// jda.addEventListener(commandManager);
} }
} }
@@ -1,7 +1,8 @@
package com.alttd.proxydiscordlink.bot; package com.alttd.proxydiscordlink.bot;
import com.alttd.proxydiscordlink.JDAListener;
import com.alttd.proxydiscordlink.DiscordLink; import com.alttd.proxydiscordlink.DiscordLink;
import com.alttd.proxydiscordlink.bot.commandManager.CommandManager;
import com.alttd.proxydiscordlink.bot.listeners.DiscordJoinListener;
import com.alttd.proxydiscordlink.bot.listeners.DiscordRoleListener; import com.alttd.proxydiscordlink.bot.listeners.DiscordRoleListener;
import com.alttd.proxydiscordlink.bot.tasks.CheckLinkSync; import com.alttd.proxydiscordlink.bot.tasks.CheckLinkSync;
import com.alttd.proxydiscordlink.config.BotConfig; import com.alttd.proxydiscordlink.config.BotConfig;
@@ -16,7 +17,6 @@ import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.exceptions.HierarchyException; import net.dv8tion.jda.api.exceptions.HierarchyException;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException; import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.MemberCachePolicy;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -31,6 +31,7 @@ public class Bot {
public void connect() { public void connect() {
disconnect(); disconnect();
try { try {
ALogger.info("Creating bot instance");
jda = JDABuilder jda = JDABuilder
.createDefault(BotConfig.DISCORD.BOT_TOKEN) .createDefault(BotConfig.DISCORD.BOT_TOKEN)
.setMemberCachePolicy(MemberCachePolicy.ALL) .setMemberCachePolicy(MemberCachePolicy.ALL)
@@ -38,13 +39,17 @@ public class Bot {
.build(); .build();
jda.setAutoReconnect(true); jda.setAutoReconnect(true);
jda.awaitReady(); jda.awaitReady();
ALogger.info("JDA ready");
jda.addEventListener( jda.addEventListener(
new DiscordRoleListener(), new DiscordJoinListener(),
new JDAListener(jda)); new DiscordRoleListener()/*,
new JDAListener(jda)*/);
DiscordLink.getPlugin().getProxy().getScheduler().buildTask(DiscordLink.getPlugin(), new CheckLinkSync()) DiscordLink.getPlugin().getProxy().getScheduler().buildTask(DiscordLink.getPlugin(), new CheckLinkSync())
.delay(120, TimeUnit.SECONDS) .delay(120, TimeUnit.SECONDS)
.repeat(12, TimeUnit.HOURS) .repeat(12, TimeUnit.HOURS)
.schedule(); .schedule();
CommandManager commandManager = new CommandManager(jda);
jda.addEventListener(commandManager);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -37,6 +37,7 @@ public class CommandManager extends ListenerAdapter {
.filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(commandName)) .filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(commandName))
.findFirst(); .findFirst();
if (first.isEmpty()) { if (first.isEmpty()) {
ALogger.info(String.format("The command %s was used, but it's not on this plugin", commandName));
return; return;
} }
first.get().execute(event); first.get().execute(event);
@@ -11,6 +11,7 @@ import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
@@ -53,6 +54,7 @@ public class CommandLink extends DiscordCommand {
return; return;
} }
event.deferReply(true).queue(interactionHook -> {
List<DiscordRole> discordRoles = Utilities.getDiscordRolesForUser(uuid, member); List<DiscordRole> discordRoles = Utilities.getDiscordRolesForUser(uuid, member);
DiscordLinkPlayer discordLinkPlayer = new DiscordLinkPlayer( DiscordLinkPlayer discordLinkPlayer = new DiscordLinkPlayer(
@@ -66,10 +68,11 @@ public class CommandLink extends DiscordCommand {
.map(DiscordRole::getInternalName) .map(DiscordRole::getInternalName)
.collect(Collectors.toList())); .collect(Collectors.toList()));
linkAccount(discordLinkPlayer, event); linkAccount(discordLinkPlayer, event, interactionHook);
});
} }
private void linkAccount(DiscordLinkPlayer discordLinkPlayer, SlashCommandInteractionEvent event) { private void linkAccount(DiscordLinkPlayer discordLinkPlayer, SlashCommandInteractionEvent event, InteractionHook interactionHook) {
discordLinkPlayer.updateDiscord( discordLinkPlayer.updateDiscord(
DiscordRole.getDiscordRoles().stream() DiscordRole.getDiscordRoles().stream()
.filter(role -> discordLinkPlayer.getRoles().contains(role.getInternalName())) .filter(role -> discordLinkPlayer.getRoles().contains(role.getInternalName()))
@@ -87,27 +90,27 @@ public class CommandLink extends DiscordCommand {
Guild guild = event.getGuild(); Guild guild = event.getGuild();
Member member = event.getMember(); Member member = event.getMember();
if (guild == null || member == null) { if (guild == null || member == null) {
Utilities.commandErrAutoRem("Unable to find guild", event); Utilities.commandErrAutoRem("Unable to find guild", interactionHook);
return; return;
} }
if (player != null || user != null) if (player != null || user != null) {
DiscordLink.getPlugin().getBot().changeNick( DiscordLink.getPlugin().getBot().changeNick(
guild.getIdLong(), guild.getIdLong(),
member.getIdLong(), member.getIdLong(),
player == null ? player == null ?
user.getUsername() : user.getUsername() :
player.getUsername()); player.getUsername());
else } else {
DiscordLink.getPlugin().getBot().changeNick( DiscordLink.getPlugin().getBot().changeNick(
guild.getIdLong(), guild.getIdLong(),
member.getIdLong(), member.getIdLong(),
discordLinkPlayer.getUsername()); discordLinkPlayer.getUsername());
}
event.replyEmbeds(Utilities.genericSuccessEmbed("Success","You have successfully linked " + interactionHook.editOriginalEmbeds(Utilities.genericSuccessEmbed("Success","You have successfully linked " +
discordLinkPlayer.getUsername() + " with " + discordLinkPlayer.getUsername() + " with " +
discordLinkPlayer.getDiscordUsername() + "!")) discordLinkPlayer.getDiscordUsername() + "!"))
.setEphemeral(true) .queue(result -> result.delete().queueAfter(5, TimeUnit.SECONDS));
.queue(result -> result.deleteOriginal().queueAfter(5, TimeUnit.SECONDS));
DiscordLinkPlayer.addDiscordLinkPlayer(discordLinkPlayer); DiscordLinkPlayer.addDiscordLinkPlayer(discordLinkPlayer);
DiscordLink.getPlugin().getDatabase().syncPlayer(discordLinkPlayer); DiscordLink.getPlugin().getDatabase().syncPlayer(discordLinkPlayer);
@@ -0,0 +1,30 @@
package com.alttd.proxydiscordlink.bot.listeners;
import com.alttd.proxydiscordlink.DiscordLink;
import com.alttd.proxydiscordlink.bot.objects.DiscordRole;
import com.alttd.proxydiscordlink.database.Database;
import com.alttd.proxydiscordlink.objects.DiscordLinkPlayer;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.util.stream.Collectors;
public class DiscordJoinListener extends ListenerAdapter {
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
User user = event.getUser();
Database database = DiscordLink.getPlugin().getDatabase();
if (database.playerIsLinked(user.getIdLong())) {
DiscordLinkPlayer discordLinkPlayer = database.getPlayer(user.getIdLong());
discordLinkPlayer.linkedRole(true);
discordLinkPlayer.updateDiscord(
DiscordRole.getDiscordRoles().stream()
.filter(role -> discordLinkPlayer.getRoles().contains(role.getInternalName()))
.collect(Collectors.toList()),
true);
}
}
}
@@ -34,7 +34,7 @@ public class CheckLinkSync implements Runnable {
HashSet<Long> notInDbIds = membersIdSet.stream().filter(id -> !dbIdSet.contains(id)).collect(Collectors.toCollection(HashSet::new)); HashSet<Long> notInDbIds = membersIdSet.stream().filter(id -> !dbIdSet.contains(id)).collect(Collectors.toCollection(HashSet::new));
fixNotInDb(members, notInDbIds); fixNotInDb(members, notInDbIds);
fixNoLinkRole(members, noRoleIds); // fixNoLinkRole(members, noRoleIds); //TODO remove this and find another way to do this cus this only finds cached members which most ppl aren't
} }
private void fixNotInDb(List<Member> members, Set<Long> notInDbIds) { private void fixNotInDb(List<Member> members, Set<Long> notInDbIds) {
@@ -4,11 +4,10 @@ import com.alttd.proxydiscordlink.bot.objects.DiscordRole;
import com.alttd.proxydiscordlink.util.ALogger; import com.alttd.proxydiscordlink.util.ALogger;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode; import org.spongepowered.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions; import org.spongepowered.configurate.ConfigurationOptions;
import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.spongepowered.configurate.serialize.SerializationException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader; import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -27,7 +26,7 @@ public class BotConfig {
private static File CONFIG_FILE; private static File CONFIG_FILE;
public static ConfigurationNode config; public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader; public static YamlConfigurationLoader configLoader;
static int version; static int version;
static boolean verbose; static boolean verbose;
@@ -38,9 +37,8 @@ public class BotConfig {
CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "DiscordLink"); CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "DiscordLink");
CONFIG_FILE = new File(CONFIGPATH, "bot-config.yml"); CONFIG_FILE = new File(CONFIGPATH, "bot-config.yml");
configLoader = YAMLConfigurationLoader.builder() configLoader = YamlConfigurationLoader.builder()
.setFile(CONFIG_FILE) .file(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build(); .build();
if (!CONFIG_FILE.getParentFile().exists()) { if (!CONFIG_FILE.getParentFile().exists()) {
if (!CONFIG_FILE.getParentFile().mkdirs()) { if (!CONFIG_FILE.getParentFile().mkdirs()) {
@@ -58,7 +56,7 @@ public class BotConfig {
} }
try { try {
config = configLoader.load(ConfigurationOptions.defaults().setHeader(HEADER)); config = configLoader.load(ConfigurationOptions.defaults().header(HEADER));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -81,24 +79,24 @@ public class BotConfig {
try { try {
method.setAccessible(true); method.setAccessible(true);
method.invoke(instance); method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) { } catch (InvocationTargetException | IllegalAccessException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
} }
} }
try { try {
configLoader.save(config); configLoader.save(config);
} catch (IOException ex) { } catch (IOException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
public static void saveConfig() { public static void saveConfig() {
try { try {
configLoader.save(config); configLoader.save(config);
} catch (IOException ex) { } catch (IOException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
@@ -107,58 +105,64 @@ public class BotConfig {
} }
private static void set(String path, Object def) { private static void set(String path, Object def) {
if (config.getNode(splitPath(path)).isVirtual()) if (config.node(splitPath(path)).virtual()) {
config.getNode(splitPath(path)).setValue(def); try {
config.node(splitPath(path)).set(def);
} catch (SerializationException e) {
e.printStackTrace();
}
}
} }
private static void setString(String path, String def) { private static void setString(String path, String def) {
try { try {
if (config.getNode(splitPath(path)).isVirtual()) if (config.node(splitPath(path)).virtual())
config.getNode(splitPath(path)).setValue(TypeToken.of(String.class), def); config.node(splitPath(path)).set(String.class, def);
} catch (ObjectMappingException ex) { } catch (SerializationException e) {
e.printStackTrace();
} }
} }
private static boolean getBoolean(String path, boolean def) { private static boolean getBoolean(String path, boolean def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getBoolean(def); return config.node(splitPath(path)).getBoolean(def);
} }
private static double getDouble(String path, double def) { private static double getDouble(String path, double def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getDouble(def); return config.node(splitPath(path)).getDouble(def);
} }
private static int getInt(String path, int def) { private static int getInt(String path, int def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getInt(def); return config.node(splitPath(path)).getInt(def);
} }
private static String getString(String path, String def) { private static String getString(String path, String def) {
setString(path, def); setString(path, def);
return config.getNode(splitPath(path)).getString(def); return config.node(splitPath(path)).getString(def);
} }
private static Long getLong(String path, Long def) { private static Long getLong(String path, Long def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getLong(def); return config.node(splitPath(path)).getLong(def);
} }
private static <T> List<String> getList(String path, T def) { private static <T> List<String> getList(String path, T def) {
try { try {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getList(TypeToken.of(String.class)); return config.node(splitPath(path)).getList(String.class);
} catch (ObjectMappingException ex) { } catch (SerializationException e) {
} }
return new ArrayList<>(); return new ArrayList<>();
} }
private static ConfigurationNode getNode(String path) { private static ConfigurationNode getNode(String path) {
if (config.getNode(splitPath(path)).isVirtual()) { if (config.node(splitPath(path)).virtual()) {
//new RegexConfig("Dummy"); //new RegexConfig("Dummy");
} }
config.getChildrenMap(); config.childrenMap();
return config.getNode(splitPath(path)); return config.node(splitPath(path));
} }
/** /**
@@ -203,12 +207,12 @@ public class BotConfig {
private static void prefix() { private static void prefix() {
prefixMap.clear(); prefixMap.clear();
ConfigurationNode node = getNode("prefixes"); ConfigurationNode node = getNode("prefixes");
if (node.getChildrenMap().isEmpty()) { if (node.childrenMap().isEmpty()) {
ALogger.warn("No prefixes found in BotConfig, add them to use commands:\n" + ALogger.warn("No prefixes found in BotConfig, add them to use commands:\n" +
"prefixes:\n\t" + "prefixes:\n\t" +
"server_id: prefix"); "server_id: prefix");
} }
node.getChildrenMap().forEach((key, value) -> { node.childrenMap().forEach((key, value) -> {
prefixMap.put((Long) key, value.getString()); prefixMap.put((Long) key, value.getString());
}); });
} }
@@ -216,7 +220,7 @@ public class BotConfig {
private static void roles() { private static void roles() {
DiscordRole.cleanDiscordRoles(); DiscordRole.cleanDiscordRoles();
ConfigurationNode node = getNode("sync-roles"); ConfigurationNode node = getNode("sync-roles");
if (node.getChildrenMap().isEmpty()) if (node.childrenMap().isEmpty())
ALogger.warn("No roles found in BotConfig, add them to use sync-roles feature:\n" + ALogger.warn("No roles found in BotConfig, add them to use sync-roles feature:\n" +
"sync-roles:\n\t" + "sync-roles:\n\t" +
"example_rank:\n\t\t" + "example_rank:\n\t\t" +
@@ -226,14 +230,14 @@ public class BotConfig {
"update-to-minecraft: true\n\t\t" + "update-to-minecraft: true\n\t\t" +
"update-to-discord: true\n\t\t" + "update-to-discord: true\n\t\t" +
"announcement: <player> got example rank!"); "announcement: <player> got example rank!");
node.getChildrenMap().forEach((key, value) -> { node.childrenMap().forEach((key, value) -> {
String internalName = key.toString(); String internalName = key.toString();
long id = value.getNode("role-id").getLong(-1); long id = value.node("role-id").getLong(-1);
String luckpermsName = value.getNode("luckperms-name").getString("example"); String luckpermsName = value.node("luckperms-name").getString("example");
String display_name = value.getNode("display-name").getString("Example"); String display_name = value.node("display-name").getString("Example");
boolean updateToMinecraft = value.getNode("update-to-minecraft").getBoolean(false); boolean updateToMinecraft = value.node("update-to-minecraft").getBoolean(false);
boolean updateToDiscord = value.getNode("update-to-discord").getBoolean(false); boolean updateToDiscord = value.node("update-to-discord").getBoolean(false);
String announcement = value.getNode("announcement").getString("<player> got example rank!"); String announcement = value.node("announcement").getString("<player> got example rank!");
if (id == -1) if (id == -1)
ALogger.error("Invalid id in BotConfig for roles."); ALogger.error("Invalid id in BotConfig for roles.");
@@ -2,10 +2,10 @@ package com.alttd.proxydiscordlink.config;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode; import org.spongepowered.configurate.ConfigurationNode;
import ninja.leaping.configurate.ConfigurationOptions; import org.spongepowered.configurate.ConfigurationOptions;
import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.spongepowered.configurate.serialize.SerializationException;
import ninja.leaping.configurate.yaml.YAMLConfigurationLoader; import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import java.io.File; import java.io.File;
@@ -23,7 +23,7 @@ public final class Config {
private static File CONFIG_FILE; private static File CONFIG_FILE;
public static ConfigurationNode config; public static ConfigurationNode config;
public static YAMLConfigurationLoader configLoader; public static YamlConfigurationLoader configLoader;
static int version; static int version;
static boolean verbose; static boolean verbose;
@@ -34,9 +34,8 @@ public final class Config {
CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "DiscordLink"); CONFIGPATH = new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "DiscordLink");
CONFIG_FILE = new File(CONFIGPATH, "config.yml"); CONFIG_FILE = new File(CONFIGPATH, "config.yml");
configLoader = YAMLConfigurationLoader.builder() configLoader = YamlConfigurationLoader.builder()
.setFile(CONFIG_FILE) .file(CONFIG_FILE)
.setFlowStyle(DumperOptions.FlowStyle.BLOCK)
.build(); .build();
if (!CONFIG_FILE.getParentFile().exists()) { if (!CONFIG_FILE.getParentFile().exists()) {
if (!CONFIG_FILE.getParentFile().mkdirs()) { if (!CONFIG_FILE.getParentFile().mkdirs()) {
@@ -54,7 +53,7 @@ public final class Config {
} }
try { try {
config = configLoader.load(ConfigurationOptions.defaults().setHeader(HEADER)); config = configLoader.load(ConfigurationOptions.defaults().header(HEADER));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -77,24 +76,24 @@ public final class Config {
try { try {
method.setAccessible(true); method.setAccessible(true);
method.invoke(instance); method.invoke(instance);
} catch (InvocationTargetException | IllegalAccessException ex) { } catch (InvocationTargetException | IllegalAccessException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
} }
} }
try { try {
configLoader.save(config); configLoader.save(config);
} catch (IOException ex) { } catch (IOException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
public static void saveConfig() { public static void saveConfig() {
try { try {
configLoader.save(config); configLoader.save(config);
} catch (IOException ex) { } catch (IOException e) {
throw Throwables.propagate(ex.getCause()); throw Throwables.propagate(e.getCause());
} }
} }
@@ -103,58 +102,64 @@ public final class Config {
} }
private static void set(String path, Object def) { private static void set(String path, Object def) {
if (config.getNode(splitPath(path)).isVirtual()) if (config.node(splitPath(path)).virtual()) {
config.getNode(splitPath(path)).setValue(def); try {
config.node(splitPath(path)).set(def);
} catch (SerializationException e) {
throw new RuntimeException(e);
}
}
} }
private static void setString(String path, String def) { private static void setString(String path, String def) {
try { try {
if (config.getNode(splitPath(path)).isVirtual()) if (config.node(splitPath(path)).virtual())
config.getNode(splitPath(path)).setValue(TypeToken.of(String.class), def); config.node(splitPath(path)).set(String.class, def);
} catch (ObjectMappingException ex) { } catch (SerializationException e) {
} }
} }
private static boolean getBoolean(String path, boolean def) { private static boolean getBoolean(String path, boolean def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getBoolean(def); return config.node(splitPath(path)).getBoolean(def);
} }
private static double getDouble(String path, double def) { private static double getDouble(String path, double def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getDouble(def); return config.node(splitPath(path)).getDouble(def);
} }
private static int getInt(String path, int def) { private static int getInt(String path, int def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getInt(def); return config.node(splitPath(path)).getInt(def);
} }
private static String getString(String path, String def) { private static String getString(String path, String def) {
setString(path, def); setString(path, def);
return config.getNode(splitPath(path)).getString(def); return config.node(splitPath(path)).getString(def);
} }
private static Long getLong(String path, Long def) { private static Long getLong(String path, Long def) {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getLong(def); return config.node(splitPath(path)).getLong(def);
} }
private static <T> List<String> getList(String path, T def) { private static <T> List<String> getList(String path, T def) {
try { try {
set(path, def); set(path, def);
return config.getNode(splitPath(path)).getList(TypeToken.of(String.class)); return config.node(splitPath(path)).getList(String.class);
} catch (ObjectMappingException ex) { } catch (SerializationException e) {
e.printStackTrace();
} }
return new ArrayList<>(); return new ArrayList<>();
} }
private static ConfigurationNode getNode(String path) { private static ConfigurationNode getNode(String path) {
if (config.getNode(splitPath(path)).isVirtual()) { if (config.node(splitPath(path)).virtual()) {
//new RegexConfig("Dummy"); //new RegexConfig("Dummy");
} }
config.getChildrenMap(); config.childrenMap();
return config.getNode(splitPath(path)); return config.node(splitPath(path));
} }
@@ -174,7 +179,9 @@ public final class Config {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static void loadSubclasses() { private static void loadSubclasses() {
DB.database(); DB.database();
WORDPRESS_DB.database();
MESSAGES.loadMessages(); MESSAGES.loadMessages();
NEXT_CLOUD.loadNextCloud();
} }
public static class DB { public static class DB {
@@ -195,6 +202,38 @@ public final class Config {
} }
} }
public static class WORDPRESS_DB {
public static String DRIVERS = "mysql";
public static String IP = "localhost";
public static String PORT = "3306";
public static String DATABASE_NAME = "wordpress";
public static String USERNAME = "root";
public static String PASSWORD = "root";
private static void database() {
DRIVERS = getString("database.drivers", DRIVERS);
IP = getString("database.ip", IP);
PORT = getString("database.port", PORT);
DATABASE_NAME = getString("database.database_name", DATABASE_NAME);
USERNAME = getString("database.username", USERNAME);
PASSWORD = getString("database.password", PASSWORD);
}
}
public static class NEXT_CLOUD {
public static String ADDRESS = "drive.alttd.com";
public static Integer PORT = 443;
public static String USERNAME = "root";
public static String PASSWORD = "root";
private static void loadNextCloud() {
ADDRESS = getString("next_cloud.address", ADDRESS);
PORT = getInt("next_cloud.port", PORT);
USERNAME = getString("next_cloud.username", USERNAME);
PASSWORD = getString("next_cloud.password", PASSWORD);
}
}
public static class MESSAGES { public static class MESSAGES {
public static String ALREADY_LINKED_ACCOUNTS = "<yellow>Your accounts are already linked. You can unlink your accounts by doing <gold>/discord unlink</gold>.</yellow>"; public static String ALREADY_LINKED_ACCOUNTS = "<yellow>Your accounts are already linked. You can unlink your accounts by doing <gold>/discord unlink</gold>.</yellow>";
@@ -0,0 +1,23 @@
package com.alttd.proxydiscordlink.database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
public class WordPressDatabase {
public Optional<Integer> getLastId() { //TODO use this to let players know if there was a new announcement
try {
PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement("SELECT MAX(id) FROM wp_posts");
ResultSet result = statement.executeQuery();
if (result.next()) {
return Optional.of(result.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return Optional.empty();
}
}
@@ -0,0 +1,56 @@
package com.alttd.proxydiscordlink.database;
import com.alttd.proxydiscordlink.DiscordLink;
import com.alttd.proxydiscordlink.config.Config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class WordPressDatabaseConnection {
private static WordPressDatabaseConnection instance;
private Connection connection;
public WordPressDatabaseConnection() throws SQLException {
instance = this;
instance.openConnection();
DiscordLink.getPlugin().getDatabase().createTables();
}
public void openConnection() throws SQLException {
if (this.connection == null || this.connection.isClosed()) {
synchronized(this) {
if (this.connection == null || this.connection.isClosed()) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
this.connection = DriverManager.getConnection("jdbc:"
+ Config.WORDPRESS_DB.DRIVERS + "://"
+ Config.WORDPRESS_DB.IP + ":"
+ Config.WORDPRESS_DB.PORT + "/"
+ Config.WORDPRESS_DB.DATABASE_NAME
+ "?autoReconnect=true&useSSL=false", Config.WORDPRESS_DB.USERNAME,
Config.WORDPRESS_DB.PASSWORD);
}
}
}
}
public static Connection getConnection() {
try {
instance.openConnection();
} catch (SQLException var1) {
var1.printStackTrace();
}
return instance.connection;
}
public static void initialize() throws SQLException {
instance = new WordPressDatabaseConnection();
}
}
@@ -0,0 +1,41 @@
package com.alttd.proxydiscordlink.minecraft.listeners;
import com.alttd.proxydiscordlink.database.WordPressDatabase;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
//Sorry this is not really a listener...
public class AnnouncementListener {
int lastId;
private static AnnouncementListener instance;
public static AnnouncementListener getInstance() {
if (instance == null)
instance = new AnnouncementListener();
return instance;
}
private AnnouncementListener() {
lastId = checkLatestAnnouncement();
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
// Schedule the task to run every 5 minutes
executorService.scheduleAtFixedRate(() -> {
// Call the function you want to execute
lastId = checkLatestAnnouncement();
}, 5, 5, TimeUnit.MINUTES);
}
private int checkLatestAnnouncement() {
return new WordPressDatabase().getLastId().orElse(0);
}
public int getCurrentId() {
return lastId;
}
}
@@ -3,12 +3,18 @@ package com.alttd.proxydiscordlink.minecraft.listeners;
import com.alttd.proxydiscordlink.DiscordLink; import com.alttd.proxydiscordlink.DiscordLink;
import com.alttd.proxydiscordlink.config.BotConfig; import com.alttd.proxydiscordlink.config.BotConfig;
import com.alttd.proxydiscordlink.objects.DiscordLinkPlayer; import com.alttd.proxydiscordlink.objects.DiscordLinkPlayer;
import com.alttd.proxydiscordlink.util.ALogger;
import com.alttd.proxydiscordlink.util.Evidence;
import com.alttd.proxydiscordlink.util.Utilities;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import litebans.api.Entry; import litebans.api.Entry;
import litebans.api.Events; import litebans.api.Events;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.luckperms.api.model.user.User;
import java.awt.*; import java.awt.*;
import java.time.Instant;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -32,39 +38,93 @@ public class LiteBansBanListener {
} }
private void onBan(Entry entry) { private void onBan(Entry entry) {
if (!entry.isPermanent()) ALogger.info("Ban detected, making evidence...");
if (entry == null) {
ALogger.warn("Failed to find ban entry, no evidence made");
return; return;
}
String stringUuid = entry.getUuid(); String stringUuid = entry.getUuid();
if (stringUuid == null) if (stringUuid == null) {
ALogger.warn("Failed to find uuid in entry, no evidence made");
return; return;
}
UUID uuid = UUID.fromString(stringUuid); UUID uuid = UUID.fromString(stringUuid);
Optional<Player> player = DiscordLink.getPlugin().getProxy().getPlayer(uuid);
String username;
if (player.isPresent()) {
username = player.get().getUsername();
} else {
User user = Utilities.getLuckPerms().getUserManager().getUser(uuid);
if (user == null) {
username = uuid.toString();
} else {
username = user.getUsername();
}
}
ALogger.info(String.format("Making evidence folder for %s", username));
Evidence evidence = new Evidence();
evidence.getNewEvidenceFolder(username).handle((optionalUrl, ex) -> {
if (ex != null) {
ALogger.error("Failed to make evidence folder", ex);
return Optional.empty();
}
Optional<MessageEmbed.Field> field = banDiscordUserIfExists(entry, uuid);
EmbedBuilder banEvidence = new EmbedBuilder()
.setColor(entry.isPermanent() ? Color.RED : Color.ORANGE)
.setAuthor(username, null, "https://crafatar.com/avatars/" + stringUuid + "?overlay")
.addField("Banned by", entry.getExecutorName() == null ? "unknown" : entry.getExecutorName(), true)
.addField("Ban duration", getBanDuration(entry), true)
.addField("Reason", entry.getReason() == null ? "unknown" : entry.getReason(), true)
.setTitle("Evidence");
Optional<String> returnUrl;
if (optionalUrl.isPresent()) {
String s = optionalUrl.get();
banEvidence.addField("Evidence", s, false);
returnUrl = Optional.of(s);
} else {
banEvidence.addField("Evidence", "Failed to get url, please make the folder yourself and reply to this post with the link.", false);
returnUrl = Optional.empty();
}
field.ifPresent(banEvidence::addField);
DiscordLink.getPlugin().getBot().sendEmbedToDiscord(BotConfig.DISCORD.EVIDENCE_CHANNEL_ID, banEvidence, -1);
return returnUrl;
});
}
private String getBanDuration(Entry entry) {
if (entry.isPermanent())
return "Permanent ban";
Instant instant = Instant.ofEpochMilli(entry.getDateEnd());
return String.format("<t:%d:F>", instant.getEpochSecond());
}
private Optional<MessageEmbed.Field> banDiscordUserIfExists(Entry entry, UUID uuid) {
if (!entry.isPermanent())
return Optional.empty();
DiscordLinkPlayer discordLinkPlayer = DiscordLinkPlayer.getDiscordLinkPlayer(uuid); DiscordLinkPlayer discordLinkPlayer = DiscordLinkPlayer.getDiscordLinkPlayer(uuid);
if (discordLinkPlayer == null || !discordLinkPlayer.isActive()) if (discordLinkPlayer == null || !discordLinkPlayer.isActive())
return; return Optional.empty();
discordLinkPlayer.setActive(false); discordLinkPlayer.setActive(false);
DiscordLink.getPlugin().getBot().discordBan(BotConfig.DISCORD.GUILD_ID, discordLinkPlayer.getUserId(), "Auto ban due to Minecraft ban"); DiscordLink.getPlugin().getBot().discordBan(BotConfig.DISCORD.GUILD_ID, discordLinkPlayer.getUserId(), "Auto ban due to Minecraft ban");
Optional<Player> player = DiscordLink.getPlugin().getProxy().getPlayer(uuid);
String username = discordLinkPlayer.getUsername(); return Optional.of(new MessageEmbed.Field("Auto Discord ban",
if (player.isPresent())
username = player.get().getUsername();
DiscordLink.getPlugin().getBot().sendEmbedToDiscord(BotConfig.DISCORD.EVIDENCE_CHANNEL_ID,
new EmbedBuilder()
.setColor(Color.RED)
.setAuthor(username, null, "https://crafatar.com/avatars/" + stringUuid + "?overlay")
.setTitle("Auto Discord ban")
.addField("Ban info",
"**Discord username**: `" + discordLinkPlayer.getDiscordUsername() + "`" + "**Discord username**: `" + discordLinkPlayer.getDiscordUsername() + "`" +
"\n**Discord id**: `" + discordLinkPlayer.getUserId() + "`" + "\n**Discord id**: `" + discordLinkPlayer.getUserId() + "`" +
"\n**UUID**: `" + stringUuid + "`" + "\n**UUID**: `" + uuid.toString() + "`" +
"\n**Banned by**: `" + entry.getExecutorName() + "`" + "\n**Banned by**: `" + entry.getExecutorName() + "`" +
"\n**For**: ```" + (entry.getReason().length() < 800 ? entry.getReason() : entry.getReason().substring(0, 797) + "...") + "```", "\n**For**: ```" + (entry.getReason().length() < 800 ? entry.getReason() : entry.getReason().substring(0, 797) + "...") + "```",
false), false)
-1); );
} }
private void onUnBan(Entry entry) { private void onUnBan(Entry entry) {
@@ -21,4 +21,8 @@ public class ALogger {
public static void error(String message) { public static void error(String message) {
logger.error(message); logger.error(message);
} }
public static void error(String message, Throwable t) {
logger.error(message, t);
}
} }
@@ -0,0 +1,48 @@
package com.alttd.proxydiscordlink.util;
import com.alttd.proxydiscordlink.config.Config;
import org.aarboard.nextcloud.api.NextcloudConnector;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class Evidence {
public CompletableFuture<Optional<String>> getNewEvidenceFolder(String username) {
return CompletableFuture.supplyAsync(() -> {
NextcloudConnector nextcloudConnector = new NextcloudConnector(
Config.NEXT_CLOUD.ADDRESS,
true,
Config.NEXT_CLOUD.PORT,
Config.NEXT_CLOUD.USERNAME,
Config.NEXT_CLOUD.PASSWORD
);
String evidenceFilePath = String.format("/Evidence/%s", username);
if (!nextcloudConnector.folderExists(evidenceFilePath)) {
nextcloudConnector.createFolder(evidenceFilePath);
}
String newEvidenceFolderPath = evidenceFilePath + "/" + getCurrentDate();
if (!nextcloudConnector.folderExists(newEvidenceFolderPath)) {
nextcloudConnector.createFolder(newEvidenceFolderPath);
}
String id;
try {
id = nextcloudConnector.getProperties(newEvidenceFolderPath, true).getId();
} catch (IOException e) {
ALogger.error("Failed to get share link for Next Cloud folder", e);
return Optional.empty();
}
return Optional.of("https://drive.alttd.com/f/" + id);
});
}
private static String getCurrentDate() {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH_mm");
return now.format(formatter);
}
}
@@ -15,6 +15,7 @@ import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.RestAction;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
@@ -218,6 +219,11 @@ public class Utilities {
.queue(res -> res.deleteOriginal().queueAfter(5, TimeUnit.SECONDS)); .queue(res -> res.deleteOriginal().queueAfter(5, TimeUnit.SECONDS));
} }
public static void commandErrAutoRem(String text, InteractionHook event) {
event.editOriginalEmbeds(Utilities.genericErrorEmbed("Error", text))
.queue(res -> res.delete().queueAfter(5, TimeUnit.SECONDS));
}
public static boolean removeRole(UUID uuid, String group) { public static boolean removeRole(UUID uuid, String group) {
User user = getLuckPerms().getUserManager().getUser(uuid); User user = getLuckPerms().getUserManager().getUser(uuid);