feat: initial commit (stole codebase from solarcore)

This commit is contained in:
hexlocation 2025-04-18 18:20:03 +02:00
parent 01aeefaaa3
commit 739abce169
32 changed files with 428 additions and 989 deletions

3
.gitignore vendored
View file

@ -1,2 +1,5 @@
target/
test_server/
.gradle
build/
server/

View file

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>BUKKIT</platformType>
</autoDetectTypes>
<projectReimportVersion>1</projectReimportVersion>
</configuration>
</facet>
</component>
</module>

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# CivilCore (v2)
PaperMC plugin written in Kotlin for civil.iwakura.rip.

34
build.gradle.kts Normal file
View file

@ -0,0 +1,34 @@
group = "rip.iwakura"
version = "0.1.0"
plugins {
java
kotlin("jvm") version "2.1.10"
id("com.github.johnrengelman.shadow") version "7.1.2"
id("de.eldoria.plugin-yml.paper") version "0.7.1"
}
repositories {
mavenCentral()
maven {
name = "papermc"
url = uri("https://repo.papermc.io/repository/maven-public/")
}
}
paper {
main = "rip.iwakura.civil.Core"
authors = listOf("hex", "grng")
apiVersion = "1.21"
}
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
library("com.google.code.gson", "gson", "2.10.1") // All platform plugins
shadow("org.jetbrains.kotlin:kotlin-stdlib:2.1.10")
}
kotlin {
jvmToolchain(21)
}

View file

@ -1,4 +0,0 @@
mvn clean package dependency:copy -DskipTests -DmcVersion=1.21 -DoutputDirectory=test_server/plugins
cd test_server
java -jar server.jar -nogui
cd ../

2
db.ps1
View file

@ -1,2 +0,0 @@
docker-compose up
docker ps

View file

@ -1,8 +0,0 @@
version: '3'
services:
civil_test_db:
environment:
- POSTGRES_PASSWORD=TEST123
image: postgres:16.3
ports:
- 5432:5432

5
gradle.properties Normal file
View file

@ -0,0 +1,5 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
org.gradle.configuration-cache=true

View file

@ -0,0 +1,8 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
[versions]
kotlin-gradle-plugin = "2.0.20"
[libraries]
kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin-gradle-plugin" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
gradlew vendored Normal file
View file

@ -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" "$@"

94
gradlew.bat vendored Normal file
View file

@ -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

BIN
kls_database.db Normal file

Binary file not shown.

106
pom.xml
View file

@ -1,106 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<mcVersion>1.21</mcVersion> <!-- default mc version -->
</properties>
<groupId>rip.iwakura</groupId>
<artifactId>CivilCore</artifactId>
<version>0.1c</version>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>5.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>club.minnced</groupId>
<artifactId>discord-webhooks</artifactId>
<version>0.1.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
<scope>compile</scope>
</dependency>
<!-- spigot api -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${mcVersion}-R0.1-SNAPSHOT</version>
</dependency>
<!-- plugin annotations -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>plugin-annotations</artifactId>
<version>1.2.3-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<overWrite>true</overWrite>
</artifactItem>
</artifactItems>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -1,9 +0,0 @@
if (-not (Test-Path -Path test_server)) {
New-Item -ItemType Directory -Path test_server
}
# mvn clean package dependency:copy -DskipTests -DoutputDirectory=test_server/plugins
Set-Location -Path test_server
java -jar server.jar -nogui
Set-Location -Path ..

13
settings.gradle.kts Normal file
View file

