commit efe11b77f7d829edeead813d72de4e2b7528702b Author: Melaine Gérard Date: Sat Nov 16 12:56:41 2024 +0100 :sparkles: Initialisation du projet + rattrapage de l'ancien code sur la nouvelle base diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a6ca59a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.idea/ +.vscode/ +.fleet/ +*.iml + +.git +build/ + +.gradle/ \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8e8f383 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +BOT_TOKEN= +GUILD_ID= + +DB_URL=jdbc:postgresql://localhost:5433/gachamelia +DB_USER=postgres +DB_PASSWORD=gachamelia + +WELCOME_CHANNEL= \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.gitea/workflows/build-docker.yml b/.gitea/workflows/build-docker.yml new file mode 100644 index 0000000..9d8a14e --- /dev/null +++ b/.gitea/workflows/build-docker.yml @@ -0,0 +1,23 @@ +name: Build and Push Docker Image + +on: + push: + tags: + - '*' + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Build and Push with Kaniko + uses: aevea/action-kaniko@master + with: + image: camelia-studio/gachamelia + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + registry: git.crystalyx.net + tag: ${{ gitea.ref_name }} + tag_with_latest: true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..30c6cd5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.gradle +build +.idea/ +.vscode/ +.fleet/ +*.iml + +.env +.env.* +!.env.example \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d79f847 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM eclipse-temurin:21-alpine AS build +WORKDIR /src +COPY . . + +RUN ./gradlew clean shadowJar +FROM eclipse-temurin:21-alpine AS runner +RUN mkdir -p /app +WORKDIR /app +COPY --from=build /src/build/libs/gachamelia.jar /app/gachamelia.jar + +CMD ["java", "-jar", "gachamelia.jar"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c738eed --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Gachamélia + + +Transforme ton serveur Discord en *gacha* géant ! + + +**Gachamélia** est un bot Discord qui va transformer ton serveur en un véritable *gacha* ! Cet outil est développé par la branche **CILA** de l'association **Camélia Studio**. + + +Liens utiles : + + +- Site web Camélia Studio : https://camelia-studio.org +- Site web CILA : https://cila.camelia-studio.org +- Notre serveur Discord : https://discord.gg/nBuZ9vJ \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..cef5754 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,41 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id("java") + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +group = "org.camelia.studio.gachamelia" +version = "0.0.1" + +repositories { + mavenCentral() +} + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.withType { + manifest { + attributes["Main-Class"] = "org.camelia.studio.gachamelia.Gachamelia" + } + + archiveFileName.set("gachamelia.jar") +} + +dependencies { + implementation("org.hibernate:hibernate-core:6.6.2.Final") + implementation("org.hibernate:hibernate-hikaricp:6.6.2.Final") + implementation("org.postgresql:postgresql:42.7.4") + implementation("io.github.cdimascio:dotenv-kotlin:6.4.2") + implementation("net.dv8tion:JDA:5.2.1") + implementation("ch.qos.logback:logback-classic:1.5.12") +} + + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e721dbb --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,13 @@ +services: + postgres: + image: postgres:17 + environment: + POSTGRES_PASSWORD: gachamelia + POSTGRES_DB: gachamelia + ports: + - "5433:5432" + volumes: + - postgres_gachamelia_data:/var/lib/postgresql/data + +volumes: + postgres_gachamelia_data: \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..94113f2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# 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. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +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 ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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" && ! "$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 + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + 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 new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +: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/licence.txt b/licence.txt new file mode 100644 index 0000000..456b86f --- /dev/null +++ b/licence.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2024 Camélia Studio, https://camelia-studio.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/gachamelia/Gachamelia.java b/src/main/java/org/camelia/studio/gachamelia/Gachamelia.java new file mode 100644 index 0000000..fab1ebd --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/Gachamelia.java @@ -0,0 +1,79 @@ +package org.camelia.studio.gachamelia; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.requests.GatewayIntent; +import org.camelia.studio.gachamelia.db.HibernateConfig; +import org.camelia.studio.gachamelia.listeners.ReadyListener; +import org.camelia.studio.gachamelia.managers.ListenerManager; +import org.camelia.studio.gachamelia.models.User; +import org.camelia.studio.gachamelia.repossitories.RankRepository; +import org.camelia.studio.gachamelia.services.RankService; +import org.camelia.studio.gachamelia.services.UserService; +import org.camelia.studio.gachamelia.utils.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +public class Gachamelia { + private static JDA jda; + private static final Logger logger = LoggerFactory.getLogger(Gachamelia.class); + + public static void main(String[] args) { + try { + Configuration.getInstance(); + + jda = JDABuilder.createDefault(Configuration.getInstance().getDotenv().get("BOT_TOKEN")) + .addEventListeners(new ReadyListener()) + .enableIntents(GatewayIntent.getIntents(GatewayIntent.ALL_INTENTS)) + .build() + .awaitReady() + ; + + new ListenerManager().registerListeners(jda); + + + + // Initialisation de la base de données + initDatabase(); + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + HibernateConfig.shutdown(); + jda.shutdown(); + })); + } catch (Exception e) { + logger.error("Une erreur est survenue lors de l'exécution du bot : {}", e.getMessage()); + System.exit(1); + } + } + + public static JDA getJda() { + return jda; + } + + public static void initDatabase() { + if (!RankRepository.getInstance().findAll().isEmpty()) { + Guild guild = jda.getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID")); + if (guild != null) { + List members = guild.getMembers(); + + for (Member member : members) { + User user = UserService.getInstance().getOrCreateUser(member.getId()); + + if (user.getRank() == null) { + user.setRank(RankService.getInstance().getRandomRank()); + UserService.getInstance().updateUser(user); + } + + logger.info("Utilisateur {} initialisé", member.getUser().getAsTag()); + } + } + } else { + logger.error("Aucun rang n'a été trouvé dans la base de données"); + System.exit(1); + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/gachamelia/commands/utils/PingCommand.java b/src/main/java/org/camelia/studio/gachamelia/commands/utils/PingCommand.java new file mode 100644 index 0000000..06cf825 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/commands/utils/PingCommand.java @@ -0,0 +1,20 @@ +package org.camelia.studio.gachamelia.commands.utils; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import org.camelia.studio.gachamelia.interfaces.ISlashCommand; + +public class PingCommand implements ISlashCommand { + @Override + public String getName() { + return "ping"; + } + + @Override + public String getDescription() { + return "Envoie pong !"; + } + + @Override + public void execute(SlashCommandInteractionEvent event) { + event.getHook().editOriginal("Pong !").queue(); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/db/HibernateConfig.java b/src/main/java/org/camelia/studio/gachamelia/db/HibernateConfig.java new file mode 100644 index 0000000..73dd5fc --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/db/HibernateConfig.java @@ -0,0 +1,85 @@ +package org.camelia.studio.gachamelia.db; + +import io.github.cdimascio.dotenv.Dotenv; +import org.camelia.studio.gachamelia.interfaces.IEntity; +import org.camelia.studio.gachamelia.utils.ReflectionUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Properties; + +public class HibernateConfig { + private static final Logger logger = LoggerFactory.getLogger(HibernateConfig.class); + private static SessionFactory sessionFactory; + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + try { + logger.info("Initializing Hibernate SessionFactory"); + Dotenv dotenv = Dotenv.load(); + + Properties props = new Properties(); + + // Configuration Hibernate + props.put(Environment.HBM2DDL_AUTO, "update"); // On utilise validate au lieu de update + + + props.put(Environment.GLOBALLY_QUOTED_IDENTIFIERS, "true"); + + // Configuration HikariCP + props.put("hibernate.connection.provider_class", + "org.hibernate.hikaricp.internal.HikariCPConnectionProvider"); + props.put("hibernate.hikari.minimumIdle", "5"); + props.put("hibernate.hikari.maximumPoolSize", "10"); + props.put("hibernate.hikari.idleTimeout", "300000"); + props.put("hibernate.hikari.dataSourceClassName", + "org.postgresql.ds.PGSimpleDataSource"); + props.put("hibernate.hikari.dataSource.url", dotenv.get("DB_URL")); + props.put("hibernate.hikari.dataSource.user", dotenv.get("DB_USER")); + props.put("hibernate.hikari.dataSource.password", dotenv.get("DB_PASSWORD")); + + Configuration configuration = new Configuration(); + configuration.setProperties(props); + + List entities = ReflectionUtils.loadClasses( + "org.camelia.studio.gachamelia.models", + IEntity.class + ); + + for (IEntity entity : entities) { + configuration.addAnnotatedClass(entity.getClass()); + } + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()) + .build(); + + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + logger.info("Hibernate SessionFactory initialized successfully"); + + } catch (Exception e) { + logger.error("Failed to initialize Hibernate SessionFactory", e); + throw new RuntimeException("Failed to initialize Hibernate SessionFactory", e); + } + } + return sessionFactory; + } + + public static void shutdown() { + logger.info("Shutting down database connections"); + if (sessionFactory != null && !sessionFactory.isClosed()) { + try { + sessionFactory.close(); + logger.info("SessionFactory closed successfully"); + } catch (Exception e) { + logger.error("Error closing SessionFactory", e); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/gachamelia/interfaces/IEntity.java b/src/main/java/org/camelia/studio/gachamelia/interfaces/IEntity.java new file mode 100644 index 0000000..a4f1e89 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/interfaces/IEntity.java @@ -0,0 +1,4 @@ +package org.camelia.studio.gachamelia.interfaces; + +public interface IEntity { +} diff --git a/src/main/java/org/camelia/studio/gachamelia/interfaces/ISlashCommand.java b/src/main/java/org/camelia/studio/gachamelia/interfaces/ISlashCommand.java new file mode 100644 index 0000000..e19159f --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/interfaces/ISlashCommand.java @@ -0,0 +1,16 @@ +package org.camelia.studio.gachamelia.interfaces; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; + +import java.util.List; + +public interface ISlashCommand { + String getName(); + String getDescription(); + void execute(SlashCommandInteractionEvent event); + default List getOptions() { + return List.of(); + } +} + diff --git a/src/main/java/org/camelia/studio/gachamelia/listeners/GuildMemberJoinListener.java b/src/main/java/org/camelia/studio/gachamelia/listeners/GuildMemberJoinListener.java new file mode 100644 index 0000000..058a988 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/listeners/GuildMemberJoinListener.java @@ -0,0 +1,56 @@ +package org.camelia.studio.gachamelia.listeners; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.camelia.studio.gachamelia.models.User; +import org.camelia.studio.gachamelia.models.WelcomeMessage; +import org.camelia.studio.gachamelia.services.RankService; +import org.camelia.studio.gachamelia.services.UserService; +import org.camelia.studio.gachamelia.utils.Configuration; +import org.camelia.studio.gachamelia.utils.MessageUtils; + +import java.awt.*; +import java.util.Map; + + +public class GuildMemberJoinListener extends ListenerAdapter { + @Override + public void onGuildMemberJoin(GuildMemberJoinEvent event) { + Member member = event.getMember(); + User user = UserService.getInstance().getOrCreateUser(member.getId()); + + WelcomeMessage welcomeMessage = RankService.getInstance().getRandomWelcomeMessage(user.getRank()); + + TextChannel channel = event.getGuild().getTextChannelById(Configuration.getInstance().getDotenv().get("WELCOME_CHANNEL", "0")); + String description = MessageUtils.insertPlaceholders(welcomeMessage.getMessage(), Map.of( + "username", member.getEffectiveName(), + "rank", user.getRank().getName() + )); + + Role role = event.getGuild().getRoleById(user.getRank().getDiscordId()); + Color color = new Color(0, 0, 0); + + if (role != null) { + event.getGuild().addRoleToMember(member, role).queue(); + color = role.getColor(); + } + + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle("Bienvenue sur le serveur " + event.getGuild().getName() + " !") + .setDescription(description) + .setThumbnail(member.getUser().getAvatarUrl()) + .setTimestamp(event.getMember().getTimeJoined()) + .setColor(color) + ; + + + if (channel != null) { + channel.sendMessageEmbeds(embedBuilder.build()).queue(); + } + + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/listeners/ReadyListener.java b/src/main/java/org/camelia/studio/gachamelia/listeners/ReadyListener.java new file mode 100644 index 0000000..5a14270 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/listeners/ReadyListener.java @@ -0,0 +1,16 @@ +package org.camelia.studio.gachamelia.listeners; + +import net.dv8tion.jda.api.events.session.ReadyEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReadyListener extends ListenerAdapter { + private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class); + + + @Override + public void onReady(ReadyEvent event) { + logger.info("Connecté en tant que {}", event.getJDA().getSelfUser().getAsTag()); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/listeners/SlashCommandListener.java b/src/main/java/org/camelia/studio/gachamelia/listeners/SlashCommandListener.java new file mode 100644 index 0000000..79fe364 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/listeners/SlashCommandListener.java @@ -0,0 +1,22 @@ +package org.camelia.studio.gachamelia.listeners; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.camelia.studio.gachamelia.managers.CommandManager; +import org.jetbrains.annotations.NotNull; + +public class SlashCommandListener extends ListenerAdapter { + private final CommandManager commandManager; + + public SlashCommandListener() { + commandManager = new CommandManager(); + commandManager.registerCommands(); + } + + + @Override + public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { + event.deferReply().setEphemeral(true).queue(); + commandManager.handleCommand(event.getName(), event); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/managers/CommandManager.java b/src/main/java/org/camelia/studio/gachamelia/managers/CommandManager.java new file mode 100644 index 0000000..073e9db --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/managers/CommandManager.java @@ -0,0 +1,63 @@ +package org.camelia.studio.gachamelia.managers; + + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.Commands; +import org.camelia.studio.gachamelia.Gachamelia; +import org.camelia.studio.gachamelia.interfaces.ISlashCommand; +import org.camelia.studio.gachamelia.utils.Configuration; +import org.camelia.studio.gachamelia.utils.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +public class CommandManager { + private final List slashCommands; + private final Logger logger = LoggerFactory.getLogger(CommandManager.class); + + public CommandManager() { + slashCommands = ReflectionUtils.loadClasses( + "org.camelia.studio.gachamelia.commands", + ISlashCommand.class + ); + } + + public void registerCommands() { + Guild guild = Gachamelia + .getJda() + .getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID")); + + if (guild == null) { + logger.error("Impossible de trouver le serveur Discord"); + return; + } + + guild + .updateCommands() + .addCommands( + slashCommands + .stream() + .map( + (cmd) -> Commands.slash(cmd.getName(), cmd.getDescription()).addOptions(cmd.getOptions()) + ) + .toList() + ) + .queue(); + + + logger.info("Enregistrement de {} commandes", slashCommands.size()); + } + + public void handleCommand(String commandName, SlashCommandInteractionEvent event) { + for (ISlashCommand command : slashCommands) { + if (command.getName().equals(commandName)) { + command.execute(event); + return; + } + } + event.getHook().editOriginal("Commande inconnue").queue(); + } +} + diff --git a/src/main/java/org/camelia/studio/gachamelia/managers/ListenerManager.java b/src/main/java/org/camelia/studio/gachamelia/managers/ListenerManager.java new file mode 100644 index 0000000..b066a18 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/managers/ListenerManager.java @@ -0,0 +1,33 @@ +package org.camelia.studio.gachamelia.managers; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.camelia.studio.gachamelia.listeners.GuildMemberJoinListener; +import org.camelia.studio.gachamelia.listeners.SlashCommandListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class ListenerManager { + private final List listener; + private final Logger logger = LoggerFactory.getLogger(ListenerManager.class.getName()); + public ListenerManager() { + listener = new ArrayList<>(); + + addListener(new SlashCommandListener()); + addListener(new GuildMemberJoinListener()); + } + public void registerListeners(JDA jda) { + for (ListenerAdapter listenerAdapter : listener) { + jda.addEventListener(listenerAdapter); + + logger.info("Listener {} enregistré !", listenerAdapter.getClass().getSimpleName()); + } + } + + private void addListener(ListenerAdapter listenerAdapter) { + this.listener.add(listenerAdapter); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/models/Rank.java b/src/main/java/org/camelia/studio/gachamelia/models/Rank.java new file mode 100644 index 0000000..e1a1d7e --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/models/Rank.java @@ -0,0 +1,94 @@ +package org.camelia.studio.gachamelia.models; + +import jakarta.persistence.*; +import org.camelia.studio.gachamelia.interfaces.IEntity; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.LocalDateTime; +import java.util.List; + +@Entity +@Table(name = "ranks") +public class Rank implements IEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "discordId", nullable = false, length = 255, unique = true) + private String discordId; + + @Column(nullable = false) + private String name; + + @Column(nullable = false) + private int percentage; + + @OneToMany(mappedBy = "rank") + private List users; + + @OneToMany(mappedBy = "rank") + private List welcomeMessages; + + @CreationTimestamp + @Column(name = "createdAt") + private LocalDateTime createdAt; + + @UpdateTimestamp + @Column(name = "updatedAt") + private LocalDateTime updatedAt; + + + public Rank(String discordId, String name, int percentage) { + this.discordId = discordId; + this.name = name; + this.percentage = percentage; + } + + public Rank() { + } + + public Long getId() { + return id; + } + + public String getDiscordId() { + return discordId; + } + + public void setDiscordId(String discordId) { + this.discordId = discordId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPercentage() { + return percentage; + } + + public void setPercentage(int percentage) { + this.percentage = percentage; + } + + public List getUsers() { + return users; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public LocalDateTime getUpdatedAt() { + return updatedAt; + } + + public List getWelcomeMessages() { + return welcomeMessages; + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/models/User.java b/src/main/java/org/camelia/studio/gachamelia/models/User.java new file mode 100644 index 0000000..d0c769d --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/models/User.java @@ -0,0 +1,68 @@ +package org.camelia.studio.gachamelia.models; + +import jakarta.persistence.*; +import org.camelia.studio.gachamelia.interfaces.IEntity; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "users") +public class User implements IEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "discordId", nullable = false, unique = true) + private String discordId; + + @ManyToOne(fetch = FetchType.EAGER) + private Rank rank; + + @CreationTimestamp + @Column(name = "createdAt") + private LocalDateTime createdAt; + + @UpdateTimestamp + @Column(name = "updatedAt") + private LocalDateTime updatedAt; + + + public User() { + } + + public User(String discordId, Rank rank) { + this.discordId = discordId; + this.rank = rank; + } + + + public Long getId() { + return id; + } + + public String getDiscordId() { + return discordId; + } + + public void setDiscordId(String discordId) { + this.discordId = discordId; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public LocalDateTime getUpdatedAt() { + return updatedAt; + } + + public Rank getRank() { + return rank; + } + + public void setRank(Rank rank) { + this.rank = rank; + } +} \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/gachamelia/models/WelcomeMessage.java b/src/main/java/org/camelia/studio/gachamelia/models/WelcomeMessage.java new file mode 100644 index 0000000..617591a --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/models/WelcomeMessage.java @@ -0,0 +1,46 @@ +package org.camelia.studio.gachamelia.models; + +import jakarta.persistence.*; +import org.camelia.studio.gachamelia.interfaces.IEntity; + +@Entity +@Table(name = "welcome_messages") +public class WelcomeMessage implements IEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne + private Rank rank; + + @Column(nullable = false) + private String message; + + public WelcomeMessage() { + } + + public WelcomeMessage(Rank rank, String message) { + this.rank = rank; + this.message = message; + } + + public Long getId() { + return id; + } + + public Rank getRank() { + return rank; + } + + public void setRank(Rank rank) { + this.rank = rank; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/repossitories/RankRepository.java b/src/main/java/org/camelia/studio/gachamelia/repossitories/RankRepository.java new file mode 100644 index 0000000..961be83 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/repossitories/RankRepository.java @@ -0,0 +1,84 @@ +package org.camelia.studio.gachamelia.repossitories; + + +import org.camelia.studio.gachamelia.db.HibernateConfig; +import org.camelia.studio.gachamelia.models.Rank; +import org.camelia.studio.gachamelia.models.WelcomeMessage; +import org.hibernate.Session; +import org.hibernate.SessionFactory; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class RankRepository { + private final SessionFactory sessionFactory; + private static RankRepository instance; + + public static RankRepository getInstance() { + if (instance == null) { + instance = new RankRepository(); + } + + return instance; + } + + public RankRepository() { + this.sessionFactory = HibernateConfig.getSessionFactory(); + } + + public List findAll() { + try (Session session = sessionFactory.openSession()) { + return session.createQuery("FROM Rank", Rank.class).list(); + } + } + + public Rank findByName(String name) { + try (Session session = sessionFactory.openSession()) { + return session.createQuery("FROM User WHERE name = :name", Rank.class) + .setParameter("discordId", name) + .uniqueResult(); + } + } + + public Rank save(Rank rank) { + try (Session session = sessionFactory.openSession()) { + session.beginTransaction(); + session.persist(rank); + session.getTransaction().commit(); + return rank; + } + } + + public void update(Rank rank) { + try (Session session = sessionFactory.openSession()) { + session.beginTransaction(); + session.merge(rank); + session.getTransaction().commit(); + } + } + + public WelcomeMessage getRandomWelcomeMessage(Rank rank) { + try (Session session = sessionFactory.openSession()) { + session.beginTransaction(); + try { + // Recharger le rank avec ses messages + Rank refreshedRank = session.get(Rank.class, rank.getId()); + List welcomeMessages = refreshedRank.getWelcomeMessages(); + + if (welcomeMessages.isEmpty()) { + return null; + } + + WelcomeMessage message = welcomeMessages.get( + ThreadLocalRandom.current().nextInt(welcomeMessages.size()) + ); + + session.getTransaction().commit(); + return message; + } catch (Exception e) { + session.getTransaction().rollback(); + throw e; + } + } + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/repossitories/UserRepository.java b/src/main/java/org/camelia/studio/gachamelia/repossitories/UserRepository.java new file mode 100644 index 0000000..7912bc6 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/repossitories/UserRepository.java @@ -0,0 +1,57 @@ +package org.camelia.studio.gachamelia.repossitories; + + +import org.camelia.studio.gachamelia.db.HibernateConfig; +import org.camelia.studio.gachamelia.models.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; + +import java.util.List; + +public class UserRepository { + private final SessionFactory sessionFactory; + private static UserRepository instance; + + public static UserRepository getInstance() { + if (instance == null) { + instance = new UserRepository(); + } + + return instance; + } + + public UserRepository() { + this.sessionFactory = HibernateConfig.getSessionFactory(); + } + + public List findAll() { + try (Session session = sessionFactory.openSession()) { + return session.createQuery("FROM User", User.class).list(); + } + } + + public User findByDiscordId(String discordId) { + try (Session session = sessionFactory.openSession()) { + return session.createQuery("FROM User WHERE discordId = :discordId", User.class) + .setParameter("discordId", discordId) + .uniqueResult(); + } + } + + public User save(User user) { + try (Session session = sessionFactory.openSession()) { + session.beginTransaction(); + session.persist(user); + session.getTransaction().commit(); + return user; + } + } + + public void update(User user) { + try (Session session = sessionFactory.openSession()) { + session.beginTransaction(); + session.merge(user); + session.getTransaction().commit(); + } + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/services/RankService.java b/src/main/java/org/camelia/studio/gachamelia/services/RankService.java new file mode 100644 index 0000000..21aa605 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/services/RankService.java @@ -0,0 +1,56 @@ +package org.camelia.studio.gachamelia.services; + +import org.camelia.studio.gachamelia.models.Rank; +import org.camelia.studio.gachamelia.models.WelcomeMessage; +import org.camelia.studio.gachamelia.repossitories.RankRepository; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class RankService { + private static RankService instance; + + public static RankService getInstance() { + if (instance == null) { + instance = new RankService(); + } + + return instance; + } + + public Rank getOrCreateRank(String name, String discordId, int percentage) { + Rank rank = RankRepository.getInstance().findByName(name); + + if (rank == null) { + rank = new Rank(discordId, name, percentage); + RankRepository.getInstance().save(rank); + } + + return rank; + } + + public List getAllRanks() { + return RankRepository.getInstance().findAll(); + } + + public Rank getRandomRank() { + List ranks = RankRepository.getInstance().findAll(); + + int percentage = ThreadLocalRandom.current().nextInt(100); + int cumulativePercentage = 0; + + for (Rank rank : ranks) { + cumulativePercentage += rank.getPercentage(); + if (percentage <= cumulativePercentage) { + return rank; + } + } + + // Ne devrait jamais arriver + return null; + } + + public WelcomeMessage getRandomWelcomeMessage(Rank rank) { + return RankRepository.getInstance().getRandomWelcomeMessage(rank); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/services/UserService.java b/src/main/java/org/camelia/studio/gachamelia/services/UserService.java new file mode 100644 index 0000000..1c13d66 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/services/UserService.java @@ -0,0 +1,39 @@ +package org.camelia.studio.gachamelia.services; + +import org.camelia.studio.gachamelia.models.Rank; +import org.camelia.studio.gachamelia.models.User; +import org.camelia.studio.gachamelia.repossitories.UserRepository; + +import java.util.List; + +public class UserService { + private static UserService instance; + + public static UserService getInstance() { + if (instance == null) { + instance = new UserService(); + } + + return instance; + } + + public User getOrCreateUser(String discordId) { + User user = UserRepository.getInstance().findByDiscordId(discordId); + + if (user == null) { + Rank rank = RankService.getInstance().getRandomRank(); + user = new User(discordId, rank); + UserRepository.getInstance().save(user); + } + + return user; + } + + public List getAllUsers() { + return UserRepository.getInstance().findAll(); + } + + public void updateUser(User user) { + UserRepository.getInstance().update(user); + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/utils/Configuration.java b/src/main/java/org/camelia/studio/gachamelia/utils/Configuration.java new file mode 100644 index 0000000..061d494 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/utils/Configuration.java @@ -0,0 +1,23 @@ +package org.camelia.studio.gachamelia.utils; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Configuration { + private static Configuration instance; + private final Dotenv dotenv; + + public Configuration() { + this.dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + } + + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); + } + return instance; + } + + public Dotenv getDotenv() { + return dotenv; + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/utils/MessageUtils.java b/src/main/java/org/camelia/studio/gachamelia/utils/MessageUtils.java new file mode 100644 index 0000000..672d8c5 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/utils/MessageUtils.java @@ -0,0 +1,14 @@ +package org.camelia.studio.gachamelia.utils; + +import java.util.Map; + +public class MessageUtils { + + public static String insertPlaceholders(String message, Map placeholders) { + for (Map.Entry entry : placeholders.entrySet()) { + message = message.replace("%" + entry.getKey() + "%", entry.getValue()); + } + + return message; + } +} diff --git a/src/main/java/org/camelia/studio/gachamelia/utils/ReflectionUtils.java b/src/main/java/org/camelia/studio/gachamelia/utils/ReflectionUtils.java new file mode 100644 index 0000000..b730317 --- /dev/null +++ b/src/main/java/org/camelia/studio/gachamelia/utils/ReflectionUtils.java @@ -0,0 +1,105 @@ +package org.camelia.studio.gachamelia.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +public class ReflectionUtils { + private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class); + + /** + * Charge toutes les classes d'un type spécifique depuis un package + * + * @param packageName Le package à scanner + * @param targetType Le type de classe à charger + * @return Liste des instances des classes trouvées + */ + public static List loadClasses(String packageName, Class targetType) { + List instances = new ArrayList<>(); + + try { + // Convertit le nom du package en chemin + String path = packageName.replace('.', '/'); + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + + // Récupère toutes les ressources du package + var resources = classLoader.getResources(path); + + // Parcourt toutes les ressources trouvées + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + File directory = new File(resource.toURI()); + + // Charge les classes du répertoire et ses sous-répertoires + scanDirectory(directory, packageName, targetType, instances); + } + + } catch (Exception e) { + logger.error("Erreur lors du scan du package {} : {}", packageName, e.getMessage()); + } + + return instances; + } + + /** + * Scanne récursivement un répertoire pour trouver les classes + */ + private static void scanDirectory(File directory, String packageName, Class targetType, List instances) { + // Vérifie si le répertoire existe + if (!directory.exists()) { + return; + } + + // Récupère tous les fichiers du répertoire + File[] files = directory.listFiles(); + if (files != null) { + for (File file : files) { + // Si c'est un répertoire, on le scanne récursivement + if (file.isDirectory()) { + scanDirectory( + file, + packageName + "." + file.getName(), + targetType, + instances + ); + } + // Si c'est un fichier .class, on essaie de le charger + else if (file.getName().endsWith(".class")) { + loadClass(packageName, file.getName(), targetType, instances); + } + } + } + } + + /** + * Charge une classe spécifique + */ + @SuppressWarnings("unchecked") + private static void loadClass(String packageName, String fileName, Class targetType, List instances) { + try { + // Convertit le nom de fichier en nom de classe + String className = packageName + '.' + fileName.substring(0, fileName.length() - 6); + Class clazz = Class.forName(className); + + // Vérifie si la classe correspond au type recherché + if (targetType.isAssignableFrom(clazz) && + !clazz.isInterface() && + !Modifier.isAbstract(clazz.getModifiers())) { + + // Crée une instance de la classe + T instance = (T) clazz.getDeclaredConstructor().newInstance(); + instances.add(instance); + + logger.debug("Classe chargée : {}", className); + } + + } catch (Exception e) { + logger.error("Erreur lors du chargement d'une classe : {}", e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..c9155dc --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + %d{HH:mm:ss.SSS} %boldCyan(%-34.-34thread) %red(%10.10X{jda.shard}) %boldGreen(%-15.-15logger{0}) %highlight(%-6level) %msg%n + + + + + + + + + \ No newline at end of file