diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..941d18c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{kt,kts}] +ktlint_code_style = intellij_idea + +[*{.yml,yaml}] +indent_style = space +indent_size = 2 diff --git a/.github/workflows/build-workflow.yml b/.github/workflows/build-workflow.yml new file mode 100644 index 0000000..fe22014 --- /dev/null +++ b/.github/workflows/build-workflow.yml @@ -0,0 +1,37 @@ +name: Build +on: + workflow_call: + outputs: + version: + description: Built version + value: ${{ jobs.build.outputs.version }} + +jobs: + build: + name: Gradle Build + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 21 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Gradle Build + run: ./gradlew build shadowJar + - name: Get Version + id: version + run: echo "version=$(./gradlew --console plain --quiet currentVersion -Prelease.quiet)" >> $GITHUB_OUTPUT + - name: Upload build + uses: actions/upload-artifact@v4 + with: + name: build + path: build/libs/*.jar + retention-days: 7 + if-no-files-found: error diff --git a/.github/workflows/create-version.yml b/.github/workflows/create-version.yml new file mode 100644 index 0000000..2cac3ac --- /dev/null +++ b/.github/workflows/create-version.yml @@ -0,0 +1,42 @@ +name: Create Version + +on: + workflow_dispatch: + inputs: + versionIncrementer: + type: choice + description: Override the default version incrementer according to https://axion-release-plugin.readthedocs.io/en/latest/configuration/version/#incrementing + default: default + options: + - default + - incrementPatch + - incrementMinor + - incrementMajor + - incrementPrerelease + +jobs: + release: + name: Gradle Release + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ssh-key: "${{ secrets.COMMIT_KEY }}" + fetch-depth: 0 + - uses: webfactory/ssh-agent@v0.9.1 + with: + ssh-private-key: ${{ secrets.COMMIT_KEY }} + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Gradle Release + if: ${{ inputs.versionIncrementer == 'default' }} + run: ./gradlew release + - name: Gradle Release w/ Increment Override + if: ${{ inputs.versionIncrementer != 'default' }} + run: ./gradlew release -Prelease.versionIncrementer=${{ inputs.versionIncrementer }} diff --git a/.github/workflows/pr-workflow.yml b/.github/workflows/pr-workflow.yml index 6661a7c..28d2147 100644 --- a/.github/workflows/pr-workflow.yml +++ b/.github/workflows/pr-workflow.yml @@ -3,23 +3,4 @@ on: pull_request jobs: build: - name: Gradle Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-java@v1 - with: - java-version: 11 - - uses: actions/cache@v1 - with: - path: ~/.gradle/wrapper - key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties') }} - - uses: actions/cache@v1 - with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-caches-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties') }} - restore-keys: | - ${{ runner.os }}-gradle-caches- - - uses: eskatos/gradle-command-action@v1 - with: - arguments: build + uses: ./.github/workflows/build-workflow.yml diff --git a/.github/workflows/publish-workflow.yml b/.github/workflows/publish-workflow.yml new file mode 100644 index 0000000..2af66dc --- /dev/null +++ b/.github/workflows/publish-workflow.yml @@ -0,0 +1,32 @@ +name: Publish +on: + push: + branches: ['master', 'main'] + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + +jobs: + build: + uses: ./.github/workflows/build-workflow.yml + release: + needs: build + name: Create Release + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Download build + uses: actions/download-artifact@v4 + with: + name: build + path: build + - name: Release + uses: docker://antonyurchenko/git-release:v6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_NAME: ${{ needs.build.outputs.version }} + PRE_RELEASE: ${{ github.ref_type == 'branch' }} + UNRELEASED: ${{ github.ref_type == 'branch' && 'update' || '' }} + UNRELEASED_TAG: latest-snapshot + ALLOW_EMPTY_CHANGELOG: ${{ github.ref_type == 'branch' && 'true' || 'false' }} + with: + args: build/*.jar diff --git a/.github/workflows/release-workflow.yml b/.github/workflows/release-workflow.yml deleted file mode 100644 index 56bbe49..0000000 --- a/.github/workflows/release-workflow.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: Release -on: - push: - tags: - - 'release-*' - - '!release-*-alpha' - -jobs: - release: - name: Create Release - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Gradle Build - uses: eskatos/gradle-command-action@v1 - with: - arguments: build - - name: Extract version - uses: frabert/replace-string-action@master - id: format-version - with: - pattern: 'refs/tags/release-([0-9]+.[0-9]+.[0-9]+)' - string: ${{ github.ref }} - replace-with: '$1' - - name: Release - uses: docker://antonyurchenko/git-release:v3 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DRAFT_RELEASE: "true" - ALLOW_TAG_PREFIX: "true" - with: - args: | - build/libs/simplereserve-${{ steps.format-version.outputs.replaced }}.jar diff --git a/.gitignore b/.gitignore index a16a5c2..327cf6d 100755 --- a/.gitignore +++ b/.gitignore @@ -1,44 +1,53 @@ -# Created by https://www.gitignore.io/api/intellij,java,gradle - -### Intellij ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android -Studio and Webstorm - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -# User-specific stuff: -# .idea/workspace.xml -# .idea/tasks.xml -# .idea/dictionaries -# .idea/shelf - -# Sensitive or high-churn files: -# .idea/dataSources.ids -# .idea/dataSources.xml -# .idea/sqlDataSources.xml -# .idea/dynamic.xml -# .idea/uiDesigner.xml - -# Gradle: -# .idea/gradle.xml -# .idea/libraries - -# Mongo Explorer plugin: -# .idea/mongoSettings.xml - -## File-based project format: -*.ipr +# Created by https://www.gitignore.io/api/gradle,intellij+all +# Edit at https://www.gitignore.io/?templates=gradle,intellij+all + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format *.iws -## Plugin-specific files: - # IntelliJ -/out/ +out/ # mpeltonen/sbt-idea plugin .idea_modules/ @@ -46,31 +55,37 @@ Studio and Webstorm # JIRA plugin atlassian-ide-plugin.xml +# Cursive Clojure plugin +.idea/replstate.xml + # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties +# Editor-based Rest Client +.idea/httpRequests -### Java ### -*.class +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser -# Mobile Tools for Java (J2ME) -.mtj.tmp/ +### Intellij+all Patch ### +# Ignores the whole .idea folder and all .iml files +# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 -# Package Files # -*.jar -*.war -*.ear +.idea/ -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 +*.iml +modules.xml +.idea/misc.xml +*.ipr ### Gradle ### .gradle -build/ +/build/ # Ignore Gradle GUI config gradle-app.setting @@ -80,3 +95,11 @@ gradle-app.setting # Cache of project .gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +# End of https://www.gitignore.io/api/gradle,intellij+all diff --git a/CHANGELOG.md b/CHANGELOG.md index 536b21e..fe44281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,20 @@ # Changelog ## [Unreleased] +### Added +- MIT license + +### Changed +- Rewrote plugin in Kotlin +- MC 1.21, Java 21, Kotlin 2.1 +- **BREAKING**: New config format + +### Removed +- Help command (duplicated built-in usage functionality) + +### Fixed +- Close listeners on reload +- `KICK` method will now function for players with both kick and full permissions and `BOTH` reserve method ## [1.0.1] - 2020-06-28 ### Changed @@ -13,8 +27,7 @@ - Github Actions for build and automated releases ### Changed -- Adopt semver - - axion-release plugin +- Adopt semver via axion-release plugin - Target MC version 1.15 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b8f94e9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 SimpleMC + +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. diff --git a/README.md b/README.md index 1816e6a..492c2e4 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,90 @@ -SimpleReserve -============= +# SimpleReserve -SimpleReserve is a simple reserve slot plugin for the Bukkit Minecraft API. +Simple, easy-to-use Reserve slot plugin + +Tired of not being able to offer VIPs reserved slots or being unable to join your own full server? SimpleReserve +provides an easy way to add that functionality with Bukkit permission support. + +## Features + +- Simple to use reserve slots plugin with bukkit permission support +- Provides functionality for 2 reserve slot methods: + - Full method: Users with 'simplereserve.enter.full' may enter past the imposed player limit + - Kick method: Users with 'simplereserve.enter.kick' may enter a server when full by kicking the first player found that is able to be kicked. Users with the 'simplereserve.kick.prevent' permission are immune to being kicked(Utilize inheritance!) + +## Config + +The config file for SimpleReserve is very simple and will be auto-generated on first run. The file should contain: + +```yaml +reserve: + method: both + server-full-message: The server is full! + full: + cap: 5 + kick-fallback: false + over-capacity-message: All reserve slots full! + kick: + message: Kicked to make room for reserved user! +``` + +### Reserve Methods + +- `full`: Allow reserves to log on past the server's configured player limit +- `kick`: Attempt to kick a player without kick immunity to make room +- `both`: Both methods of reservation based on Permission + - **NOTE**: If a player has permission for kick and full, full takes precedence +- `none`: No reservation. Effectively disables mod without needing to remove + +## Permissions + +Permissions for SimpleReserve are...well...simple. There are only 4 basic permissions to worry about. + +- `simplereserve.enter.full`: User may join past server player cap +- `simplereserve.enter.kick`: User may join full server by kicking another player +- `simplereserve.kick.prevent`: User cannot be kicked to make room for a joining player +- `simplereserve.reload`: Gives access to SimpleReserve reload command + +...and for convenience +- `simplereserve.*`: All SimpleReserve permissions +- `simplereserve.enter`: Enter full and enter kick permissions + +See also [plugin.yml](src/main/resources/plugin.yml). + +### Examples + +- Lets say you have 4 usergroups. Guests(default), Users, Moderators, and Admins. You want to give Admins and Moderators + joining full server via "kick" method, but you only want to be able to kick at the expense of guests. Permissions: + ```yaml + groups: + Guests: + default: true + Users: + default: false + inheritance: Guests + permissions: + - 'simplereserve.kick.prevent' + Moderators: + default: false + inheritance: Users + permissions: + - 'simplereserve.enter.kick' + Admins: + default: false + inheritance: + permissions: + - '*' + ``` + Note that Users only have the `prevent` permission. Any groups that inherit from Users will also have the same + permission. Now to ensure we're using the right type of reserve slot, the config.yml would look like: + ```yaml + reserve: + method: kick + # ... + ``` +- Same situation but we want to be able to join over capacity instead of kicking. We only need to change the + `Moderators`'s group `simplereserve.enter.kick` permission to `simplereserve.enter.full` and change `method: kick` to + `method: full` in config. +- We could also allow mods to join using the `kick` method and admins to join using `full`. Set `method: both` in the + config and give mods `simplereserve.enter.kick` permission. Now, Admins have both `kick` and `full` which will default + to using `full` when both are available while mods can join using the `kick` permission. diff --git a/build.gradle.kts b/build.gradle.kts index b6c2bdc..c670f01 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,91 +1,112 @@ +import org.yaml.snakeyaml.DumperOptions +import org.yaml.snakeyaml.Yaml import pl.allegro.tech.build.axion.release.domain.hooks.HookContext -import pl.allegro.tech.build.axion.release.domain.hooks.HooksConfig import java.time.OffsetDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter plugins { - id("java") - id("pl.allegro.tech.build.axion-release") version "1.10.3" + alias(libs.plugins.axionRelease) + alias(libs.plugins.kotlin) + alias(libs.plugins.ktlint) + alias(libs.plugins.shadow) } -val repoRef = "SimpleMC\\/SimpleReserve" -val mcApiVersion = "1.15" - -group = "org.simplemc" -version = scmVersion.version - scmVersion { - hooks(closureOf { - pre( - "fileUpdate", - mapOf( - "file" to "src/main/resources/plugin.yml", - "pattern" to KotlinClosure2({ v, _ -> "version: $v\\napi-version: \".+\"" }), - "replacement" to KotlinClosure2({ v, _ -> "version: $v\napi-version: \"$mcApiVersion\"" }) - ) - ) - // "normal" changelog update--changelog already contains a history + versionIncrementer("incrementMinorIfNotOnRelease", mapOf("releaseBranchPattern" to "release/.+")) + unshallowRepoOnCI.set(true) + + hooks { + // Automate moving `[Unreleased]` changelog entries into `[]` on release + // FIXME - workaround for Kotlin DSL issue https://github.com/allegro/axion-release-plugin/issues/500 + val changelogPattern = + "\\[Unreleased\\]([\\s\\S]+?)\\n" + + "(?:^\\[Unreleased\\]: https:\\/\\/github\\.com\\/(\\S+\\/\\S+)\\/compare\\/[^\\n]*\$([\\s\\S]*))?\\z" pre( "fileUpdate", mapOf( "file" to "CHANGELOG.md", - "pattern" to KotlinClosure2({ v, _ -> - "\\[Unreleased\\]([\\s\\S]+?)\\n(?:^\\[Unreleased\\]: https:\\/\\/github\\.com\\/$repoRef\\/compare\\/release-$v\\.\\.\\.HEAD\$([\\s\\S]*))?\\z" - }), - "replacement" to KotlinClosure2({ v, c -> + "pattern" to KotlinClosure2({ _, _ -> changelogPattern }), + "replacement" to KotlinClosure2({ version, context -> + // github "diff" for previous version + val previousVersionDiffLink = + when (context.previousVersion == version) { + true -> "releases/tag/v$version" // no previous, just link to the version + false -> "compare/v${context.previousVersion}...v$version" + } """ \[Unreleased\] - - ## \[$v\] - ${currentDateString()}$1 - \[Unreleased\]: https:\/\/github\.com\/$repoRef\/compare\/release-$v...HEAD - \[$v\]: https:\/\/github\.com\/$repoRef\/compare\/release-${c.previousVersion}...release-$v$2 + + ## \[$version\] - $currentDateString$1 + \[Unreleased\]: https:\/\/github\.com\/$2\/compare\/v$version...HEAD + \[$version\]: https:\/\/github\.com\/$2\/$previousVersionDiffLink$3 """.trimIndent() - }) - ) - ) - // first-time changelog update--changelog has only unreleased info - pre( - "fileUpdate", - mapOf( - "file" to "CHANGELOG.md", - "pattern" to KotlinClosure2({ v, _ -> - "Unreleased([\\s\\S]+?\\nand this project adheres to \\[Semantic Versioning\\]\\(https:\\/\\/semver\\.org\\/spec\\/v2\\.0\\.0\\.html\\).)\\s\\z" }), - "replacement" to KotlinClosure2({ v, c -> - """ - \[Unreleased\] - - ## \[$v\] - ${currentDateString()}$1 - - \[Unreleased\]: https:\/\/github\.com\/$repoRef\/compare\/release-$v...HEAD - \[$v\]: https:\/\/github\.com\/$repoRef\/releases\/tag\/release-$v - """.trimIndent() - }) - ) + ), ) + pre("commit") - }) + } } -fun currentDateString() = OffsetDateTime.now(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ISO_DATE) +group = "org.simplemc" +version = scmVersion.version -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 -} +val currentDateString: String + get() = OffsetDateTime.now(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ISO_DATE) -repositories { - jcenter() - maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") - maven("https://oss.sonatype.org/content/repositories/snapshots") +kotlin { + jvmToolchain(21) } dependencies { - compileOnly(group = "org.spigotmc", name = "spigot-api", version = "$mcApiVersion+") + compileOnly(libs.spigot) } -tasks.wrapper { - gradleVersion = "6.5" - distributionType = Wrapper.DistributionType.ALL +tasks { + wrapper { + distributionType = Wrapper.DistributionType.ALL + } + + processResources { + val placeholders = mapOf( + "version" to version, + "apiVersion" to libs.versions.mcApi.get(), + "kotlinVersion" to libs.versions.kotlin.get(), + ) + + filesMatching("plugin.yml") { + expand(placeholders) + } + + // create an "offline" copy/variant of the plugin.yml with `libraries` omitted + doLast { + val resourcesDir = sourceSets.main.get().output.resourcesDir + val yamlDumpOptions = + // make it pretty for the people + DumperOptions().also { + it.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK + it.isPrettyFlow = true + } + val yaml = Yaml(yamlDumpOptions) + val pluginYml: Map = yaml.load(file("$resourcesDir/plugin.yml").inputStream()) + yaml.dump(pluginYml.filterKeys { it != "libraries" }, file("$resourcesDir/offline-plugin.yml").writer()) + } + } + + jar { + exclude("offline-plugin.yml") + } + + // offline jar should be ready to go with all dependencies + shadowJar { + minimize() + archiveClassifier.set("offline") + exclude("plugin.yml") + rename("offline-plugin.yml", "plugin.yml") + + // avoid classpath conflicts/pollution via relocation + isEnableRelocation = true + relocationPrefix = "${project.group}.${project.name.lowercase()}.libraries" + } } diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..63e5bbd --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,2 @@ +#This file is generated by updateDaemonJvm +toolchainVersion=21 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..7b2ff95 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,16 @@ +[versions] +axionRelease = "1.18.18" +kotlin = "2.1.20" +ktlintGradle = "12.2.0" +mcApi = "1.21" +shadow = "8.3.6" +spigot = "1.21.+" + +[plugins] +axionRelease = { id = "pl.allegro.tech.build.axion-release", version.ref = "axionRelease"} +kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin"} +ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlintGradle"} +shadow = { id = "com.gradleup.shadow", version.ref = "shadow"} + +[libraries] +spigot = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index f3d88b1..1b33c55 100755 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 186b715..6514f91 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 2fe81a7..23d15a9 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,80 +15,115 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +CLASSPATH="\\\"\\\"" + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -97,87 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "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 +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 - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 24467a1..5eed7ee 100755 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @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 +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,10 +27,14 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @@ -37,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -51,48 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar +set CLASSPATH= + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/settings.gradle b/settings.gradle deleted file mode 100755 index d085bf4..0000000 --- a/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'simplereserve' - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..e4e0441 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +buildscript { + dependencies { + classpath("org.yaml:snakeyaml:2.3") + } +} + +dependencyResolutionManagement { + repositories { + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://oss.sonatype.org/content/repositories/snapshots") + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.9.0" +} + +rootProject.name = "simplereserve" diff --git a/src/main/java/org/simplemc/simplereserve/ReserveType.java b/src/main/java/org/simplemc/simplereserve/ReserveType.java deleted file mode 100755 index f172bc1..0000000 --- a/src/main/java/org/simplemc/simplereserve/ReserveType.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.simplemc.simplereserve; - -/** - * Enum for type of reserve we are using(kick, full bypass, or either(both)) - * - * @author Taylor Becker - */ -public enum ReserveType -{ - KICK, FULL, BOTH, NONE -} diff --git a/src/main/java/org/simplemc/simplereserve/SimpleReserve.java b/src/main/java/org/simplemc/simplereserve/SimpleReserve.java deleted file mode 100755 index 83084dc..0000000 --- a/src/main/java/org/simplemc/simplereserve/SimpleReserve.java +++ /dev/null @@ -1,199 +0,0 @@ -package org.simplemc.simplereserve; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.java.JavaPlugin; - -/** - * Simple reserve slot plugin the Bukkit API - * - * @author Taylor Becker - */ -public class SimpleReserve extends JavaPlugin -{ - /** - * Set up the block listener and Permissions on enable - */ - public void onEnable() - { - loadConfig(); - - getLogger().info( - String.format("%s version %s enabled!", getDescription().getName(), getDescription().getVersion())); - } - - /** - * Load the config options from config - */ - private void loadConfig() - { - // ensure config file/options valid - validateConfig(); - - // load - ConfigurationSection config = getConfig().getConfigurationSection("reserve"); // our config - ReserveType reserveMethod; // type of reservations - - try - { - reserveMethod = ReserveType.valueOf(config.getString("type").toUpperCase()); - } - // config not set right(enum can't be valueOf'd) - catch (IllegalArgumentException iae) - { - // config not set right, default to both - config.set("type", "both"); - saveConfig(); - getLogger().info(getDescription().getName() + " config file updated, please check settings!"); - - reserveMethod = ReserveType.valueOf(config.getString("type").toUpperCase()); - } - - new SimpleReserveListener(reserveMethod, - config.getInt("full.cap", 5), - config.getBoolean("full.reverttokick", false), - config.getString("kick-message", "Kicked to make room for reserved user!"), - config.getString("full-message", "The server is full!"), - config.getString("reserve-full-message", "All reserve slots are full!"), - this); - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) - { - if (command.getName().equalsIgnoreCase("simplereserve")) - { - if (sender.hasPermission("simplereserve")) - { - // reload command - if (args.length > 0 && (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("r"))) - { - if (sender.hasPermission("simplereserve.reload")) - { - reloadConfig(); // reload file - loadConfig(); // read config - - getLogger().fine("Config reloaded."); - sender.sendMessage("SimpleReserve config reloaded"); - } - else - { - sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); - } - } - // help command - else - { - sender.sendMessage( - String.format("%s/%s%s | %s%s", - ChatColor.AQUA, - getCommand("simplereserve").getName(), - ChatColor.WHITE, - ChatColor.BLUE, - getCommand("simplereserve").getDescription())); - sender.sendMessage( - String.format("Usage: %s%s", ChatColor.GRAY, getCommand("simplereserve").getUsage())); - } - } - else - { - sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); - } - return true; - } - - return false; - } - - /** - * Validate nodes, if they don't exist or are wrong, set them and resave config - *

- * Unfortunately we cannot use defaults because there is no reasonable way of copying the defaults - * into the live config file while maintaining an updated header. We could use saveDefaultConfig - * but this doesn't help us when changing the config options and a config file already exists and - * copyDefaults destroys the header. - *

- */ - private void validateConfig() - { - boolean updated = false; - FileConfiguration config = getConfig(); // our config - - // settings - if (!config.contains("reserve.type")) - { - config.set("reserve.type", "both"); - updated = true; - } - - if (!config.contains("reserve.full.cap")) - { - config.set("reserve.full.cap", 5); - updated = true; - } - - if (!config.contains("reserve.full.reverttokick")) - { - config.set("reserve.full.reverttokick", false); - updated = true; - } - - if (!config.contains("reserve.kick-message")) - { - config.set("reserve.kick-message", "Kicked to make room for reserved user!"); - updated = true; - } - - if (!config.contains("reserve.full-message")) - { - config.set("reserve.full-message", "The server is full!"); - updated = true; - } - - if (!config.contains("reserve.reserve-full-message")) - { - config.set("reserve.reserve-full-message", "All reserve slots full!"); - updated = true; - } - - // if nodes have been updated, update header then save - if (updated) - { - // set header for information - config.options().header("Config nodes:\n" + - "\n" + - "reserve.type(enum/string): Type of reserve slots, options:\n" + - " full,kick,both,none\n" + - "reserve.full.cap(int): Max players allowed over capacity if using 'full' method, 0 for no max\n" + - "reserve.full.reverttokick(boolean): Should we fall back to kick method if we reach max over capacity using full?\n" + - "kick-message(string): Message player will receive when kicked to let reserve in\n" + - "full-message(string): Message player will receive when unable to join full server\n" + - "reserve-full-message(string): Message player with reserve privileges will receive when all reserve slots are full\n" + - "\n" + - "Reserve Types Overview:\n" + - "-----------------------\n" + - "\n" + - "Full: Allow reserves to log on past the server limit\n" + - "Kick: Attempt to kick a player without kick immunity to make room\n" + - "Both: Both methods of reservation based on Permission\n" + - " NOTE: If a player has permission for kick and full, full applies\n" + - "None: No reservation. Effectively disables mod without needing to remove\n" + - ""); - - // save - saveConfig(); - getLogger().info(getDescription().getName() + " config file updated, please check settings!"); - } - } - - /** - * Plugin disabled - */ - public void onDisable() - { - System.out.println("SimpleReserve disabled!"); - } -} diff --git a/src/main/java/org/simplemc/simplereserve/SimpleReserveListener.java b/src/main/java/org/simplemc/simplereserve/SimpleReserveListener.java deleted file mode 100755 index 5f98faf..0000000 --- a/src/main/java/org/simplemc/simplereserve/SimpleReserveListener.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.simplemc.simplereserve; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerLoginEvent; -import org.bukkit.event.player.PlayerLoginEvent.Result; - -/** - * Listener for simple reserve plugin to handle logins - * - * @author Taylor Becker - */ -public class SimpleReserveListener implements Listener -{ - private SimpleReserve plugin; // plugin using the listener - - private ReserveType reserveMethod; // method to use for reserve slots - private int capOver; // capacity allowed of server capacity - private boolean revertToKick; // in event of reaching cap over cap, should full fall back on kicking? - private String kickMessage, // message to send player when kicked to make room - fullMessage, // message to send player who can't join full server - reserveFullMessage; // message to send player who can join full but no available slots - - /** - * Initialize the player listener - * - * @param reserveMethod method to use for reserve slots - * @param capOver capacity allowed of server capacity - * @param revertToKick in event of reaching cap over cap, should full fall back on kicking? - * @param kickMessage message to send player when kicked to make room - * @param fullMessage message to send player who can't join full server - * @param plugin plugin using the listener - */ - public SimpleReserveListener(ReserveType reserveMethod, int capOver, boolean revertToKick, String kickMessage, - String fullMessage, String reserveFullMessage, SimpleReserve plugin) - { - setSettings(reserveMethod, capOver, revertToKick, kickMessage, fullMessage, reserveFullMessage); - this.plugin = plugin; - - // register events - if (reserveMethod == ReserveType.NONE) - { - plugin.getLogger().finer("ReserveType is NONE, not registering events"); - } - else - { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - - plugin.getLogger().finer( - String.format("Created SimpleReserveListener with kickMessage: \"%s\" and fullMessage: \"%s\"", - kickMessage, fullMessage)); - } - } - - /** - * Set reserve listener settings - * - * @param reserveMethod method to use for reserve slots - * @param capOver capacity allowed of server capacity - * @param revertToKick in event of reaching cap over cap, should full fall back on kicking? - * @param kickMessage message to send player when kicked to make room - * @param fullMessage message to send player who can't join full server - */ - public void setSettings(ReserveType reserveMethod, int capOver, boolean revertToKick, String kickMessage, - String fullMessage, String reserveFullMessage) - { - this.reserveMethod = reserveMethod; - this.capOver = capOver; - this.revertToKick = revertToKick; - this.kickMessage = kickMessage; - this.fullMessage = fullMessage; - this.reserveFullMessage = reserveFullMessage; - } - - /** - * If server is full, let event through if player has not been denied yet - * - * @param event the login event - */ - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLogin(PlayerLoginEvent event) - { - // is the server full? - if (event.getResult() == Result.KICK_FULL) - { - Player player = event.getPlayer(); // player doing event - - // full entry - if ((reserveMethod == ReserveType.BOTH || reserveMethod == ReserveType.FULL) - && player.hasPermission("simplereserve.enter.full")) - { - // allow player in as long as the server hasn't hit the max over cap - if (!serverTooFull()) - { - event.allow(); - plugin.getLogger().info( - "Allowed player " + event.getPlayer().getDisplayName() + " to join full server!"); - } - // server's too full to let more in, attempt to kick someone to make room - else if (revertToKick) - { - kickJoin(player, event); - } - // server's too full and fallback kick is disabled - else - { - event.disallow(Result.KICK_FULL, reserveFullMessage); - } - } - // kick entry - else if ((reserveMethod == ReserveType.BOTH || reserveMethod == ReserveType.KICK) - && player.hasPermission("simplereserve.enter.kick")) - { - kickJoin(player, event); - } - // player cannot join - else - { - event.disallow(Result.KICK_FULL, fullMessage); - } - } - } - - /** - * Perform a join via kick method - * - * @param player player logging in - * @param event login event - */ - private void kickJoin(Player player, PlayerLoginEvent event) - { - Player toKick = plugin.getServer().getOnlinePlayers().stream() - .filter(p -> !p.hasPermission("simplereserve.kick.prevent")).findFirst().orElse(null); - - // found player to kick - if (toKick != null) - { - toKick.kickPlayer(kickMessage); - event.allow(); - - plugin.getLogger().info( - String.format("Allowed player %s to join full server by kicking player %s!", - player.getDisplayName(), toKick.getDisplayName())); - } - else - { - // if we get here, no kickable player found...that would be unfortunate. - event.disallow(Result.KICK_FULL, "Unable to find any kickable players to open spots!"); - } - } - - /** - * @return if server is more full than cap over cap - */ - private boolean serverTooFull() - { - return capOver != 0 - && (plugin.getServer().getOnlinePlayers().size() >= plugin.getServer().getMaxPlayers() + capOver); - } -} diff --git a/src/main/kotlin/org/simplemc/simplereserve/ReserveConfig.kt b/src/main/kotlin/org/simplemc/simplereserve/ReserveConfig.kt new file mode 100644 index 0000000..4bcb19d --- /dev/null +++ b/src/main/kotlin/org/simplemc/simplereserve/ReserveConfig.kt @@ -0,0 +1,30 @@ +package org.simplemc.simplereserve + +data class ReserveConfig( + val method: ReserveMethod, + val serverFullMessage: String, + val full: FullMethodConfig, + val kick: KickMethodConfig, +) { + enum class ReserveMethod { + KICK, + FULL, + BOTH, + NONE, + ; + + val fullEnabled: Boolean get() = this == FULL || this == BOTH + val kickEnabled: Boolean get() = this == KICK || this == BOTH + } + data class FullMethodConfig( + val capacity: Int, + val kickFallback: Boolean, + val overCapacityMessage: String, + ) { + init { + check(capacity > 0) { "Full method capacity must be greater than 0." } + } + } + + data class KickMethodConfig(val message: String) +} diff --git a/src/main/kotlin/org/simplemc/simplereserve/ReserveLoginListener.kt b/src/main/kotlin/org/simplemc/simplereserve/ReserveLoginListener.kt new file mode 100644 index 0000000..2db0060 --- /dev/null +++ b/src/main/kotlin/org/simplemc/simplereserve/ReserveLoginListener.kt @@ -0,0 +1,75 @@ +package org.simplemc.simplereserve + +import org.bukkit.Server +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.HandlerList +import org.bukkit.event.Listener +import org.bukkit.event.player.PlayerLoginEvent +import org.bukkit.event.player.PlayerLoginEvent.Result.KICK_FULL +import org.bukkit.plugin.Plugin +import org.simplemc.simplereserve.ReserveConfig.ReserveMethod + +class ReserveLoginListener(private val plugin: Plugin, private val config: ReserveConfig) : Listener, AutoCloseable { + init { + when (config.method) { + ReserveMethod.NONE -> plugin.logger.finer { "Reserve Method is NONE, skipping listener registration." } + else -> { + plugin.server.pluginManager.registerEvents(this, plugin) + plugin.logger.finer { "Created ReserveLoginListener with config:\n$config" } + } + } + } + + /** + * Allow players to join a full server if permitted + * + * @param event the login event + */ + @EventHandler(priority = EventPriority.HIGH) + fun onPlayerLogin(event: PlayerLoginEvent) { + plugin.logger.info { config.full.kickFallback.toString() } + if (event.result != KICK_FULL) return + + val allowFull = config.method.fullEnabled && event.player.hasPermission("simplereserve.enter.full") + val canEnterFull = allowFull && plugin.server.hasOverCapacity + val allowKick = + (config.method.kickEnabled && event.player.hasPermission("simplereserve.enter.kick")) || (allowFull && config.full.kickFallback) + + when { + canEnterFull -> { + event.allow() + plugin.logger.info { "Allowed player ${event.player.displayName} to join full server!" } + } + + allowFull && !allowKick -> event.disallow(KICK_FULL, config.full.overCapacityMessage) + allowKick -> kickJoin(event.player, event) + else -> event.disallow(KICK_FULL, config.serverFullMessage) + } + } + + /** + * Perform a join via kick method + * + * @param player player logging in + * @param event login event + */ + private fun kickJoin(player: Player, event: PlayerLoginEvent) { + plugin.server.onlinePlayers.firstOrNull { p -> !p.hasPermission("simplereserve.kick.prevent") }?.let { toKick -> + toKick.kickPlayer(config.kick.message) + event.allow() + + plugin.logger.info { + "Allowed player ${player.displayName} to join full server by kicking player ${toKick.displayName}!" + } + } ?: event.disallow(KICK_FULL, "Unable to find any kickable players to make room!") + } + + // if server has overcapacity available according to reserve capacity + private val Server.hasOverCapacity: Boolean get() = onlinePlayers.size < maxPlayers + config.full.capacity + + override fun close() { + HandlerList.unregisterAll(this) // clear event binds (important for reload) + } +} diff --git a/src/main/kotlin/org/simplemc/simplereserve/SimpleReserve.kt b/src/main/kotlin/org/simplemc/simplereserve/SimpleReserve.kt new file mode 100644 index 0000000..705e14b --- /dev/null +++ b/src/main/kotlin/org/simplemc/simplereserve/SimpleReserve.kt @@ -0,0 +1,157 @@ +package org.simplemc.simplereserve + +import org.bukkit.command.Command +import org.bukkit.command.CommandSender +import org.bukkit.plugin.java.JavaPlugin +import org.simplemc.simplereserve.ReserveConfig.FullMethodConfig +import org.simplemc.simplereserve.ReserveConfig.KickMethodConfig +import org.simplemc.simplereserve.ReserveConfig.ReserveMethod + +/** + * Simple reserve slot plugin the Bukkit API + * + * @author Taylor Becker + */ +class SimpleReserve : JavaPlugin() { + + lateinit var listener: ReserveLoginListener + override fun onEnable() { + listener = ReserveLoginListener(this, loadConfig()) + + checkNotNull(getCommand("simplereservereload")).setExecutor(::reloadConfigCommand) + + logger.info { "${description.name} version ${description.version} enabled!" } + } + + /** + * Load the config options from config + */ + private fun loadConfig(): ReserveConfig { + // ensure config file/options valid + validateConfig() + + // load + val config = config.getConfigurationSection("reserve") // our config + + val reserveMethod: ReserveMethod = try { + ReserveMethod.valueOf(config!!.getString("method")!!.uppercase()) + } catch (_: IllegalArgumentException) { + // invalid method, default to both + // config not set right, default to both + config!!.set("method", "both") + saveConfig() + logger.info { "${description.name} config file updated, please check settings!" } + + ReserveMethod.valueOf(config.getString("method")!!.uppercase()) + } + + return ReserveConfig( + method = reserveMethod, + serverFullMessage = config.getString("server-full-message", "The server is full!")!!, + full = FullMethodConfig( + capacity = config.getInt("full.cap", 5), + kickFallback = config.getBoolean("full.kick-fallback", false), + overCapacityMessage = config.getString("full.over-capacity-message", "All reserve slots are full!")!!, + ), + kick = KickMethodConfig( + message = config.getString( + "kick.message", + "Kicked to make room for reserved user!", + )!!, + ), + ) + } + + private fun reloadConfigCommand( + sender: CommandSender, + command: Command, + label: String, + vararg args: String, + ): Boolean { + listener.close() + reloadConfig() // reload config file from disk + listener = ReserveLoginListener(this, loadConfig()) + + logger.fine { "Config reloaded." } + sender.sendMessage("SimpleReserve config reloaded") + return true + } + + /** + * Validate nodes, if they don't exist or are wrong, set them and resave config + * + * Unfortunately, we cannot use defaults because there is no reasonable way of copying the defaults into the live + * config file while maintaining an updated header. We could use [saveDefaultConfig] but this doesn't help us when + * changing available config options when a config file already exists. + */ + private fun validateConfig() { + var updated = false + + if (!config.contains("reserve.method")) { + config.set("reserve.method", "both") + updated = true + } + + if (!config.contains("reserve.server-full-message")) { + config.set("reserve.server-full-message", "The server is full!") + updated = true + } + + if (!config.contains("reserve.full.cap")) { + config.set("reserve.full.cap", 5) + updated = true + } + + if (!config.contains("reserve.full.kick-fallback")) { + config.set("reserve.full.kick-fallback", false) + updated = true + } + + if (!config.contains("reserve.full.over-capacity-message")) { + config.set("reserve.full.over-capacity-message", "All reserve slots full!") + updated = true + } + + if (!config.contains("reserve.kick.message")) { + config.set("reserve.kick.message", "Kicked to make room for reserved user!") + updated = true + } + + // if nodes have been updated, update header then save + if (updated) { + // set header for information + config.options().setHeader( + listOf( + "Config nodes:", + "", + "reserve.method(enum/string): Method to use for allowing reservees in, options:", + " full,kick,both,none", + "reserve.server-full-message(string): Message player will receive when unable to join full server", + "reserve.full.cap(int): Max players allowed over capacity if using 'full' method, 0 for no max", + "reserve.full.kick-fallback(boolean): Should we fall back to kick method if we reach max over capacity using full?", + "reserve.full.over-capacity-message(string): Message player with reserve privileges will receive when all reserve slots are full", + "reserve.kick.message(string): Message player will receive when kicked to let reserve in", + "", + "Reserve Methods Overview:", + "-----------------------", + "", + "Full: Allow reserves to log on past the server limit", + "Kick: Attempt to kick a player without kick immunity to make room", + "Both: Both methods of reservation based on Permission", + " NOTE: If a player has permission for kick and full, full takes precedence", + "None: No reservation. Effectively disables mod without needing to remove", + "", + ), + ) + + // save + saveConfig() + logger.info { "${description.name} config file updated, please check settings!" } + } + } + + override fun onDisable() { + listener.close() + println("SimpleReserve disabled!") + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index fb89b41..629844c 100755 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,39 +1,37 @@ name: SimpleReserve main: org.simplemc.simplereserve.SimpleReserve -version: 1.0.1 -api-version: "1.15" +version: "${version}" +api-version: "${apiVersion}" website: https://github.com/SimpleMC/SimpleReserve author: tajobe permissions: - simplereserve: - description: Gives access to SimpleReserve help command - simplereserve.*: - description: All SimpleReserve permissions - children: - simplereserve.enter: true - simplereserve.kick.prevent: true - simplereserve.reload: true - simplereserve.enter: - description: Enter full and kick permissions - children: - simplereserve.enter.full: true - simplereserve.enter.kick: true - simplereserve.enter.full: - description: User may join past server player cap - simplereserve.enter.kick: - description: User may join full server by kicking another player - simplereserve.kick.prevent: - description: User cannot be kicked to make room for a joining player - simplereserve.reload: - description: Gives access to SimpleReserve reload command - children: - simplereserve: true + simplereserve.*: + description: All SimpleReserve permissions + children: + simplereserve.enter: true + simplereserve.kick.prevent: true + simplereserve.reload: true + simplereserve.enter: + description: Enter full and kick permissions + children: + simplereserve.enter.full: true + simplereserve.enter.kick: true + simplereserve.enter.full: + description: User may join past server player cap + simplereserve.enter.kick: + description: User may join full server by kicking another player + simplereserve.kick.prevent: + description: User cannot be kicked to make room for a joining player + simplereserve.reload: + description: Gives access to SimpleReserve reload command commands: - simplereserve: - aliases: - - sr - description: SimpleReserve command for help or config reload - usage: | - / | Displays SimpleReserve help - / r | Reloads SimpleReserve config - / reload | Reloads SimpleReserve config + simplereservereload: + aliases: + - srr + - srreload + - srconfig + permission: simplereserve.reload + description: SimpleReserve command for help or config reload + usage: / | Reloads SimpleReserve config +libraries: + - org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}