@ -0,0 +1,13 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.11.1/userguide/multi_project_builds.html in the Gradle documentation.
*/
plugins {
// Apply the foojay-resolver plugin to allow automatic download of JDKs
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "civil-core"

View file

@ -1,50 +0,0 @@
package rip.iwakura.civilcore;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.WorldCreator;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
import rip.iwakura.civilcore.commands.TeamChatCommand;
import rip.iwakura.civilcore.commands.TeamCommand;
import rip.iwakura.civilcore.discord.Discord;
public class CivilCore extends JavaPlugin {
public Database db = new Database();
public Discord bot;
public ArrayList<Player> teamChatRegister = new ArrayList<>();
@Override
public void onEnable() {
this.saveDefaultConfig();
this.bot = new Discord(getConfig().getString("discord.token"), getConfig().getString("discord.channel"), this);
this.bot.initialize();
if (Bukkit.getWorld("court") == null) {
new WorldCreator("court").createWorld();
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
db.connect(this.getConfig().getString("database.url"));
} catch (SQLException e) {
e.printStackTrace();
}
getServer().getPluginManager().registerEvents(new PlayerHandler(this), this);
getServer().getPluginManager().registerEvents(new Court(), this);
this.getCommand("team").setExecutor(new TeamCommand(this));
this.getCommand("court").setExecutor(new Court());
this.getCommand("tc").setExecutor(new TeamChatCommand(this));
}
}

View file

@ -1,89 +0,0 @@
package rip.iwakura.civilcore;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
public class Court implements Listener,CommandExecutor{
private World court_world = Bukkit.getWorld("court");
private Location court_location = new Location(court_world, 4.5, 70.0, 0.5, -90f, 1.0f);
@EventHandler
public void PlayerPlaceWater(PlayerBucketEmptyEvent e) {
Player p = (Player) e.getPlayer();
if (!p.getLocation().getWorld().getName().equals("court")) return;
e.setCancelled(true);
}
@EventHandler
public void PlayerHurt(EntityDamageEvent e) {
if (!(e.getEntity() instanceof Player)) return;
Player p = (Player) e.getEntity();
if (!p.getLocation().getWorld().getName().equals("court")) return;
e.setCancelled(true);
if (e.getCause() == DamageCause.VOID) {
p.teleport(court_location);
return;
}
}
@EventHandler
public void PlayerBreak(BlockBreakEvent e) {
if (e.getPlayer().isOp()) return;
if (e.getBlock().getWorld().getName().equals(court_world.getName())) e.setCancelled(true);
}
@EventHandler
public void PlayerPlace(BlockPlaceEvent e) {
if (e.getPlayer().isOp()) return;
if (e.getBlock().getWorld().getName().equals(court_world.getName())) e.setCancelled(true);
}
@EventHandler
public void PlayerBurn(BlockBurnEvent e) {
if (e.getBlock().getWorld().getName().equals(court_world.getName())) e.setCancelled(true);
}
@EventHandler
public void FireSpread(BlockSpreadEvent e) {
if (e.getBlock().getWorld().getName().equals(court_world.getName())) e.setCancelled(true);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Non-player type.");
return true;
}
Player p = (Player) sender;
switch (args[0]) {
case "enter":
p.teleport(court_location);
break;
case "leave":
Location loc = p.getBedSpawnLocation();
if (loc == null) {
loc = Bukkit.getWorld("world").getSpawnLocation();
}
p.teleport(loc);
break;
}
return true;
}
}

View file

@ -1,188 +0,0 @@
package rip.iwakura.civilcore;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import rip.iwakura.civilcore.types.DbPlayer;
import rip.iwakura.civilcore.types.Team;
public class Database {
public ArrayList<DbPlayer> players = new ArrayList<DbPlayer>();
public ArrayList<Team> teams = new ArrayList<Team>();
private Connection c = null;
public boolean tableExists(String table) throws SQLException {
if (c.getMetaData().getTables(null, null, table, null).next()) {
return true;
}
return false;
}
public DbPlayer getPlayerByName(String name) {
List<DbPlayer> filtered = players.stream().filter(
s -> s.name.equals(name))
.collect(Collectors.toList());
if (filtered.isEmpty()) return null;
return filtered.getFirst();
}
public Team getTeamByName(String name) {
List<Team> filtered = teams.stream().filter(
s -> s.name.equals(name))
.collect(Collectors.toList());
if (filtered.isEmpty()) return null;
return filtered.getFirst();
}
public void update(String sql) throws SQLException {
Statement stmt = c.createStatement();
stmt.executeUpdate(sql);
stmt.close();
}
public void addPlayerToTeam(Team team, DbPlayer player) throws SQLException {
String sql = "UPDATE players SET TEAM_ID = ? WHERE name = ?; ";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setInt(1, team.id);
stmt.setString(2, player.name);
stmt.executeUpdate();
stmt.close();
refreshPlayers();
}
public void refreshTeams() throws SQLException {
teams.clear();
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM teams;");
while (rs.next()) {
String name = rs.getString("name");
String prefix = rs.getString("prefix");
int id = rs.getInt("team_id");
Team team = new Team(name,prefix,id);
teams.add(team);
}
stmt.close();
rs.close();
}
public List<DbPlayer> getPlayersInTeam(String team_name) {
List<DbPlayer> filtered = players.stream().filter(
s -> {
if (s.team.name == null) return false;
return s.team.name.equals(team_name);
})
.collect(Collectors.toList());
if(filtered.isEmpty()) return null;
return filtered;
}
public void refreshPlayers() throws SQLException {
players.clear();
String sql = "SELECT players.NAME AS player_name, teams.NAME AS team_name, teams.TEAM_ID as t_team_id, teams.PREFIX AS team_prefix " +
"FROM players LEFT JOIN teams ON players.TEAM_ID = teams.TEAM_ID";
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String p_name = rs.getString("player_name");
String t_name = rs.getString("team_name");
int t_id = rs.getInt("t_team_id");
String t_prefix = rs.getString("team_prefix");
Team team = new Team(t_name, t_prefix, t_id);
DbPlayer player = new DbPlayer(p_name, team);
players.add(player);
}
stmt.close();
rs.close();
}
public void insertPlayer(DbPlayer player) throws SQLException {
String sql = "INSERT INTO players (NAME,TEAM_ID) " +
"VALUES(?, ?);";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, player.name);
if(player.team != null) {
stmt.setInt(2, player.team.id);
} else {
stmt.setNull(2, Types.NULL);
}
stmt.executeUpdate();
stmt.close();
refreshPlayers();
}
public void insertTeam(Team team) throws SQLException {
String sql = "INSERT INTO teams (NAME,PREFIX) " +
"VALUES(?, ?);";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setString(1, team.name);
stmt.setString(2, team.prefix);
stmt.executeUpdate();
stmt.close();
refreshTeams();
}
public void connect(String url) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url);
} catch (Exception e) {
e.printStackTrace();
Bukkit.getLogger().info("Failed to connect to the database.");
Bukkit.getServer().getPluginManager().disablePlugin(new CivilCore());
return;
}
Bukkit.getLogger().info("Connected to the database.");
if (!tableExists("teams")) {
String sql = "CREATE TABLE teams " +
"(TEAM_ID SERIAL PRIMARY KEY," +
" NAME TEXT NOT NULL," +
" PREFIX TEXT NOT NULL)";
update(sql);
}
if (!tableExists("players")) {
String sql = "CREATE TABLE players " +
"(NAME TEXT PRIMARY KEY NOT NULL," +
" TEAM_ID INT, " +
" CONSTRAINT TEAM" +
" FOREIGN KEY(TEAM_ID)" +
" REFERENCES teams(TEAM_ID))";
update(sql);
}
refreshTeams();
refreshPlayers();
Bukkit.getLogger().info("Database has been initialized.");
}
}

View file

@ -1,72 +0,0 @@
package rip.iwakura.civilcore;
import java.sql.SQLException;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import net.md_5.bungee.api.ChatColor;
import rip.iwakura.civilcore.types.DbPlayer;
public class PlayerHandler implements Listener {
private final CivilCore civilCore;
public PlayerHandler(CivilCore civilCore) {
this.civilCore = civilCore;
}
@EventHandler
public void PlayerChat(AsyncPlayerChatEvent e) {
e.setCancelled(true);
Player p = e.getPlayer();
String player_name = p.getName();
boolean inTeamChat = civilCore.teamChatRegister.contains(p);
DbPlayer dbPlayer = civilCore.db.getPlayerByName(player_name);
String prefix = (inTeamChat ? ChatColor.DARK_GREEN + "TEAM >" + ChatColor.RESET : "")
+ (dbPlayer.team.prefix == null ?
"" :
ChatColor.translateAlternateColorCodes('&', inTeamChat ? "" : "[" + dbPlayer.team.prefix + "]"));
String message = String.format("%s %s: %s", prefix, player_name, e.getMessage());
if (!inTeamChat) {
Bukkit.broadcastMessage(message);
civilCore.bot.sendMessage(e);
} else {
List<DbPlayer> players = civilCore.db.getPlayersInTeam(dbPlayer.team.name);
if (players == null) return;
for (DbPlayer team_dbp : players) {
Player team_p = Bukkit.getPlayer(team_dbp.name);
if (team_p == null) continue;
team_p.sendMessage(message);
}
}
}
@EventHandler
public void PlayerJoinEvent(PlayerJoinEvent e) {
Player p = e.getPlayer();
String player_name = p.getName();
if(civilCore.db.getPlayerByName(player_name) == null) {
DbPlayer dbPlayer = new DbPlayer(p.getName(), null);
try {
civilCore.db.insertPlayer(dbPlayer);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}

View file

@ -1,64 +0,0 @@
package rip.iwakura.civilcore;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import net.md_5.bungee.api.ChatColor;
public class Utils {
private static String buffer = "";
private static void finishBuffer(ArrayList<String> args) {
args.add(buffer);
buffer = "";
}
public static void exceptionHandler(Exception e, CommandSender sender) {
sender.sendMessage(ChatColor.RED + "Failed to execute command: " + e.getMessage());
}
public static ArrayList<String> parser(String[] original_args) {
ArrayList<String> args = new ArrayList<String>();
String joined_args = String.join(" ", original_args);
boolean inColon = false;
char lastCharacter = ' ';
for (int i = 0; i < joined_args.length(); i++) {
char currentCharacter = joined_args.charAt(i);
switch (currentCharacter) {
case '"':
if (!inColon) {
inColon = true;
} else {
inColon = false;
finishBuffer(args);
}
break;
case ' ':
if (!inColon && lastCharacter != '"') {
finishBuffer(args);
break;
}
if (lastCharacter != '"') buffer += " ";
break;
default:
buffer+=currentCharacter;
if (i == joined_args.length() - 1) {
finishBuffer(args);
}
break;
}
lastCharacter = currentCharacter;
}
if (inColon) return null;
return args;
}
}

View file

@ -1,83 +0,0 @@
package rip.iwakura.civilcore.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
import org.jetbrains.annotations.NotNull;
import rip.iwakura.civilcore.Utils;
import rip.iwakura.civilcore.CivilCore;
import rip.iwakura.civilcore.types.DbPlayer;
import java.util.List;
import java.util.Objects;
public class TeamChatCommand implements CommandExecutor {
private final CivilCore civilCore;
public TeamChatCommand(CivilCore civilCore) {
this.civilCore = civilCore;
}
private String getPrefix(String name, boolean inTeamChat) {
DbPlayer dbPlayer = civilCore.db.getPlayerByName(name);
return (inTeamChat ? ChatColor.DARK_GREEN + "TEAM >" + ChatColor.RESET : "")
+ (dbPlayer.team.prefix == null ?
"" :
ChatColor.translateAlternateColorCodes('&', inTeamChat ? "" : "[" + dbPlayer.team.prefix + "]"));
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
args = Objects.requireNonNull(Utils.parser(args)).toArray(new String[0]);
if (!(sender instanceof Player p)) return true;
if (args.length == 0) {
if (civilCore.teamChatRegister.contains(p)) {
civilCore.teamChatRegister.remove(p);
p.sendMessage(ChatColor.GREEN + "You are now in the " + ChatColor.GOLD + "GLOBAL" + ChatColor.GREEN + " channel");
} else {
civilCore.teamChatRegister.add(p);
p.sendMessage(ChatColor.GREEN + "You are now in the " + ChatColor.GOLD + "TEAM" + ChatColor.GREEN + " channel");
}
return true;
}
String message = String.join(" ", args);
String player_name = p.getName();
boolean inTeamChat = civilCore.teamChatRegister.contains(p);
DbPlayer dbPlayer = civilCore.db.getPlayerByName(player_name);
if (inTeamChat) {
// Send message to global chat
civilCore.teamChatRegister.remove(p);
String formatted = String.format("%s%s: %s", getPrefix(player_name, false) + " ", player_name, message);
Bukkit.broadcastMessage(formatted);
civilCore.bot.sendMessage(p, message);
civilCore.teamChatRegister.add(p);
} else {
// Send message to team chat
civilCore.teamChatRegister.add(p);
String formatted = String.format("%s%s: %s", getPrefix(player_name, true) + " ", player_name, message);
List<DbPlayer> players = civilCore.db.getPlayersInTeam(dbPlayer.team.name);
if (players == null) return true;
for (DbPlayer team_dbp : players) {
Player team_p = Bukkit.getPlayer(team_dbp.name);
if (team_p == null) continue;
team_p.sendMessage(formatted);
}
civilCore.teamChatRegister.remove(p);
}
return true;
}
}

View file

@ -1,111 +0,0 @@
package rip.iwakura.civilcore.commands;
import java.sql.SQLException;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import net.md_5.bungee.api.ChatColor;
import rip.iwakura.civilcore.Utils;
import rip.iwakura.civilcore.CivilCore;
import rip.iwakura.civilcore.types.DbPlayer;
import rip.iwakura.civilcore.types.Team;
public class TeamCommand implements CommandExecutor {
private CivilCore civilCore = null;
public TeamCommand(CivilCore civilCore) {
this.civilCore = civilCore;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
args = Utils.parser(args).toArray(new String[0]);
if(args.length == 0) {
sender.sendMessage(ChatColor.RED + "Usage: /team <create | destroy | add | remove | list> [options]");
return true;
};
switch (args[0]) {
case "list":
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: /team list <teams | players>");
return true;
}
switch (args[1]) {
case "players":
for (DbPlayer dbPlayer : civilCore.db.players) {
if (dbPlayer.team != null) sender.sendMessage(ChatColor.GREEN + String.format("%s belonging to team %s", dbPlayer.name, dbPlayer.team.name));
if (dbPlayer.team == null) sender.sendMessage(ChatColor.GREEN + String.format("%s does not belong to any team.", dbPlayer.name));
}
return true;
case "teams":
for (Team team : civilCore.db.teams) {
sender.sendMessage(ChatColor.GREEN + String.format("%s with prefix %s", team.name, ChatColor.translateAlternateColorCodes('&', "&r" + team.prefix)));
}
return true;
default:
sender.sendMessage(ChatColor.RED + "Usage: /team list <teams | players>");
return true;
}
case "create":
if(args.length < 3) {
sender.sendMessage(ChatColor.RED + "Usage: /team create <name> <prefix>");
return true;
};
Team team = new Team(args[1], args[2], null);
try {
civilCore.db.insertTeam(team);
sender.sendMessage(ChatColor.GREEN + String.format("Successfully made team %s with prefix %s", args[1], ChatColor.translateAlternateColorCodes('&', "&r" + args[2])));
} catch (Exception e) {
e.printStackTrace();
Utils.exceptionHandler(e, sender);
}
break;
case "add":
if(args.length < 3) {
sender.sendMessage(ChatColor.RED + "Usage: /team add <player> <team name>");
return true;
};
Team found_team = civilCore.db.getTeamByName(args[2]);
DbPlayer dbPlayer = civilCore.db.getPlayerByName(args[1]);
if (found_team == null) {
sender.sendMessage(ChatColor.RED + "The team you are referencing does not exist.");
return true;
}
String success_msg = ChatColor.GREEN + String.format("Successfully added %s to team %s.", args[1], args[2]);
if(dbPlayer == null) {
dbPlayer = new DbPlayer(args[1], found_team);
try {
civilCore.db.insertPlayer(dbPlayer);
sender.sendMessage(success_msg);
} catch (Exception e) {
e.printStackTrace();
Utils.exceptionHandler(e, sender);
}
return true;
}
try {
civilCore.db.addPlayerToTeam(found_team, dbPlayer);
sender.sendMessage(success_msg);
} catch (Exception e) {
e.printStackTrace();
Utils.exceptionHandler(e, sender);
}
break;
}
return true;
}
}

View file

@ -1,108 +0,0 @@
package rip.iwakura.civilcore.discord;
import java.util.EnumSet;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.checkerframework.common.reflection.qual.GetConstructor;
import club.minnced.discord.webhook.WebhookClient;
import club.minnced.discord.webhook.WebhookClientBuilder;
import club.minnced.discord.webhook.send.WebhookMessage;
import club.minnced.discord.webhook.send.WebhookMessageBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import rip.iwakura.civilcore.CivilCore;
import net.dv8tion.jda.api.events.session.ReadyEvent;
import rip.iwakura.civilcore.types.DbPlayer;
public class Discord extends ListenerAdapter {
private String token;
private CivilCore civilCore;
public String channelId;
private TextChannel channel;
private WebhookClient webhook;
public JDA bot;
private EnumSet<GatewayIntent> intents = EnumSet.of(GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT, GatewayIntent.GUILD_WEBHOOKS);
public Discord(String token, String channelId, CivilCore civilCore){
this.civilCore = civilCore;
this.channelId = channelId;
this.token = token;
}
public void initialize() {
this.bot = JDABuilder.createLight(token, intents)
.addEventListeners(new MessageReceive(civilCore))
.addEventListeners(this)
.build();
}
public void sendMessage(AsyncPlayerChatEvent e) {
DbPlayer dbPlayer = civilCore.db.getPlayerByName(e.getPlayer().getName());
String prefix = (dbPlayer.team.prefix == null ?
"" :
"[" + dbPlayer.team.prefix + "]");
String player_name = e.getPlayer().getName();
WebhookMessageBuilder builder = new WebhookMessageBuilder()
.setUsername(prefix + " " + player_name)
.setAvatarUrl(String.format("https://mc-heads.net/avatar/%s", player_name))
.setContent(e.getMessage());
webhook.send(builder.build());
//channel.sendMessage(String.format("%s: %s", e.getPlayer().getName(), e.getMessage())).complete();
}
public void sendMessage(Player p, String message) {
DbPlayer dbPlayer = civilCore.db.getPlayerByName(p.getName());
String prefix = (dbPlayer.team.prefix == null ?
"" :
"[" + dbPlayer.team.prefix + "]");
WebhookMessageBuilder builder = new WebhookMessageBuilder()
.setUsername(prefix + " " + p.getName())
.setAvatarUrl(String.format("https://mc-heads.net/avatar/%s", p.getName()))
.setContent(message);
webhook.send(builder.build());
//channel.sendMessage(String.format("%s: %s", p.getName(), message)).complete();
}
public void sendMessage(String message, String name) {
DbPlayer dbPlayer = civilCore.db.getPlayerByName(name);
String prefix = (dbPlayer.team.prefix == null ?
"" :
"[" + dbPlayer.team.prefix + "]");
WebhookMessageBuilder builder = new WebhookMessageBuilder()
.setUsername(prefix + " " + name)
.setAvatarUrl(String.format("https://mc-heads.net/avatar/%s", name))
.setContent(message);
webhook.send(builder.build());
//channel.sendMessage(String.format("%s: %s", name, message)).complete();
}
@Override
public void onReady(ReadyEvent e) {
this.channel = bot.getTextChannelById(channelId);
String webhook_token = civilCore.getConfig().getString("discord.webhook.token");
if (webhook_token != null) {
Long webhook_id = Long.parseLong(civilCore.getConfig().getString("discord.webhook.id"));
this.webhook = new WebhookClientBuilder(webhook_id, webhook_token).build();
} else {
channel.createWebhook("CivilBot").queue((hook) -> {
civilCore.getConfig().set("discord.webhook.id", hook.getId());
civilCore.getConfig().set("discord.webhook.token", hook.getToken());
civilCore.saveConfig();
this.webhook = new WebhookClientBuilder(Long.parseLong(hook.getId()), hook.getToken()).build();
});
}
}
}

View file

@ -1,22 +0,0 @@
package rip.iwakura.civilcore.discord;
import org.bukkit.Bukkit;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.md_5.bungee.api.ChatColor;
import rip.iwakura.civilcore.CivilCore;
public class MessageReceive extends ListenerAdapter {
private CivilCore civilCore;
public MessageReceive (CivilCore civilCore) {
this.civilCore = civilCore;
}
@Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) return;
if(e.getChannel().getId().equals(civilCore.bot.channelId)) Bukkit.broadcastMessage(String.format("%sDiscord%s %s: %s", ChatColor.BLUE, ChatColor.RESET, e.getAuthor().getName(), e.getMessage()));
}
}

View file

@ -1,7 +0,0 @@
package rip.iwakura.civilcore.types;
import org.bukkit.command.CommandSender;
public interface CoreCommand {
public boolean run(CommandSender sender);
}

View file

@ -1,17 +0,0 @@
package rip.iwakura.civilcore.types;
/*
* Player Type
* @String name
* @Team team
*/
public class DbPlayer {
public Team team = null;
public String name = null;
public DbPlayer(String name, Team team) {
this.name = name;
this.team = team;
}
}

View file

@ -1,19 +0,0 @@
package rip.iwakura.civilcore.types;
/*
* Team Type
* @string name
* @string prefix
*/
public class Team {
public String prefix = null;
public String name = null;
public Integer id = null;
public Team(String name, String prefix, Integer id) {
this.prefix = prefix;
this.name = name;
this.id = id;
}
}

View file

@ -0,0 +1,9 @@
package rip.iwakura.civil
import org.bukkit.plugin.java.JavaPlugin
class Core: JavaPlugin() {
override fun onEnable() {
logger.info { "Hello there! We are booting up..." }
}
}

View file

@ -1,17 +0,0 @@
main: rip.iwakura.civilcore.CivilCore
name: CivilCore
version: 0.1
description: Core plugin for the CivilWars SMP
api-version: 1.21
author: hex
commands:
team:
description: Team Manager
usage: /<command> <create|destroy|add|remove>
permission: "civil.teams"
court:
description: Court Manager
usage: /<command> <enter|leave>
tc:
description: Team Chat
usage: /<command>