diff --git a/.editorconfig b/.editorconfig index b430227..bed2d93 100644 --- a/.editorconfig +++ b/.editorconfig @@ -432,4 +432,4 @@ ij_yaml_keep_line_breaks = true ij_yaml_sequence_on_new_line = false ij_yaml_space_before_colon = false ij_yaml_spaces_within_braces = true -ij_yaml_spaces_within_brackets = true +ij_yaml_spaces_within_brackets = true \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..09bc62c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..2a8838e --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @darksaid98 diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..4faa9bd --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: darksaid98 +patreon: alathramc diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..66a0311 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,34 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Version information:** +- Vanilla version: [e.g. 1.20.2] +- Server version: [e.g. paper-123] +- Plugin version [e.g. 0.1.0] + +**Additional context** +``` +Add any other context about the problem here including console errors. +``` \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..6532412 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/.github/actions/gradle/action.yml b/.github/actions/gradle/action.yml new file mode 100644 index 0000000..ed59656 --- /dev/null +++ b/.github/actions/gradle/action.yml @@ -0,0 +1,15 @@ +name: 'Setup Gradle' +description: 'Grant execute permissions and validate Gradle wrapper' + +runs: + using: 'composite' + steps: + - name: Grant execute permissions for Gradle wrapper + run: chmod +x gradlew + shell: bash + + - name: Validate Gradle Wrapper Authenticity + uses: gradle/wrapper-validation-action@v1 + + - name: Setup Gradle and Caching + uses: gradle/gradle-build-action@v2 \ No newline at end of file diff --git a/.github/actions/jdk/action.yml b/.github/actions/jdk/action.yml new file mode 100644 index 0000000..214a9af --- /dev/null +++ b/.github/actions/jdk/action.yml @@ -0,0 +1,17 @@ +name: 'Setup JDK' +description: 'Set up JDK' + +inputs: + java-version: + description: 'Java version' + required: true + default: '17' + +runs: + using: 'composite' + steps: + - name: Setup JDK + uses: actions/setup-java@v3 + with: + java-version: ${{ inputs.java-version }} + distribution: 'temurin' \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..dbf9ec8 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,26 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + commit-message: + prefix: "ci:" + target-branch: "main" + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" + commit-message: + prefix: "build:" + target-branch: "main" + groups: + "org.flywaydb": + patterns: + - "org.flywaydb*" + "org.jooq": + patterns: + - "org.jooq*" + "net.kyori": + patterns: + - "net.kyori*" \ No newline at end of file diff --git a/.github/workflows/gradle-publish.yml b/.github/workflows/gradle-publish.yml deleted file mode 100644 index 883c650..0000000 --- a/.github/workflows/gradle-publish.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: Upload release assets - -on: - release: - types: [ published ] - -jobs: - upload_asset: - runs-on: ubuntu-latest - permissions: - contents: write - packages: write - - steps: - - name: Checkout Repository - uses: actions/checkout@v3 - - - name: Validate Gradle Wrapper - uses: gradle/wrapper-validation-action@v1 - - - name: Setup Java - uses: actions/setup-java@v3 - with: - distribution: temurin - cache: gradle - java-version: 17 - - - name: Clean Build - run: ./gradlew clean build --no-daemon - - - name: Upload Release Assets - uses: AButler/upload-release-assets@v2.0 - with: - files: 'build/libs/AlathranWars-*.jar' - repo-token: ${{ secrets.GITHUB_TOKEN }} - release-tag: ${{ github.event.release.tag_name }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..055f166 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,86 @@ +name: Build & Upload Release jar with Gradle + +on: + push: + branches: + - 'main' + - 'master' + tags: + - '*' + pull_request: + branches: + - 'main' + - 'master' + schedule: + - cron: '0 0 * * 6' + workflow_dispatch: + +concurrency: + group: ${{ format('{0}-{1}', github.job, github.ref) }} + cancel-in-progress: true + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest ] + java: [ 17 ] + if: github.ref_type != 'tag' + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Setup Gradle + uses: ./.github/actions/gradle + + - name: Setup JDK + uses: ./.github/actions/jdk + with: + java-version: ${{ matrix.java }} + + - name: Build with Gradle + run: ./gradlew clean build --info + + - name: Upload build results + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.os }} Java ${{ matrix.java }} Snapshot + path: ${{ github.workspace }}/build/libs/ + + release: + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 17 ] + if: github.ref_type == 'tag' + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Setup Gradle + uses: ./.github/actions/gradle + + - name: Setup JDK + uses: ./.github/actions/jdk + with: + java-version: ${{ matrix.java }} + + - name: Set Release Environment Variable + if: github.ref_type == 'tag' + run: | + echo "CUSTOM_VERSION=${{ github.ref_name }}" >> $GITHUB_ENV + + - name: Build with Gradle + run: ./gradlew clean build -PcustomVersion=${{ env.CUSTOM_VERSION }} + + - name: Create Release + uses: softprops/action-gh-release@v1 + id: release + with: + name: ${{ format('Release {0}', github.ref_name) }} + files: ${{ github.workspace }}/build/libs/* + prerelease: ${{ contains(github.ref_name, '-RC-') }} + generate_release_notes: true + fail_on_unmatched_files: true + draft: false \ No newline at end of file diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..9bcad35 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,26 @@ +name: 'Close Stale Issues & PRs' +on: + schedule: + - cron: '30 1 * * *' + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + stale-issue-message: 'This issue has been automatically marked as stale because it has been open for 60 days with no activity.' + stale-pr-message: 'This PR has been automatically marked as stale because it has been open for 60 days with no activity.' + close-issue-message: 'This issue was closed because it has been stalled for -1 days with no activity.' + close-pr-message: 'This PR was closed because it has been stalled for -1 days with no activity.' + days-before-issue-stale: 60 + days-before-pr-stale: 60 + days-before-issue-close: -1 + days-before-pr-close: -1 + stale-issue-label: 'stale' + stale-pr-label: 'stale' \ No newline at end of file diff --git a/.gitignore b/.gitignore index 9b80541..24f40a2 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ .mtj.tmp/ *.class *.jar -*.oldWar +*.war *.ear *.nar hs_err_pid* diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..32df1e7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +darksaid9889@gmail.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b3dc4ec --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,44 @@ +## Pull Requests + +We use the [GitHub flow](https://guides.github.com/introduction/flow/) for contributions. + +1. Fork the repository. +2. Create a new branch for each feature, fix or improvement. +3. Send a pull request from each feature branch to the **main** branch. + +It is very important to separate new features or improvements into separate feature branches, and to send a pull request for each branch. This allow us to review and pull in new features or improvements individually. + +## Specifications + +### Commit Messages + +All commit messages should adhere to the [Conventional Commits specification](https://conventionalcommits.org/). + +#### Commit Types + +- API relevant changes + * `feat` Commits, that adds a new feature + * `fix` Commits, that fixes a bug/issue +- `refactor` Commits, that rewrite/restructure your code, however does not change any API behaviour + * `perf` Commits are special `refactor` commits, that improve performance +- `style` Commits, that do not affect the meaning (white-space, formatting, missing semi-colons, etc) +- `test` Commits, that add or correct existing tests +- `docs` Commits, that affect documentation only +- Tooling relevant changes + * `build` Commits, that affect build components like build tool, dependencies, project version, ... + * `ci` Commits, that affect CI configuration files and scripts +- `revert` Commits, that revert previous commits +- `chore` Miscellaneous commits without production code change, e.g. modifying `.gitignore` + +### Versioning + +Our project adheres to the [Semantic Versioning 2.0.0 specification](https://semver.org/) for versioning. + +### Style Guide + +Large refactors breaking the style defined in the `.editorconfig` file are frowned upon. +When contributing ensure your code follows existing conventions and styling. (*Any issues that arise will be noted in your pull request.*) + +## Licensing + +You must agree that your patch will be licensed under the main license found in this repository, and if we change the license, we will assume that you agreed with the change unless you object to the changes in time. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 48db873..6cde693 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,18 +1,28 @@ +import org.jooq.meta.jaxb.Logging +import java.time.Instant + plugins { `java-library` id("com.github.johnrengelman.shadow") version "8.1.1" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/ - id("xyz.jpenilla.run-paper") version "2.1.0" // Adds runServer and runMojangMappedServer tasks for testing + id("xyz.jpenilla.run-paper") version "2.2.2" // Adds runServer and runMojangMappedServer tasks for testing id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation - id("io.papermc.paperweight.userdev") version "1.5.5" // Used to develop internal plugins using Mojang mappings + id("io.papermc.paperweight.userdev") version "1.5.9" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight + id("org.flywaydb.flyway") version "10.8.1" // Database migrations + id("org.jooq.jooq-codegen-gradle") version "3.19.3" + + eclipse + idea } -group = "com.github.alathra.AlathranWars" -version = "3.0.0-SNAPSHOT-3" +group = "com.github.alathra" +version = "3.0.0" description = "" +val mainPackage = "${project.group}.${rootProject.name.lowercase()}" java { toolchain.languageVersion.set(JavaLanguageVersion.of(17)) // Configure the java toolchain. This allows gradle to auto-provision JDK 17 on systems that only have JDK 8 installed for example. +// withJavadocJar() // Enable Javadoc generation } repositories { @@ -34,7 +44,7 @@ repositories { } } - maven("https://repo.kryptonmc.org/releases/") { + maven("https://repo.kryptonmc.org/releases") { content { includeGroup("me.neznamy") } } @@ -48,55 +58,79 @@ repositories { } dependencies { - compileOnly("org.jetbrains:annotations:24.0.1") + compileOnly("org.jetbrains:annotations:24.1.0") + annotationProcessor("org.jetbrains:annotations:24.1.0") - paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT") - implementation("space.arim.morepaperlib:morepaperlib:0.4.3") + paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT") + implementation("space.arim.morepaperlib:morepaperlib:latest.release") - implementation("com.github.milkdrinkers:simplixstorage:3.2.7") + implementation("com.github.milkdrinkers:crate:1.1.0") implementation("com.github.milkdrinkers:colorparser:2.0.0") { - exclude(group = "net.kyori", module = "adventure-api") + exclude("net.kyori") } + implementation("dev.jorel:commandapi-bukkit-shade:9.3.0") + + compileOnly("me.clip:placeholderapi:2.11.5") { + exclude("me.clip.placeholderapi.libs", "kyori") + } compileOnly("com.github.MilkBowl:VaultAPI:1.7") - - compileOnly("com.palmergames.bukkit.towny:towny:0.99.5.7") { - exclude(group = "com.palmergames.adventure") - } - - compileOnly("me.neznamy:tab-api:4.0.0") - - implementation("dev.jorel:commandapi-bukkit-shade:9.0.3") { - exclude(group = "net.kyori", module = "adventure-api") - } - compileOnly("dev.jorel:commandapi-annotations:9.0.3") - annotationProcessor("dev.jorel:commandapi-annotations:9.0.3") - - implementation("com.zaxxer:HikariCP:5.0.1") - implementation("org.mariadb.jdbc:mariadb-java-client:3.1.4") { - isTransitive = false - } - - compileOnly("me.clip:placeholderapi:2.11.3") { - exclude(group = "me.clip.placeholderapi.libs", module = "kyori") + compileOnly("com.palmergames.bukkit.towny:towny:0.100.0.8") { + exclude("com.palmergames.adventure") } + compileOnly("me.neznamy:tab-api:4.0.2") compileOnly(files("lib/Graves-4.9.jar")) - compileOnly("com.github.Gecolay.GSit:core:1.4.9") + compileOnly("com.github.Gecolay.GSit:core:1.5.0") compileOnly(files("lib/HeadsPlus-7.0.14.jar")) + compileOnly(files("lib/Skulls.jar")) + + // Database Dependencies + implementation("com.zaxxer:HikariCP:5.1.0") + library("org.flywaydb:flyway-core:10.8.1") + library("org.flywaydb:flyway-mysql:10.8.1") + library("org.flywaydb:flyway-database-hsqldb:10.8.1") + library("org.jooq:jooq:3.19.3") + jooqCodegen("com.h2database:h2:2.2.224") + + // JDBC Drivers + library("org.hsqldb:hsqldb:2.7.2") + library("com.h2database:h2:2.2.224") + library("com.mysql:mysql-connector-j:8.3.0") + library("org.mariadb.jdbc:mariadb-java-client:3.3.2") } tasks { + assemble { + dependsOn(reobfJar) + } + build { dependsOn(shadowJar) } + jooqCodegen { + dependsOn(flywayMigrate) + } + compileJava { options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything // Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable. // See https://openjdk.java.net/jeps/247 for more information. options.release.set(17) - options.compilerArgs.add("-Xlint:-deprecation") + options.compilerArgs.addAll(arrayListOf("-Xlint:all", "-Xlint:-processing", "-Xdiags:verbose")) + + dependsOn(jooqCodegen) // Generate jOOQ sources before compilation + } + + javadoc { + isFailOnError = false + exclude("${mainPackage.replace(".", "/")}/db/schema/**") // Exclude generated jOOQ sources from javadocs + val options = options as StandardJavadocDocletOptions + options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything + options.overview = "src/main/javadoc/overview.html" + options.tags("apiNote:a:API Note:", "implNote:a:Implementation Note:", "implSpec:a:Implementation Requirements:") + options.use() } processResources { @@ -108,40 +142,118 @@ tasks { archiveClassifier.set("") // Shadow classes - // helper function to relocate a package into our package - fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${project.group}.${targetPkg}") + fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${mainPackage}.lib.${targetPkg}") reloc("space.arim.morepaperlib", "morepaperlib") - reloc("de.leonhard.storage", "storageapi") + reloc("com.github.milkdrinkers.Crate", "crate") + reloc("com.github.milkdrinkers.colorparser", "colorparser") reloc("dev.jorel.commandapi", "commandapi") reloc("com.zaxxer.hikari", "hikaricp") - reloc("org.mariadb.jdbc", "mariadb") + + mergeServiceFiles { + setPath("META-INF/services/org.flywaydb.core.extensibility.Plugin") // Fix Flyway overriding its own files + } + + minimize() } runServer { // Configure the Minecraft version for our task. - minecraftVersion("1.19.4") - jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005") + minecraftVersion("1.20.1") + + // IntelliJ IDEA debugger setup: https://docs.papermc.io/paper/dev/debugging#using-a-remote-debugger + jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true", "-DIReallyKnowWhatIAmDoingISwear") systemProperty("terminal.jline", false) systemProperty("terminal.ansi", true) + + // Automatically install dependencies + downloadPlugins { + url("https://ci.dmulloy2.net/job/ProtocolLib/lastStableBuild/artifact/build/libs/ProtocolLib.jar") + github("MilkBowl", "Vault", "1.7.3", "Vault.jar") + url("https://download.luckperms.net/1521/bukkit/loader/LuckPerms-Bukkit-5.4.108.jar") + modrinth("tab-was-taken", "4.1.2") + github("PlaceholderAPI", "PlaceholderAPI", "2.11.4", "PlaceholderAPI-2.11.4.jar") +// url("https://www.spigotmc.org/resources/skulls-the-ultimate-head-database.90098/download?version=520217/Skulls.jar") + } } } -bukkit { +bukkit { // Options: https://github.com/Minecrell/plugin-yml#bukkit // Plugin main class (required) - main = "${project.group}.Main" + main = "${mainPackage}.${rootProject.name}" // Plugin Information name = project.name - prefix = "AlathranWars" + prefix = project.name version = "${project.version}" description = "${project.description}" authors = listOf("darksaid98", "ShermansWorld", "NinjaMandalorian", "AubriTheHuman") contributors = listOf() - apiVersion = "1.19" + apiVersion = "1.20" // Misc properties load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD // STARTUP or POSTWORLD depend = listOf("Vault", "Towny") - softDepend = listOf("TAB") -} \ No newline at end of file + softDepend = listOf("PlaceholderAPI", "TAB", "Skulls", "HeadsPlus") +} + +flyway { + url = "jdbc:h2:${project.layout.buildDirectory.get()}/generated/flyway/db;AUTO_SERVER=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE;IGNORECASE=TRUE" + user = "sa" + password = "" + schemas = listOf("PUBLIC").toTypedArray() + placeholders = mapOf( // Substitute placeholders for flyway + "tablePrefix" to "", + "columnSuffix" to " VIRTUAL", + "tableDefaults" to "", + "uuidType" to "BINARY(16)", + "inetType" to "VARBINARY(16)", + "binaryType" to "BLOB", + "alterViewStatement" to "ALTER VIEW", + ) + validateMigrationNaming = true + baselineOnMigrate = true + cleanDisabled = false + locations = arrayOf( + "filesystem:src/main/resources/db/migration", + "classpath:db/migration" + ) +} + +jooq { + configuration { + logging = Logging.ERROR + jdbc { + driver = "org.h2.Driver" + url = flyway.url + user = flyway.user + password = flyway.password + } + generator { + database { + name = "org.jooq.meta.h2.H2Database" + includes = ".*" + excludes = "(flyway_schema_history)|(?i:information_schema\\..*)|(?i:system_lobs\\..*)" // Exclude db specific files + inputSchema = "PUBLIC" + schemaVersionProvider = "SELECT :schema_name || '_' || MAX(\"version\") FROM \"flyway_schema_history\"" // Grab version from Flyway + } + target { + packageName = "${mainPackage}.db.schema" + directory = layout.buildDirectory.dir("generated-src/jooq").get().toString() + withClean(true) + } + } + } +} + +// Apply custom version arg +val versionArg = if (hasProperty("customVersion")) + (properties["customVersion"] as String).uppercase() // Uppercase version string +else + "${project.version}-SNAPSHOT-${Instant.now().epochSecond}" // Append snapshot to version + +// Strip prefixed "v" from version tag +project.version = if (versionArg.first().equals('v', true)) + versionArg.substring(1) +else + versionArg.uppercase() \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..fc40dfd --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.caching=true +org.gradle.parallel=true +org.gradle.daemon=true +org.gradle.jvmargs=-Xmx2048M \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index ccebba7..7f93135 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 42defcc..3fa8f86 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 index 121251c..1aa94a4 --- a/gradlew +++ b/gradlew @@ -69,33 +69,31 @@ app_path=$0 # Need this for daisy-chained symlinks. while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do - ls=$(ls -ld "$app_path") + ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$(cd "${APP_HOME:-./}" && pwd -P) || exit - -# 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"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum -warn() { +warn () { echo "$*" } >&2 -die() { +die () { echo echo "$*" echo @@ -107,24 +105,25 @@ cygwin=false msys=false darwin=false nonstop=false -case "$(uname)" in #( -CYGWIN*) cygwin=true ;; #( -Darwin*) darwin=true ;; #( -MSYS* | 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 + # Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then +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 + 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 @@ -132,30 +131,31 @@ 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. + 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 +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( - max*) + max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 - MAX_FD=$(ulimit -H -n) || + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" - ;; esac - case $MAX_FD in #( - '' | soft) : ;; #( - *) + 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=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" - ;; esac fi @@ -168,25 +168,23 @@ fi # * 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") +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - JAVACMD=$(cygpath --unix "$JAVACMD") + JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg; do + 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 ;; + 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") + 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 @@ -195,25 +193,30 @@ if "$cygwin" || "$msys"; then # 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 + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# 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 \ - "$@" + "-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 +if ! command -v xargs >/dev/null 2>&1 +then die "xargs is not available" fi @@ -237,10 +240,10 @@ fi # eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + 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 old mode 100644 new mode 100755 diff --git a/lib/Graves-4.9.jar b/lib/Graves-4.9.jar new file mode 100644 index 0000000..dd56fcb Binary files /dev/null and b/lib/Graves-4.9.jar differ diff --git a/lib/HeadsPlus-7.0.14.jar b/lib/HeadsPlus-7.0.14.jar new file mode 100644 index 0000000..6941d31 Binary files /dev/null and b/lib/HeadsPlus-7.0.14.jar differ diff --git a/settings.gradle.kts b/settings.gradle.kts index c43136f..8c6c031 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,7 +1,12 @@ pluginManagement { repositories { gradlePluginPortal() + mavenCentral() } } +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0") +} + rootProject.name = "AlathranWars" \ No newline at end of file diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/Conflict.java b/src/main/java/com/github/alathra/AlathranWars/conflict/Conflict.java deleted file mode 100644 index 8cd6592..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/Conflict.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.github.alathra.AlathranWars.conflict; - -import com.github.alathra.AlathranWars.enums.ConflictType; - -public class Conflict { - private ConflictType conflictType; -} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java b/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java deleted file mode 100644 index 462a721..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.github.alathra.AlathranWars.conflict; - -import com.github.alathra.AlathranWars.conflict.battle.raid.Raid; -import com.github.alathra.AlathranWars.conflict.battle.siege.Siege; -import com.github.alathra.AlathranWars.utility.SQLQueries; -import com.palmergames.bukkit.towny.object.Nation; -import com.palmergames.bukkit.towny.object.Town; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.inject.Singleton; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; - -@Singleton -public class WarManager { - private static WarManager instance; - private @NotNull Set wars = new HashSet<>(); - - private WarManager() { - if (instance != null) - Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton"); - } - - @NotNull - public static WarManager getInstance() { - if (instance == null) - instance = new WarManager(); - - return instance; - } - - public void loadAll() { - wars = SQLQueries.loadAll(); - } - - @NotNull - public Set getWars() { - return wars; - } - - @Nullable - public War getWar(String warName) { - for (@NotNull War war : wars) - if (war.equals(warName)) return war; - - return null; - } - - @Nullable - public War getWar(UUID uuid) { - for (@NotNull War war : wars) - if (war.equals(uuid)) return war; - - return null; - } - - @Nullable - public Side getSide(UUID uuid) { - for (@NotNull War war : wars) - if (war.getSide(uuid) != null) return war.getSide(uuid); - - return null; - } - - @Nullable - public Siege getSiege(UUID uuid) { - for (@NotNull War war : wars) - if (war.getSiege(uuid) != null) return war.getSiege(uuid); - - return null; - } - - public void addWar(War war) { - wars.add(war); - } - - public void removeWar(War war) { - wars.remove(war); - } - - public boolean isPlayerInAnyWars(UUID uuid) { - for (@NotNull War war : wars) { - if (war.isPlayerInWar(uuid)) return true; - } - return false; - } - - public boolean isPlayerInAnyWars(@NotNull Player p) { - return isPlayerInAnyWars(p.getUniqueId()); - } - - public @NotNull Set getPlayerWars(@NotNull Player p) { - return getPlayerWars(p.getUniqueId()); - } - - public @NotNull Set getPlayerWars(UUID uuid) { - return wars.stream() - .filter(war -> war.isPlayerInWar(uuid)) - .collect(Collectors.toSet()); - } - - public boolean isTownInAnyWars(Town town) { - for (@NotNull War war : wars) { - if (war.isTownInWar(town)) return true; - } - return false; - } - - public @NotNull Set getTownWars(Town town) { - return wars.stream() - .filter(war -> war.isTownInWar(town)) - .collect(Collectors.toSet()); - } - - public boolean isNationInAnyWars(Nation nation) { - for (@NotNull War war : wars) { - if (war.isNationInWar(nation)) return true; - } - return false; - } - - public @NotNull Set getNationWars(Nation nation) { - return wars.stream() - .filter(war -> war.isNationInWar(nation)) - .collect(Collectors.toSet()); - } - - @NotNull - public List getWarNames() { - return wars.stream() - .map(War::getName) - .sorted(String::compareToIgnoreCase) - .collect(Collectors.toList()); - } - - @NotNull - public List getWarLabels() { - return wars.stream() - .map(War::getLabel) - .sorted(String::compareToIgnoreCase) - .collect(Collectors.toList()); - } - - @NotNull - public Set getSieges() { - return getWars().stream() - .map(War::getSieges) - .flatMap(Set::stream) - .collect(Collectors.toSet()); - } - - @NotNull - public Set getRaids() { - return getWars().stream() - .map(War::getRaids) - .flatMap(Set::stream) - .collect(Collectors.toSet()); - } - - public boolean isPlayerInAnySiege(@NotNull Player p) { - return isPlayerInAnySiege(p.getUniqueId()); - } - - public boolean isPlayerInAnySiege(UUID uuid) { - for (@NotNull Siege siege : getSieges()) { - if (siege.isPlayerInSiege(uuid)) return true; - } - - return false; - } - - public @NotNull Set getPlayerSieges(@NotNull Player p) { - return getPlayerSieges(p.getUniqueId()); - } - - public @NotNull Set getPlayerSieges(UUID uuid) { - return getSieges().stream() - .filter(siege -> siege.isPlayerInSiege(uuid)) - .collect(Collectors.toSet()); - } - - public @NotNull Set getNationsAtWar() { - return getWars().stream() - .map(War::getNations) - .flatMap(Set::stream) - .collect(Collectors.toSet()); - } - - public @NotNull Set getTownsAtWar() { - return getWars().stream() - .map(War::getTowns) - .flatMap(Set::stream) - .collect(Collectors.toSet()); - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java deleted file mode 100644 index 9c28f91..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.github.alathra.AlathranWars.conflict.battle; - -public class Battle { - /*private int attackerPoints; - private int defenderPoints; - - public int getAttackerPoints() { - return this.attackerPoints; - } - - public void setAttackerPoints(int points) { - this.attackerPoints = points; - } - - public int getDefenderPoints() { - return this.defenderPoints; - } - - public void setDefenderPoints(int points) { - this.defenderPoints = points; - } - - public void addPointsToAttackers(final int points) { - this.attackerPoints += points; - } - - public void addPointsToDefenders(final int points) { - this.defenderPoints += points; - }*/ -} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java deleted file mode 100644 index a8b3888..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.github.alathra.AlathranWars.conflict.battle.raid; - -import com.github.alathra.AlathranWars.conflict.battle.Battle; - -public class Raid extends Battle { -} diff --git a/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java b/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java deleted file mode 100644 index e6b7e17..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.github.alathra.AlathranWars.data; - -import com.github.alathra.AlathranWars.Main; -import de.leonhard.storage.Config; - -public class ConfigManager { - private final Main instance; - private Config cfg; - - public ConfigManager(Main instance) { - this.instance = instance; - } - - public void onLoad() { - cfg = new Config("config", instance.getDataFolder().getPath(), instance.getResource("config.yml")); - } - - public void onEnable() { - } - - public void onDisable() { - - } - - public Config getConfig() { - return cfg; - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java b/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java deleted file mode 100644 index 726d209..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.github.alathra.AlathranWars.data; - -import com.github.alathra.AlathranWars.Main; -import com.github.alathra.AlathranWars.utility.Config; -import com.github.alathra.AlathranWars.utility.SQLQueries; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; - -public class DataManager { - private final Main instance; - private HikariDataSource hikariDataSource; - - public DataManager(Main instance) { - this.instance = instance; - } - - public void onLoad() { - openConnection(); - SQLQueries.initDB(); - } - - public void onEnable() { - } - - public void onDisable() { - closeDatabaseConnection(); - } - - @NotNull - public Connection getConnection() throws SQLException { - if (hikariDataSource == null) - throw new SQLException("Unable to get a connection from the pool. (hikariDataSource is null)"); - - Connection connection = hikariDataSource.getConnection(); - if (connection == null) - throw new SQLException("Unable to get a connection from the pool. (HikariDataSource#getConnection returned null)"); - - return connection; - } - - @NotNull - public HikariDataSource getDataSource() { - return hikariDataSource; - } - - private void openConnection() { - if (hikariDataSource != null) - return; - - HikariConfig hikariConfig = new HikariConfig(); - - final boolean mysqlEnabled = Config.get().getBoolean("mysql.enabled"); - - if (mysqlEnabled) { - hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource"); - hikariConfig.addDataSourceProperty("url", "jdbc:mariadb://%s/%s".formatted( - Config.get().get("mysql.host", "127.0.0.1:3306"), - Config.get().get("mysql.database", "database") - )); - hikariConfig.setUsername(Config.get().get("mysql.user", "username")); - hikariConfig.setPassword(Config.get().get("mysql.pass", "123")); - hikariConfig.setConnectionTimeout(5000); - hikariConfig.setKeepaliveTime(0); - } else { - @NotNull File dataFolder = new File(instance.getDataFolder(), "database.db"); - - if (!dataFolder.exists()) { - try { - if (!dataFolder.createNewFile()) - instance.getLogger().severe("File write error: database.db (1)"); - } catch (IOException e) { - instance.getLogger().severe("File write error: database.db (2) - %s".formatted(e.getMessage())); - } - } - - hikariConfig.setJdbcUrl("jdbc:sqlite:" + dataFolder); - hikariConfig.setConnectionInitSql("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=30000"); - hikariConfig.setConnectionTimeout(30000); - } - - hikariConfig.setPoolName("althranwars-hikari"); - hikariConfig.setMaximumPoolSize(10); - hikariConfig.setMinimumIdle(10); - hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection - - hikariDataSource = new HikariDataSource(hikariConfig); - } - - private void closeDatabaseConnection() { - instance.getLogger().info("Closing database connection..."); - - if (hikariDataSource == null) { - instance.getLogger().severe("Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!"); - return; - } - - if (hikariDataSource.isClosed()) { - instance.getLogger().info("Skipped closing database connection: connection is already closed."); - return; - } - - try { - hikariDataSource.close(); - } catch (Exception e) { - instance.getLogger().severe("Error closing database connections:"); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java b/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java deleted file mode 100644 index 1843b15..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.github.alathra.AlathranWars.enums; - -public enum BattleTeam { - SIDE_1, - SIDE_2, -} diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/ConflictType.java b/src/main/java/com/github/alathra/AlathranWars/enums/ConflictType.java deleted file mode 100644 index 8d7730c..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/enums/ConflictType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.github.alathra.AlathranWars.enums; - -public enum ConflictType { - WAR -} diff --git a/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java deleted file mode 100644 index 5be9040..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.github.alathra.AlathranWars.events; - -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class WarCreateEvent extends Event implements Cancellable { - private static final HandlerList HANDLER_LIST = new HandlerList(); - private boolean cancelled; - - /** - * Gets the cancellation state of this event. A cancelled event will not - * be executed in the server, but will still pass to other plugins - * - * @return true if this event is cancelled - */ - @Override - public boolean isCancelled() { - return this.cancelled; - } - - /** - * Sets the cancellation state of this event. A cancelled event will not - * be executed in the server, but will still pass to other plugins. - * - * @param cancelled true if you wish to cancel this event - */ - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @Override - public @NotNull HandlerList getHandlers() { - return HANDLER_LIST; - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java deleted file mode 100644 index f6d50ed..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.github.alathra.AlathranWars.events.battle; - -public class PreSiegeEndEvent { -} diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java deleted file mode 100644 index 2e3995d..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.github.alathra.AlathranWars.events.battle; - -public class PreSiegeStartEvent { -} diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java deleted file mode 100644 index fa9ef1b..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.github.alathra.AlathranWars.events.battle; - -public class SiegeEndEvent { -} diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java deleted file mode 100644 index 6540644..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.github.alathra.AlathranWars.events.battle; - -public class SiegeStartEvent { -} diff --git a/src/main/java/com/github/alathra/AlathranWars/hooks/HookManager.java b/src/main/java/com/github/alathra/AlathranWars/hooks/HookManager.java deleted file mode 100644 index a443b1f..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/hooks/HookManager.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.github.alathra.AlathranWars.hooks; - -public class HookManager { - public HookManager() { - - } - - public void onLoad() { - - - } - - public void onEnable() { - TABHook.init(); - TownyHook.init(); - } - - public void onDisable() { - - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/hooks/TABHook.java b/src/main/java/com/github/alathra/AlathranWars/hooks/TABHook.java deleted file mode 100644 index 6113e0d..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/hooks/TABHook.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.github.alathra.AlathranWars.hooks; - -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener; -import com.github.alathra.AlathranWars.utility.UtilsChat; -import me.neznamy.tab.api.TabAPI; -import me.neznamy.tab.api.TabPlayer; -import me.neznamy.tab.api.event.EventBus; -import me.neznamy.tab.api.event.player.PlayerLoadEvent; -import me.neznamy.tab.api.nametag.UnlimitedNameTagManager; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class TABHook { - private static boolean enabled = false; - private static TabAPI tabAPI; - - public static void init() { - if (enabled) return; - - try { - tabAPI = TabAPI.getInstance(); - enabled = true; - - registerPlayerLoadListener(); - } catch (NoClassDefFoundError ignored) { - } - } - - private static void registerPlayerLoadListener() { - if (!enabled) return; - - @Nullable EventBus eventBus = tabAPI.getEventBus(); - if (eventBus == null) return; - - eventBus.register(PlayerLoadEvent.class, e -> { - @NotNull TabPlayer tabPlayer = e.getPlayer(); - if (tabPlayer.getPlayer() instanceof Player p) - PlayerJoinListener.checkPlayer(p); - }); - } - - public static void assignSide1WarSuffix(@NotNull Player p, @NotNull War war) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, - UtilsChat.color(" &c[" + war.getSide1().getName() + "]&r") - ); - - if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) { - unm.setPrefix(tabPlayer, "&c"); - } - } - - public static void assignSide2WarSuffix(@NotNull Player p, @NotNull War war) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, UtilsChat.color(" &9[") + war.getSide2().getName() + "]&r"); - - if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) { - unm.setPrefix(tabPlayer, "&9"); - } - } - - public static void assignSide1WarSuffixMerc(@NotNull Player p, @NotNull War war) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, - UtilsChat.color(" &a[M]&c[") + war.getSide1() + "]&r"); - } - - public static void assignSide2WarSuffixMerc(@NotNull Player p, @NotNull War war) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, - UtilsChat.color(" &a[M]&9[") + war.getSide2() + "]&r"); - } - - public static void resetSuffix(@NotNull Player p) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null); - } - - public static void resetSuffix(@NotNull String username) { - if (!enabled) return; - - @NotNull - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username); - - try { - if (offlinePlayer.isOnline()) { - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(username); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null); - } - } catch (NullPointerException ignored) { - } - } - - public static void resetPrefix(@NotNull Player p) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null); - - if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) { - unm.setPrefix(tabPlayer, null); - } - } - - public static void resetPrefix(@NotNull String playername) { - if (!enabled) return; - - @NotNull - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playername); - try { - if (offlinePlayer.isOnline()) { - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(playername); - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null); - } - } catch (NullPointerException ignored) { - } - } - - public static void removeColorPrefix(@NotNull Player p, @NotNull String prefix) { - if (!enabled) return; - - @Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); - - if (prefix.length() > 2) { - prefix = prefix.substring(0, prefix.length() - 2); - } else { - Bukkit.getLogger().info("There is an error when removing a color prefix, prefix not long enough:"); - Bukkit.getLogger().info("Player: " + p.displayName()); - Bukkit.getLogger().info("Prefix: " + prefix); - Bukkit.getLogger().info("------"); - } - - - if (tabAPI.getTabListFormatManager() == null) return; - - tabAPI.getTabListFormatManager().setPrefix(tabPlayer, UtilsChat.color(prefix)); - } - -} \ No newline at end of file diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java b/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java deleted file mode 100644 index 3f7f016..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.github.alathra.AlathranWars.listeners; - -import com.github.alathra.AlathranWars.Main; -import com.github.alathra.AlathranWars.listeners.items.PlayerInteractListener; -import com.github.alathra.AlathranWars.listeners.siege.BlockBreakPlaceListener; -import com.github.alathra.AlathranWars.listeners.siege.PlayerDeathListener; -import com.github.alathra.AlathranWars.listeners.siege.PlayerQuitListener; -import com.github.alathra.AlathranWars.listeners.siege.PlayerSitListener; -import com.github.alathra.AlathranWars.listeners.war.NationListener; -import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener; -import com.github.alathra.AlathranWars.listeners.war.TownListener; - -/** - * A class to handle registration of event listeners. - */ -public class ListenerHandler { - private final Main instance; - - public ListenerHandler(Main instance) { - this.instance = instance; - } - - public void onLoad() { - - } - - public void onEnable() { - // Sieges - instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.siege.PlayerJoinListener(), instance); - instance.getServer().getPluginManager().registerEvents(new PlayerQuitListener(), instance); - instance.getServer().getPluginManager().registerEvents(new BlockBreakPlaceListener(), instance); - instance.getServer().getPluginManager().registerEvents(new PlayerDeathListener(), instance); - instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance); - - // Wars - instance.getServer().getPluginManager().registerEvents(new NationListener(), instance); - instance.getServer().getPluginManager().registerEvents(new TownListener(), instance); - instance.getServer().getPluginManager().registerEvents(new PlayerJoinListener(), instance); - instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.war.PlayerQuitListener(), instance); - - instance.getServer().getPluginManager().registerEvents(new CommandsListener(), instance); - instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance); - } - - public void onDisable() { - - } -} \ No newline at end of file diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/war/PlayerJoinListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/war/PlayerJoinListener.java deleted file mode 100644 index 1e8817e..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/listeners/war/PlayerJoinListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.github.alathra.AlathranWars.listeners.war; - -import com.github.alathra.AlathranWars.conflict.Side; -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.hooks.TABHook; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; - -public class PlayerJoinListener implements Listener { - public static void checkPlayer(@NotNull Player p) { - final @NotNull UUID uuid = p.getUniqueId(); - - if (WarManager.getInstance().isPlayerInAnyWars(uuid)) { - for (final @NotNull War war : WarManager.getInstance().getWars()) { - if (war.getSide1().isPlayerOnSide(uuid) && !war.getSide1().isPlayerSurrendered(uuid)) { - TABHook.assignSide1WarSuffix(p, war); - } else if (war.getSide2().isPlayerOnSide(uuid) && !war.getSide2().isPlayerSurrendered(uuid)) { - TABHook.assignSide2WarSuffix(p, war); - } else if (war.getSide1().isPlayerSurrendered(uuid) || war.getSide2().isPlayerSurrendered(uuid)) { - TABHook.resetPrefix(p); - } - } - } else { - TABHook.resetPrefix(p); - } - } - - @EventHandler - private void onPlayerJoin(@NotNull PlayerJoinEvent e) { - final @NotNull Player p = e.getPlayer(); - if (WarManager.getInstance().isPlayerInAnyWars(p)) { - for (@NotNull War war : WarManager.getInstance().getWars()) { - if (war.isPlayerInWar(p)) { - @Nullable Side side = war.getPlayerSide(p); - if (side != null) { - side.addOnlinePlayer(p); - } - } - } - } - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/Config.java b/src/main/java/com/github/alathra/AlathranWars/utility/Config.java deleted file mode 100644 index 8cd4d45..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/utility/Config.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.github.alathra.AlathranWars.utility; - -import com.github.alathra.AlathranWars.Main; -import org.jetbrains.annotations.NotNull; - -/** - * Convenience class for accessing {@link com.github.alathra.AlathranWars.data.ConfigManager} - */ -public abstract class Config { - public static @NotNull de.leonhard.storage.Config get() { - return Main.getInstance().getConfigManager().getConfig(); - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/DB.java b/src/main/java/com/github/alathra/AlathranWars/utility/DB.java deleted file mode 100644 index e13cb42..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/utility/DB.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.github.alathra.AlathranWars.utility; - -import com.github.alathra.AlathranWars.Main; -import com.zaxxer.hikari.HikariDataSource; -import org.jetbrains.annotations.NotNull; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Convenience class for accessing {@link com.github.alathra.AlathranWars.data.DataManager } - */ -public abstract class DB { - public static @NotNull Connection get() throws SQLException { - return Main.getInstance().getDataManager().getConnection(); - } - - public static @NotNull HikariDataSource getDataSource() { - return Main.getInstance().getDataManager().getDataSource(); - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java b/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java deleted file mode 100644 index 9c4a434..0000000 --- a/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java +++ /dev/null @@ -1,629 +0,0 @@ -package com.github.alathra.AlathranWars.utility; - -import com.github.alathra.AlathranWars.conflict.Side; -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.conflict.battle.siege.Siege; -import com.github.alathra.AlathranWars.enums.BattleSide; -import com.github.alathra.AlathranWars.enums.BattleTeam; -import com.palmergames.bukkit.towny.TownyAPI; -import com.palmergames.bukkit.towny.object.Nation; -import com.palmergames.bukkit.towny.object.Town; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.sql.*; -import java.time.Instant; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -/** - * Convenience class for defining and executing SQL queries - */ -public abstract class SQLQueries { - public static void initDB() { - try (final Statement statement = DB.get().createStatement()) { - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_list` ( - `uuid` uuid NOT NULL DEFAULT uuid(), - `name` tinytext NOT NULL, - `label` tinytext NOT NULL, - `side1` uuid NOT NULL DEFAULT uuid(), - `side2` uuid NOT NULL DEFAULT uuid(), - PRIMARY KEY (`uuid`), - KEY `side2` (`side2`), - KEY `side1` (`side1`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides` ( - `war` uuid NOT NULL, - `uuid` uuid NOT NULL, - `side` tinytext NOT NULL, - `team` tinytext NOT NULL, - `name` tinytext NOT NULL, - `town` uuid NOT NULL, - `siegeGrace` timestamp NOT NULL, - `raidGrace` timestamp NOT NULL, - PRIMARY KEY (`uuid`), - KEY `town` (`town`), - KEY `war` (`war`), - CONSTRAINT `war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_nations` ( - `side` uuid NOT NULL, - `nation` uuid NOT NULL, - KEY `side_nations` (`side`), - CONSTRAINT `side_nations` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_nations_surrendered` ( - `side` uuid NOT NULL, - `nation` uuid NOT NULL, - KEY `side_nations_surrendered` (`side`), - CONSTRAINT `side_nations_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_players` ( - `side` uuid NOT NULL, - `player` uuid NOT NULL, - KEY `side_players` (`side`), - CONSTRAINT `side_players` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_players_surrendered` ( - `side` uuid NOT NULL, - `player` uuid NOT NULL, - KEY `side_players_surrendered` (`side`), - CONSTRAINT `side_players_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_towns` ( - `side` uuid NOT NULL, - `town` uuid NOT NULL, - KEY `side_towns` (`side`), - CONSTRAINT `side_towns` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sides_towns_surrendered` ( - `side` uuid NOT NULL, - `town` uuid NOT NULL, - KEY `side_towns_surrendered` (`side`), - CONSTRAINT `side_towns_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sieges` ( - `war` uuid NOT NULL, - `uuid` uuid NOT NULL, - `town` uuid NOT NULL, - `siegeLeader` uuid NOT NULL, - `endTime` timestamp NOT NULL, - `lastTouched` timestamp NOT NULL, - `siegeProgress` int(11) NOT NULL, - PRIMARY KEY (`uuid`), - KEY `siege_war` (`war`), - CONSTRAINT `siege_war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sieges_players_attackers` ( - `siege` uuid NOT NULL, - `player` uuid NOT NULL, - KEY `siege_players_attackers` (`siege`), - CONSTRAINT `siege_players_attackers` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.addBatch(""" - CREATE TABLE IF NOT EXISTS `wars_sieges_players_defenders` ( - `siege` uuid NOT NULL, - `player` uuid NOT NULL, - KEY `siege_players_defenders` (`siege`), - CONSTRAINT `siege_players_defenders` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; - """); - - statement.executeLargeBatch(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public static void saveAll() { - try ( - @NotNull Connection con = DB.get(); - PreparedStatement warStatement = con.prepareStatement("INSERT INTO `wars_list` (`uuid`, `name`, `label`, `side1`, `side2`) VALUES (?, ?, ?, ?, ?) " - + "ON DUPLICATE KEY UPDATE `name` = ?, `label` = ?, `side1` = ?, `side2` = ?") - ) { - // Save wars - for (@NotNull War war : WarManager.getInstance().getWars()) { - // Insert - warStatement.setString(1, war.getUUID().toString()); - warStatement.setString(2, war.getName()); - warStatement.setString(3, war.getLabel()); - warStatement.setString(4, war.getSide1().getUUID().toString()); - warStatement.setString(5, war.getSide2().getUUID().toString()); - - // Update - warStatement.setString(6, war.getName()); - warStatement.setString(7, war.getLabel()); - warStatement.setString(8, war.getSide1().getUUID().toString()); - warStatement.setString(9, war.getSide2().getUUID().toString()); - - warStatement.executeUpdate(); - - // Save sides - for (@NotNull Side side : war.getSides()) { - saveSide(con, side); - } - - // Save sieges - for (@NotNull Siege siege : war.getSieges()) { - saveSiege(con, siege); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void saveSide(@NotNull Connection con, @NotNull Side side) { - try ( - PreparedStatement sideStatement = con.prepareStatement("INSERT INTO `wars_sides` (`war`, `uuid`, `side`, `team`, `name`, `town`, `siegeGrace`, `raidGrace`) VALUES (?, ?, ?, ?, ?, ?, ?, ?) " - + "ON DUPLICATE KEY UPDATE `side` = ?, `team` = ?, `name` = ?, `town` = ?, `siegeGrace` = ?, `raidGrace` = ?") - ) { - // Insert - sideStatement.setString(1, side.getWar().getUUID().toString()); - sideStatement.setString(2, side.getUUID().toString()); - sideStatement.setString(3, side.getSide().toString()); - sideStatement.setString(4, side.getTeam().toString()); - sideStatement.setString(5, side.getName()); - sideStatement.setString(6, side.getTown().getUUID().toString()); - sideStatement.setTimestamp(7, Timestamp.from(side.getSiegeGrace())); - sideStatement.setTimestamp(8, Timestamp.from(side.getRaidGrace())); - - // Update - sideStatement.setString(9, side.getSide().toString()); - sideStatement.setString(10, side.getTeam().toString()); - sideStatement.setString(11, side.getName()); - sideStatement.setString(12, side.getTown().getUUID().toString()); - sideStatement.setTimestamp(13, Timestamp.from(side.getSiegeGrace())); - sideStatement.setTimestamp(14, Timestamp.from(side.getRaidGrace())); - - sideStatement.executeUpdate(); - - saveSideNations(con, side, false); - saveSideNations(con, side, true); - saveSideTowns(con, side, false); - saveSideTowns(con, side, true); - saveSidePlayers(con, side, false); - saveSidePlayers(con, side, true); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void saveSideNations(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException { - try ( - PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations")); - PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `nation`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations")) - ) { - try { - // Transaction start - con.setAutoCommit(false); - - // Delete old - deleteStatement.setString(1, side.getUUID().toString()); - deleteStatement.executeUpdate(); - - // Insert new - for (@NotNull Nation nation : (surrendered ? side.getSurrenderedNations() : side.getNations())) { - insertStatement.setString(1, side.getUUID().toString()); - insertStatement.setString(2, nation.getUUID().toString()); - insertStatement.executeUpdate(); - } - - // Transaction end - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - } - } - - private static void saveSideTowns(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException { - try ( - PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns")); - PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `town`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns")) - ) { - try { - // Transaction start - con.setAutoCommit(false); - - // Delete old - deleteStatement.setString(1, side.getUUID().toString()); - deleteStatement.executeUpdate(); - - // Insert new - for (@NotNull Town town : (surrendered ? side.getSurrenderedTowns() : side.getTowns())) { - insertStatement.setString(1, side.getUUID().toString()); - insertStatement.setString(2, town.getUUID().toString()); - insertStatement.executeUpdate(); - } - - // Transaction end - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - } - } - - private static void saveSidePlayers(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException { - try ( - PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players")); - PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `player`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players")) - ) { - try { - // Transaction start - con.setAutoCommit(false); - - // Delete old - deleteStatement.setString(1, side.getUUID().toString()); - deleteStatement.executeUpdate(); - - // Insert new - for (@NotNull UUID uuid : (surrendered ? side.getSurrenderedPlayersIncludingOffline() : side.getPlayersIncludingOffline())) { - insertStatement.setString(1, side.getUUID().toString()); - insertStatement.setString(2, uuid.toString()); - insertStatement.executeUpdate(); - } - - // Transaction end - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - } - } - - public static @NotNull Set loadAll() { - @NotNull Set wars = new HashSet<>(); - - try ( - @NotNull Connection con = DB.get(); - PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_list`") - ) { - // Load all wars - ResultSet warsResult = warStatement.executeQuery(); - - if (warsResult == null) - throw new SQLException("Failed to get wars from DB"); - - while (warsResult.next()) { - // War data - @NotNull UUID uuid = UUID.fromString(warsResult.getString("uuid")); - String name = warsResult.getString("name"); - String label = warsResult.getString("label"); - @NotNull UUID side1UUID = UUID.fromString(warsResult.getString("side1")); - @NotNull UUID side2UUID = UUID.fromString(warsResult.getString("side2")); - @NotNull Side side1 = loadSide(con, uuid, side1UUID); - @NotNull Side side2 = loadSide(con, uuid, side2UUID); - - wars.add(new War( - uuid, - name, - label, - side1, - side2, - new HashSet<>(), - new HashSet<>() - )); - } - - for (War war : wars) { - @NotNull Set sieges = loadSieges(con, war); - war.setSieges(sieges); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return wars; - } - - @Contract("_, _, _ -> new") - public static @NotNull Side loadSide(@NotNull Connection con, @NotNull UUID warUUID, @NotNull UUID uuid) { - try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_sides` WHERE `war` = ? AND `uuid` = ?")) { - // Load side - warStatement.setString(1, warUUID.toString()); - warStatement.setString(2, uuid.toString()); - ResultSet sideResult = warStatement.executeQuery(); - - if (sideResult == null) - throw new SQLException("Failed to get side from DB"); - - sideResult.next(); - - // Side data - @NotNull BattleSide side = BattleSide.valueOf(sideResult.getString("side")); - @NotNull BattleTeam team = BattleTeam.valueOf(sideResult.getString("team")); - String name = sideResult.getString("name"); - @Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(sideResult.getString("town"))); - Instant siegeGrace = sideResult.getTimestamp("siegeGrace").toInstant(); - Instant raidGrace = sideResult.getTimestamp("raidGrace").toInstant(); - - @NotNull Set players = loadSidePlayers(con, uuid, false); - @NotNull Set playersSurrendered = loadSidePlayers(con, uuid, true); - @NotNull Set nations = loadSideNations(con, uuid, false); - @NotNull Set nationsSurrendered = loadSideNations(con, uuid, true); - @NotNull Set towns = loadSideTowns(con, uuid, false); - @NotNull Set townsSurrendered = loadSideTowns(con, uuid, true); - - return new Side( - warUUID, - uuid, - town, - side, - team, - name, - towns, - nations, - players, - townsSurrendered, - nationsSurrendered, - playersSurrendered, - siegeGrace, - raidGrace - ); - } catch (SQLException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - public static @NotNull Set loadSidePlayers(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) { - @NotNull Set players = new HashSet<>(); - - try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))) { - warStatement.setString(1, sideUUID.toString()); - ResultSet warsResult = warStatement.executeQuery(); - - if (warsResult == null) - throw new SQLException("Failed to get players from DB"); - - while (warsResult.next()) { - players.add(UUID.fromString(warsResult.getString("player"))); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return players; - } - - public static @NotNull Set loadSideNations(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) { - @NotNull Set nations = new HashSet<>(); - - try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))) { - warStatement.setString(1, sideUUID.toString()); - ResultSet warsResult = warStatement.executeQuery(); - - if (warsResult == null) - throw new SQLException("Failed to get nations from DB"); - - while (warsResult.next()) { - final @NotNull UUID uuid = UUID.fromString(warsResult.getString("nation")); - - @Nullable Nation nation = TownyAPI.getInstance().getNation(uuid); - if (nation == null) continue; - - nations.add(nation); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return nations; - } - - public static @NotNull Set loadSideTowns(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) { - @NotNull Set towns = new HashSet<>(); - - try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))) { - warStatement.setString(1, sideUUID.toString()); - ResultSet warsResult = warStatement.executeQuery(); - - if (warsResult == null) - throw new SQLException("Failed to get towns from DB"); - - while (warsResult.next()) { - final @NotNull UUID uuid = UUID.fromString(warsResult.getString("town")); - - @Nullable Town town = TownyAPI.getInstance().getTown(uuid); - if (town == null) continue; - - towns.add(town); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return towns; - } - - public static @NotNull Set loadSieges(@NotNull Connection con, @NotNull War war) { - @NotNull Set sieges = new HashSet<>(); - - try (PreparedStatement siegesStatement = con.prepareStatement("SELECT * FROM `wars_sieges` WHERE `war` = ?")) { - siegesStatement.setString(1, war.getUUID().toString()); - ResultSet siegesResults = siegesStatement.executeQuery(); - - if (siegesResults == null) - throw new SQLException("Failed to get sieges from DB"); - - while (siegesResults.next()) { - final UUID uuid = UUID.fromString(siegesResults.getString("uuid")); - final @Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(siegesResults.getString("town"))); - final OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(UUID.fromString(siegesResults.getString("siegeLeader"))); - final Instant endTime = siegesResults.getTimestamp("endTime").toInstant(); - final Instant lastTouched = siegesResults.getTimestamp("lastTouched").toInstant(); - final int siegeProgress = siegesResults.getInt("siegeProgress"); - final Set attackersIncludingOffline = loadSiegePlayers(con, uuid, true); - final Set defendersIncludingOffline = loadSiegePlayers(con, uuid, false); - - if (town == null) continue; - - sieges.add(new Siege( - war, - uuid, - town, - siegeLeader, - endTime, - lastTouched, - siegeProgress, - attackersIncludingOffline, - defendersIncludingOffline - )); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return sieges; - } - - public static @NotNull Set loadSiegePlayers(@NotNull Connection con, @NotNull UUID siegeUUID, boolean getAttackers) { - @NotNull Set players = new HashSet<>(); - - try (PreparedStatement siegeStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `siege` = ?".formatted(getAttackers ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"))) { - siegeStatement.setString(1, siegeUUID.toString()); - ResultSet playersResult = siegeStatement.executeQuery(); - - if (playersResult == null) - throw new SQLException("Failed to get players from DB"); - - while (playersResult.next()) { - players.add(UUID.fromString(playersResult.getString("player"))); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return players; - } - - public static void deleteWar(@NotNull War war) { - try ( - @NotNull Connection con = DB.get(); - PreparedStatement warStatement = con.prepareStatement("DELETE FROM `wars_list` WHERE `uuid` = ?") - ) { - // Delete war data - warStatement.setString(1, war.getUUID().toString()); - warStatement.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public static void deleteSiege(@NotNull Siege siege) { - try ( - @NotNull Connection con = DB.get(); - PreparedStatement siegesStatement = con.prepareStatement("DELETE FROM `wars_sieges` WHERE `uuid` = ?") - ) { - // Delete siege data - siegesStatement.setString(1, siege.getUUID().toString()); - siegesStatement.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void saveSiege(@NotNull Connection con, @NotNull Siege siege) { - try ( - PreparedStatement siegeStatement = con.prepareStatement("INSERT INTO `wars_sieges` (`war`, `uuid`, `town`, `siegeLeader`, `endTime`, `lastTouched`, `siegeProgress`) VALUES (?, ?, ?, ?, ?, ?, ?) " - + "ON DUPLICATE KEY UPDATE `war` = ?, `town` = ?, `siegeLeader` = ?, `endTime` = ?, `lastTouched` = ?, `siegeProgress` = ?") - ) { - // Insert - siegeStatement.setString(1, siege.getWar().getUUID().toString()); - siegeStatement.setString(2, siege.getUUID().toString()); - siegeStatement.setString(3, siege.getTown().getUUID().toString()); - siegeStatement.setString(4, siege.getSiegeLeader().getUniqueId().toString()); - siegeStatement.setTimestamp(5, Timestamp.from(siege.getEndTime())); - siegeStatement.setTimestamp(6, Timestamp.from(siege.getLastTouched())); - siegeStatement.setInt(7, siege.getSiegeProgress()); - - // Update - siegeStatement.setString(8, siege.getWar().getUUID().toString()); - siegeStatement.setString(9, siege.getTown().getUUID().toString()); - siegeStatement.setString(10, siege.getSiegeLeader().getUniqueId().toString()); - siegeStatement.setTimestamp(11, Timestamp.from(siege.getEndTime())); - siegeStatement.setTimestamp(12, Timestamp.from(siege.getLastTouched())); - siegeStatement.setInt(13, siege.getSiegeProgress()); - - siegeStatement.executeUpdate(); - - saveSiegePlayers(con, siege, false); - saveSiegePlayers(con, siege, true); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private static void saveSiegePlayers(@NotNull Connection con, @NotNull Siege siege, boolean isAttacker) throws SQLException { - try ( - PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `siege` = ?".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders")); - PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`siege`, `player`) VALUES (?, ?)".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders")) - ) { - try { - // Transaction start - con.setAutoCommit(false); - - // Delete old - deleteStatement.setString(1, siege.getUUID().toString()); - deleteStatement.executeUpdate(); - - // Insert new - for (@NotNull UUID uuid : (isAttacker ? siege.getAttackerPlayersIncludingOffline() : siege.getDefenderPlayersIncludingOffline())) { - insertStatement.setString(1, siege.getUUID().toString()); - insertStatement.setString(2, uuid.toString()); - insertStatement.executeUpdate(); - } - - // Transaction end - con.commit(); - } catch (Exception e) { - con.rollback(); - } finally { - con.setAutoCommit(true); - } - } - } -} diff --git a/src/main/java/com/github/alathra/AlathranWars/Main.java b/src/main/java/com/github/alathra/alathranwars/AlathranWars.java similarity index 53% rename from src/main/java/com/github/alathra/AlathranWars/Main.java rename to src/main/java/com/github/alathra/alathranwars/AlathranWars.java index 3ecf2d1..30ea039 100644 --- a/src/main/java/com/github/alathra/AlathranWars/Main.java +++ b/src/main/java/com/github/alathra/alathranwars/AlathranWars.java @@ -1,13 +1,13 @@ -package com.github.alathra.AlathranWars; +package com.github.alathra.alathranwars; -import com.github.alathra.AlathranWars.commands.CommandManager; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.data.ConfigManager; -import com.github.alathra.AlathranWars.data.DataManager; -import com.github.alathra.AlathranWars.hooks.HookManager; -import com.github.alathra.AlathranWars.items.WarItemRegistry; -import com.github.alathra.AlathranWars.listeners.ListenerHandler; -import com.github.alathra.AlathranWars.utility.SQLQueries; +import com.github.alathra.alathranwars.commands.CommandManager; +import com.github.alathra.alathranwars.config.ConfigHandler; +import com.github.alathra.alathranwars.conflict.war.WarController; +import com.github.alathra.alathranwars.db.DatabaseHandler; +import com.github.alathra.alathranwars.db.DatabaseQueries; +import com.github.alathra.alathranwars.hooks.HookManager; +import com.github.alathra.alathranwars.items.WarItemRegistry; +import com.github.alathra.alathranwars.listeners.ListenerHandler; import net.milkbowl.vault.economy.Economy; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; @@ -15,26 +15,18 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import space.arim.morepaperlib.MorePaperLib; -public class Main extends JavaPlugin { +public class AlathranWars extends JavaPlugin { public static @Nullable Economy econ = null; - private static Main instance = null; private static MorePaperLib paperLib; - private ConfigManager configManager; - private DataManager dataManager; - private CommandManager commandManager; + private static AlathranWars instance; + private ConfigHandler configHandler; + private DatabaseHandler databaseHandler; private ListenerHandler listenerHandler; + + private CommandManager commandManager; private HookManager hookManager; - @NotNull - public static Main getInstance() { - return instance; - } - - public static MorePaperLib getPaperLib() { - return paperLib; - } - @SuppressWarnings("rawtypes") private boolean setupEconomy() { if (this.getServer().getPluginManager().getPlugin("Vault") == null) { @@ -49,54 +41,62 @@ public class Main extends JavaPlugin { return econ != null; } - @Override public void onLoad() { instance = this; - paperLib = new MorePaperLib(getInstance()); - WarManager.getInstance(); - configManager = new ConfigManager(getInstance()); - dataManager = new DataManager(getInstance()); - commandManager = new CommandManager(getInstance()); - listenerHandler = new ListenerHandler(getInstance()); + paperLib = new MorePaperLib(instance); + WarController.getInstance(); + configHandler = new ConfigHandler(instance); + databaseHandler = new DatabaseHandler(instance); + commandManager = new CommandManager(instance); + listenerHandler = new ListenerHandler(instance); hookManager = new HookManager(); - configManager.onLoad(); - dataManager.onLoad(); + configHandler.onLoad(); + databaseHandler.onLoad(); commandManager.onLoad(); listenerHandler.onLoad(); hookManager.onLoad(); } - @Override public void onEnable() { this.saveDefaultConfig(); new WarItemRegistry(); setupEconomy(); - configManager.onEnable(); - dataManager.onEnable(); + configHandler.onEnable(); + databaseHandler.onEnable(); commandManager.onEnable(); listenerHandler.onEnable(); hookManager.onEnable(); - WarManager.getInstance().loadAll(); + WarController.getInstance().loadAll(); } - @Override public void onDisable() { getPaperLib().scheduling().cancelGlobalTasks(); - SQLQueries.saveAll(); - configManager.onDisable(); + DatabaseQueries.saveAll(); commandManager.onDisable(); listenerHandler.onDisable(); hookManager.onDisable(); - dataManager.onDisable(); + databaseHandler.onDisable(); + configHandler.onDisable(); } - public ConfigManager getConfigManager() { - return configManager; + @NotNull + public static AlathranWars getInstance() { + return instance; } - public DataManager getDataManager() { - return dataManager; + public static MorePaperLib getPaperLib() { + return paperLib; + } + + @NotNull + public DatabaseHandler getDataHandler() { + return databaseHandler; + } + + @NotNull + public ConfigHandler getConfigHandler() { + return configHandler; } } diff --git a/src/main/java/com/github/alathra/alathranwars/Reloadable.java b/src/main/java/com/github/alathra/alathranwars/Reloadable.java new file mode 100644 index 0000000..400da5c --- /dev/null +++ b/src/main/java/com/github/alathra/alathranwars/Reloadable.java @@ -0,0 +1,21 @@ +package com.github.alathra.alathranwars; + +/** + * Implemented in classes that should support being reloaded IE executing the methods during runtime after startup. + */ +public interface Reloadable { + /** + * On plugin load. + */ + void onLoad(); + + /** + * On plugin enable. + */ + void onEnable(); + + /** + * On plugin disable. + */ + void onDisable(); +} diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java similarity index 83% rename from src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java rename to src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java index 8a0efe7..99b08e9 100644 --- a/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java +++ b/src/main/java/com/github/alathra/alathranwars/commands/AdminCommands.java @@ -1,8 +1,9 @@ -package com.github.alathra.AlathranWars.commands; +package com.github.alathra.alathranwars.commands; -import com.github.alathra.AlathranWars.Main; -import com.github.alathra.AlathranWars.items.WarItemRegistry; -import com.github.alathra.AlathranWars.utility.UtilsChat; +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.hooks.NameColorHandler; +import com.github.alathra.alathranwars.items.WarItemRegistry; +import com.github.alathra.alathranwars.utility.UtilsChat; import com.github.milkdrinkers.colorparser.ColorParser; import dev.jorel.commandapi.CommandAPIBukkit; import dev.jorel.commandapi.CommandAPICommand; @@ -12,6 +13,7 @@ import dev.jorel.commandapi.arguments.PlayerArgument; import dev.jorel.commandapi.arguments.StringArgument; import dev.jorel.commandapi.executors.CommandArguments; import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; @@ -24,7 +26,8 @@ public class AdminCommands { .withSubcommands( commandItem(), commandWar(), - commandSiege() + commandSiege(), + commandNames() ) .executes((sender, args) -> { if (args.count() == 0) @@ -51,7 +54,7 @@ public class AdminCommands { throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid item argument.").build()); @Nullable ItemStack stack; - if (argItem.contains(Main.getInstance().getName().toLowerCase())) { + if (argItem.contains(AlathranWars.getInstance().getName().toLowerCase())) { stack = WarItemRegistry.getInstance().getOrNullNamespace(argItem); } else { stack = WarItemRegistry.getInstance().getOrNull(argItem); @@ -96,9 +99,11 @@ public class AdminCommands { WarCommands.commandCreate(true), WarCommands.commandDelete(true), WarCommands.commandJoin(true), + WarCommands.commandJoinNear(), WarCommands.commandSurrender(true), WarCommands.commandList(), - WarCommands.commandInfo() + WarCommands.commandInfo(), + WarCommands.commandKick() ); } @@ -112,4 +117,11 @@ public class AdminCommands { SiegeCommands.commandList() ); } + + private CommandAPICommand commandNames() { + return new CommandAPICommand("updatenames") + .executesPlayer((player, commandArguments) -> { + Bukkit.getOnlinePlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p)); + }); + } } diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java b/src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java similarity index 74% rename from src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java rename to src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java index 7c814b0..e17ebfd 100644 --- a/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java +++ b/src/main/java/com/github/alathra/alathranwars/commands/CommandManager.java @@ -1,13 +1,13 @@ -package com.github.alathra.AlathranWars.commands; +package com.github.alathra.alathranwars.commands; -import com.github.alathra.AlathranWars.Main; +import com.github.alathra.alathranwars.AlathranWars; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.CommandAPIBukkitConfig; public class CommandManager { - private final Main instance; + private final AlathranWars instance; - public CommandManager(Main instance) { + public CommandManager(AlathranWars instance) { this.instance = instance; } diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java b/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java similarity index 83% rename from src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java rename to src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java index 1468a65..0de605e 100644 --- a/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java +++ b/src/main/java/com/github/alathra/alathranwars/commands/CommandUtil.java @@ -1,15 +1,15 @@ -package com.github.alathra.AlathranWars.commands; +package com.github.alathra.alathranwars.commands; -import com.github.alathra.AlathranWars.Main; -import com.github.alathra.AlathranWars.conflict.Side; -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.conflict.battle.siege.Siege; -import com.github.alathra.AlathranWars.enums.CommandArgsSiege; -import com.github.alathra.AlathranWars.enums.CommandArgsWar; -import com.github.alathra.AlathranWars.hooks.TownyHook; -import com.github.alathra.AlathranWars.items.WarItemRegistry; -import com.github.alathra.AlathranWars.utility.UtilsChat; +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.conflict.battle.siege.Siege; +import com.github.alathra.alathranwars.conflict.war.War; +import com.github.alathra.alathranwars.conflict.war.WarController; +import com.github.alathra.alathranwars.conflict.war.side.Side; +import com.github.alathra.alathranwars.enums.CommandArgsSiege; +import com.github.alathra.alathranwars.enums.CommandArgsWar; +import com.github.alathra.alathranwars.hooks.TownyHook; +import com.github.alathra.alathranwars.items.WarItemRegistry; +import com.github.alathra.alathranwars.utility.UtilsChat; import com.github.milkdrinkers.colorparser.ColorParser; import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.object.Nation; @@ -22,12 +22,15 @@ import dev.jorel.commandapi.arguments.ArgumentSuggestions; import dev.jorel.commandapi.arguments.CustomArgument; import dev.jorel.commandapi.arguments.StringArgument; import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; import org.bukkit.Statistic; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -225,7 +228,6 @@ public class CommandUtil { })); } - /** * Accepts all towns and nations as argument. Returns a string. * @@ -288,6 +290,64 @@ public class CommandUtil { })); } + static public Argument playerOrTownOrNationInWar(String nodeName, String warNodeName) { + return new CustomArgument<>(new StringArgument(nodeName), info -> { + final String argPlayerOrTownOrNationName = info.input(); + + if (!(info.previousArgs().get(warNodeName) instanceof War war)) { + throw CustomArgument.CustomArgumentException.fromAdventureComponent( + ColorParser.of(UtilsChat.getPrefix() + "The war does not exist!") + .build() + ); + } + + final List townNames = war.getTowns().stream().map(Town::getName).sorted().toList(); + final List nationNames = war.getNations().stream().map(Nation::getName).sorted().toList(); + final List playerNames = war.getPlayersIncludingOffline().stream() + .filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days + .filter(p -> p.getName() != null) + .map(OfflinePlayer::getName) + .sorted() + .toList(); + + + if (townNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName) != null) + return TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName).getUUID(); + + if (nationNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName) != null) + return TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName).getUUID(); + + if (playerNames.contains(argPlayerOrTownOrNationName)) + return Bukkit.getOfflinePlayer(argPlayerOrTownOrNationName).getUniqueId(); + + throw CustomArgument.CustomArgumentException.fromAdventureComponent( + ColorParser.of(UtilsChat.getPrefix() + "The player, town or nation is not in the war!") + .parseMinimessagePlaceholder("name", argPlayerOrTownOrNationName) + .build() + ); + }).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> { + if (!(info.previousArgs().get(warNodeName) instanceof War war)) { + return Collections.emptyList(); + } + + final List nationNames = war.getNations().stream().map(Nation::getName).sorted().toList(); + final List townNames = war.getTowns().stream().map(Town::getName).sorted().toList(); + final List playerNames = war.getPlayersIncludingOffline().stream() + .filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days + .filter(p -> p.getName() != null) + .map(OfflinePlayer::getName) + .sorted() + .toList(); + + final List recommendations = new ArrayList<>(); + recommendations.addAll(nationNames); + recommendations.addAll(townNames); + recommendations.addAll(playerNames); + + return recommendations; + })); + } + public static Argument customSiegeAttackableTownArgument(String nodeName, String warNodeName, final boolean checkIfIn, final boolean checkIfSieged) { return new CustomArgument<>(new StringArgument(nodeName), info -> { if (!(info.previousArgs().get(warNodeName) instanceof War war)) @@ -302,7 +362,7 @@ public class CommandUtil { throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town is not in that war!").parseLegacy().build()); if (checkIfSieged) { - for (@NotNull Siege siege : WarManager.getInstance().getSieges()) { + for (@NotNull Siege siege : WarController.getInstance().getSieges()) { if (siege.getTown().getUUID() == town.getUUID()) throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The town is already under siege!").parseLegacy().build()); } @@ -342,13 +402,13 @@ public class CommandUtil { final String argSiegeName = info.input(); @Nullable UUID siegeUUID = null; - for (Siege siege : WarManager.getInstance().getSieges()) { + for (Siege siege : WarController.getInstance().getSieges()) { if (siege.getName().equals(argSiegeName)) { siegeUUID = siege.getUUID(); } } - final @Nullable Siege siege = WarManager.getInstance().getSiege(siegeUUID); + final @Nullable Siege siege = WarController.getInstance().getSiege(siegeUUID); if (siege == null) throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The siege does not exist!").parseMinimessagePlaceholder("siege", argSiegeName).build()); @@ -394,7 +454,7 @@ public class CommandUtil { } private static List siegeAll(SuggestionInfo info, final boolean isAdmin) { - return WarManager.getInstance().getSieges().stream().map(Siege::getName).toList(); + return WarController.getInstance().getSieges().stream().map(Siege::getName).toList(); } private static List siegeOutside(SuggestionInfo info, final boolean isAdmin, final String playerNodeName) { @@ -402,11 +462,11 @@ public class CommandUtil { if (isAdmin) { if (info.previousArgs().get(playerNodeName) instanceof Player player) { - siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList(); + siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList(); } } else { if (info.sender() instanceof Player player) { - siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList(); + siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList(); } } @@ -418,11 +478,11 @@ public class CommandUtil { if (isAdmin) { if (info.previousArgs().get(playerNodeName) instanceof Player player) { - siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList(); + siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList(); } } else { if (info.sender() instanceof Player player) { - siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList(); + siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList(); } } @@ -433,7 +493,7 @@ public class CommandUtil { return new CustomArgument<>(new StringArgument(nodeName), info -> { final String argWarName = info.input(); - final @Nullable War war = WarManager.getInstance().getWar(argWarName); + final @Nullable War war = WarController.getInstance().getWar(argWarName); if (war == null) throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "The war does not exist!").parseMinimessagePlaceholder("war", argWarName).build()); @@ -479,7 +539,7 @@ public class CommandUtil { } private static List warsAll(SuggestionInfo info, final boolean isAdmin) { - return WarManager.getInstance().getWarNames(); + return WarController.getInstance().getWarNames(); } private static List warsOutside(SuggestionInfo info, final boolean isAdmin, final String playerNodeName) { @@ -487,11 +547,11 @@ public class CommandUtil { if (isAdmin) { if (info.previousArgs().get(playerNodeName) instanceof Player player) { - warNames = WarManager.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList(); + warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList(); } } else { if (info.sender() instanceof Player player) { - warNames = WarManager.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList(); + warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList(); } } @@ -503,11 +563,11 @@ public class CommandUtil { if (isAdmin) { if (info.previousArgs().get(playerNodeName) instanceof Player player) { - warNames = WarManager.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList(); + warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList(); } } else { if (info.sender() instanceof Player player) { - warNames = WarManager.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList(); + warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList(); } } @@ -641,14 +701,15 @@ public class CommandUtil { long regTime = res.getRegistered(); int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE); int out = 0; - if (Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) { + if (AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge") > 0) { //compare the join date, if they joined less that min age ago it is true - if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge")) + if ((System.currentTimeMillis() - regTime) < 86400000L * AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge")) out = 1; } - if (Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) { + if (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") > 0) { //check playtime, if its less than min its true - if (playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2; + if (playTicks < (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) + out = 2; } return out; diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java similarity index 87% rename from src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java rename to src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java index f73ec98..84986cb 100644 --- a/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java +++ b/src/main/java/com/github/alathra/alathranwars/commands/SiegeCommands.java @@ -1,11 +1,12 @@ -package com.github.alathra.AlathranWars.commands; +package com.github.alathra.alathranwars.commands; -import com.github.alathra.AlathranWars.Main; -import com.github.alathra.AlathranWars.conflict.Side; -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.conflict.battle.siege.Siege; -import com.github.alathra.AlathranWars.utility.UtilsChat; +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.conflict.battle.siege.Siege; +import com.github.alathra.alathranwars.conflict.war.War; +import com.github.alathra.alathranwars.conflict.war.WarController; +import com.github.alathra.alathranwars.conflict.war.side.Side; +import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason; +import com.github.alathra.alathranwars.utility.UtilsChat; import com.github.milkdrinkers.colorparser.ColorParser; import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.object.Resident; @@ -26,10 +27,10 @@ import java.time.Duration; import java.time.Instant; import java.util.Set; -import static com.github.alathra.AlathranWars.enums.CommandArgsSiege.ALL_SIEGES; -import static com.github.alathra.AlathranWars.enums.CommandArgsSiege.IN_SIEGE; -import static com.github.alathra.AlathranWars.enums.CommandArgsWar.ALL_WARS; -import static com.github.alathra.AlathranWars.enums.CommandArgsWar.IN_WAR; +import static com.github.alathra.alathranwars.enums.CommandArgsSiege.ALL_SIEGES; +import static com.github.alathra.alathranwars.enums.CommandArgsSiege.IN_SIEGE; +import static com.github.alathra.alathranwars.enums.CommandArgsWar.ALL_WARS; +import static com.github.alathra.alathranwars.enums.CommandArgsWar.IN_WAR; public class SiegeCommands { public SiegeCommands() { @@ -151,7 +152,7 @@ public class SiegeCommands { if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to be further than blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build()); - if ((Main.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin) + if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to have $ to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build()); side.setSiegeGrace(); @@ -176,7 +177,7 @@ public class SiegeCommands { if (!(args.get("siege") instanceof final @NotNull Siege siege)) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Invalid siege.").build()); - siege.noWinner(); + siege.equalWin(BattleVictoryReason.ADMIN_COMMAND); } private static void siegeAbandon(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException { @@ -187,13 +188,7 @@ public class SiegeCommands { if (siegeLeader != p && !asAdmin) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You are not the leader of this siege.").build()); - Bukkit.broadcast( - ColorParser.of("The siege at has been abandoned.") - .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) - .parseMinimessagePlaceholder("town", siege.getTown().getName()) - .build() - ); - siege.defendersWin(); + siege.defendersWin(BattleVictoryReason.OPPONENT_RETREAT); } private static void siegeSurrender(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException { @@ -212,17 +207,11 @@ public class SiegeCommands { if (!asAdmin && !canKingSurrender && !canMayorSurrender) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You cannot surrender this town.").build()); - Bukkit.broadcast( - ColorParser.of("The town of has surrendered.") - .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) - .parseMinimessagePlaceholder("town", siege.getTown().getName()) - .build() - ); - siege.attackersWin(); + siege.attackersWin(BattleVictoryReason.OPPONENT_RETREAT); } private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException { - Set sieges = WarManager.getInstance().getSieges(); + Set sieges = WarController.getInstance().getSieges(); if (sieges.isEmpty()) { sender.sendMessage(ColorParser.of("There are no sieges at the moment.").build()); diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java b/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java similarity index 59% rename from src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java rename to src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java index d7155b4..32c59eb 100644 --- a/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java +++ b/src/main/java/com/github/alathra/alathranwars/commands/WarCommands.java @@ -1,10 +1,12 @@ -package com.github.alathra.AlathranWars.commands; +package com.github.alathra.alathranwars.commands; -import com.github.alathra.AlathranWars.conflict.Side; -import com.github.alathra.AlathranWars.conflict.War; -import com.github.alathra.AlathranWars.conflict.WarManager; -import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener; -import com.github.alathra.AlathranWars.utility.UtilsChat; +import com.github.alathra.alathranwars.conflict.war.War; +import com.github.alathra.alathranwars.conflict.war.WarBuilder; +import com.github.alathra.alathranwars.conflict.war.WarController; +import com.github.alathra.alathranwars.conflict.war.side.Side; +import com.github.alathra.alathranwars.conflict.war.side.SideCreationException; +import com.github.alathra.alathranwars.hooks.NameColorHandler; +import com.github.alathra.alathranwars.utility.UtilsChat; import com.github.milkdrinkers.colorparser.ColorParser; import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.object.Nation; @@ -13,6 +15,7 @@ import com.palmergames.bukkit.towny.object.Town; import dev.jorel.commandapi.CommandAPIBukkit; import dev.jorel.commandapi.CommandAPICommand; import dev.jorel.commandapi.arguments.ArgumentSuggestions; +import dev.jorel.commandapi.arguments.BooleanArgument; import dev.jorel.commandapi.arguments.GreedyStringArgument; import dev.jorel.commandapi.arguments.PlayerArgument; import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException; @@ -21,6 +24,8 @@ import net.kyori.adventure.key.Key; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.title.Title; import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -32,7 +37,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; -import static com.github.alathra.AlathranWars.enums.CommandArgsWar.*; +import static com.github.alathra.alathranwars.enums.CommandArgsWar.*; public class WarCommands { public WarCommands() { @@ -58,6 +63,7 @@ public class WarCommands { .withArguments( CommandUtil.customTownAndNationArgument("side1", "war", false), CommandUtil.customTownAndNationArgument("side2", "war", false), + new BooleanArgument("event"), new GreedyStringArgument("warlabel") .replaceSuggestions( ArgumentSuggestions.stringCollection(info -> List.of( @@ -81,6 +87,7 @@ public class WarCommands { public static CommandAPICommand commandJoin(boolean asAdmin) { return new CommandAPICommand("join") + .withPermission("AlathranWars.war.join") .withArguments( CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : OUT_WAR, ""), CommandUtil.warSideCreateArgument("side", "war", asAdmin, !asAdmin, ""), @@ -89,7 +96,17 @@ public class WarCommands { // new PlayerArgument("nation").setOptional(true).withPermission("AlathranWars.admin.join"), // new PlayerArgument("town").setOptional(true).withPermission("AlathranWars.admin.join") ) - .executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, false)); + .executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, asAdmin)); + } + + public static CommandAPICommand commandJoinNear() { + return new CommandAPICommand("joinnear") + .withPermission("AlathranWars.admin") + .withArguments( + CommandUtil.warWarArgument("war", true, ALL_WARS, ""), + CommandUtil.warSideCreateArgument("side", "war", true, false, "") + ) + .executesPlayer((Player p, CommandArguments args) -> warJoinNear(p, args, true)); } public static CommandAPICommand commandSurrender(boolean asAdmin) { @@ -116,6 +133,16 @@ public class WarCommands { .executesPlayer(WarCommands::warInfo); } + public static CommandAPICommand commandKick() { + return new CommandAPICommand("kick") + .withArguments( + CommandUtil.warWarArgument("war", true, ALL_WARS, "player"), + CommandUtil.playerOrTownOrNationInWar("target", "war") + .withPermission("AlathranWars.admin") + ) + .executesPlayer(WarCommands::warKick); + } + protected static void warCreate(CommandSender p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException { if (!(args.get("warlabel") instanceof final String argLabel)) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You need to specify a war label.").build()); @@ -123,6 +150,8 @@ public class WarCommands { if (Objects.equals(args.get("side1"), args.get("side2"))) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Cannot declare war on oneself.").build()); + final boolean event = (boolean) args.getOrDefault("event", false); + final UUID uuid1 = (UUID) args.get("side1"); final UUID uuid2 = (UUID) args.get("side2"); @@ -137,33 +166,42 @@ public class WarCommands { // Implement permission checking here if this is ever going to be exposed to players // Create war depending on what args have been passed, attempt to create nation wars first + WarBuilder builder = new WarBuilder() + .setUuid(UUID.randomUUID()) + .setLabel(argLabel) + .setEvent(event); if (nation1 != null) { if (nation2 != null) { // Nation vs Nation - // Allow civil wars if (nation2.getUUID() != nation1.getUUID()) { - new War(argLabel, nation1, nation2); + builder + .setAggressor(nation1) + .setVictim(nation2); } else { - new War(argLabel, town1, town2); + builder + .setAggressor(town1) + .setVictim(town2); } - } else if (town2 != null) { // Nation vs Town - - new War(argLabel, nation1, town2); - + builder + .setAggressor(nation1) + .setVictim(town2); } } else if (town1 != null) { - if (town2 != null) { // Town vs Town - - new War(argLabel, town1, town2); - + builder + .setAggressor(town1) + .setVictim(town2); } else if (nation2 != null) { // Nation vs Town - - new War(argLabel, town1, nation2); - + builder + .setAggressor(town1) + .setVictim(nation2); } - + } + try { + builder.create(); // TODO Add war to list + } catch (SideCreationException e) { + throw new RuntimeException(e); } } @@ -194,92 +232,94 @@ public class WarCommands { throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Resident invalid.").build()); // Get nations and towns - @Nullable Nation nation = res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString); - @Nullable Town town = res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString); + @Nullable Nation nation = asAdmin ? TownyAPI.getInstance().getNation(targetString) : res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString); + @Nullable Town town = asAdmin ? TownyAPI.getInstance().getTown(targetString) : res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString); - final boolean isNation = nation != null; - final boolean isTown = town != null; - final boolean isPlayer = targetPlayer != null; + final boolean isArgNation = nation != null; + final boolean isArgTown = town != null; + final boolean isArgPlayer = targetPlayer != null; // If no valid targets - if ((!isNation && !isTown && !isPlayer)) + if ((!isArgNation && !isArgTown && !isArgPlayer)) throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Invalid target.").build()); // Check if player can validly join or not final boolean canKingJoin = (res.hasNation() && res.getNationOrNull().equals(nation) && res.isKing() && nation.isKing(res)); final boolean canMayorJoin = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor() && town.isMayor(res)); - // Join nation into war - if (isNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) { - side.addNation(nation); - nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(PlayerJoinListener::checkPlayer); - Bukkit.broadcast( - ColorParser.of( - "The nation of joined the war of on the side of ." - ) - .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) - .parseMinimessagePlaceholder("nation", nation.getName()) - .parseMinimessagePlaceholder("war", war.getLabel()) - .parseMinimessagePlaceholder("side", side.getName()) - .build() - ); - final Title warTitle = Title.title( - ColorParser.of("War") - .build(), - ColorParser.of("You entered the war of !") - .parseMinimessagePlaceholder("war", war.getLabel()) - .build(), - Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)) - ); - final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F); + if (!war.isEventWar()) { + // Join nation into war + if (isArgNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) { + side.addNation(nation); + nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player)); + Bukkit.broadcast( + ColorParser.of( + "The nation of joined the war of on the side of ." + ) + .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) + .parseMinimessagePlaceholder("nation", nation.getName()) + .parseMinimessagePlaceholder("war", war.getLabel()) + .parseMinimessagePlaceholder("side", side.getName()) + .build() + ); + final Title warTitle = Title.title( + ColorParser.of("War") + .build(), + ColorParser.of("You entered the war of !") + .parseMinimessagePlaceholder("war", war.getLabel()) + .build(), + Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)) + ); + final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F); - nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> { - player.showTitle(warTitle); - player.playSound(warSound); - }); - return; - } else if (town == null && nation != null && (!canKingJoin || !asAdmin)) { - throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Nation is already in that war.").build()); - } + nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> { + player.showTitle(warTitle); + player.playSound(warSound); + }); + return; + } else if (town == null && nation != null && (!canKingJoin || !asAdmin)) { + throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Nation is already in that war.").build()); + } - // Join town into war - if (isTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) { - side.addTown(town); - town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(PlayerJoinListener::checkPlayer); - Bukkit.broadcast( - ColorParser.of( - "The town of joined the war of on the side of ." - ) - .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) - .parseMinimessagePlaceholder("town", town.getName()) - .parseMinimessagePlaceholder("war", war.getLabel()) - .parseMinimessagePlaceholder("side", side.getName()) - .build() - ); - final Title warTitle = Title.title( - ColorParser.of("War") - .build(), - ColorParser.of("You entered the war of !") - .parseMinimessagePlaceholder("war", war.getLabel()) - .build(), - Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)) - ); - final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F); + // Join town into war + if (isArgTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) { + side.addTown(town); + town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player)); + Bukkit.broadcast( + ColorParser.of( + "The town of joined the war of on the side of ." + ) + .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix()) + .parseMinimessagePlaceholder("town", town.getName()) + .parseMinimessagePlaceholder("war", war.getLabel()) + .parseMinimessagePlaceholder("side", side.getName()) + .build() + ); + final Title warTitle = Title.title( + ColorParser.of("War") + .build(), + ColorParser.of("You entered the war of !") + .parseMinimessagePlaceholder("war", war.getLabel()) + .build(), + Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)) + ); + final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F); - town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> { - player.showTitle(warTitle); - player.playSound(warSound); - }); - return; - } else if (targetPlayer == null && town != null && !canMayorJoin) { - throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Town is already in that war.").build()); + town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> { + player.showTitle(warTitle); + player.playSound(warSound); + }); + return; + } else if (targetPlayer == null && town != null && !canMayorJoin) { + throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Town is already in that war.").build()); + } } // Join player into war - if (isPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) { + if (isArgPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) { targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build()); side.addPlayer(targetPlayer); - PlayerJoinListener.checkPlayer(targetPlayer); + NameColorHandler.getInstance().calculatePlayerColors(targetPlayer); final Title warTitle = Title.title( ColorParser.of("War") .build(), @@ -313,6 +353,40 @@ public class WarCommands { }*/ } + protected static void warJoinNear(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException { + War war = (War) args.get("war"); + if (war == null) return; + + if (!(args.get("side") instanceof final Side side)) + throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "You need to specify a side.").build()); + + final Location location = p.getLocation(); + + for (Player targetPlayer : Bukkit.getOnlinePlayers()) { + if (p.equals(targetPlayer)) continue; + final Location targetLocation = targetPlayer.getLocation(); + if (!location.getWorld().equals(targetLocation.getWorld())) continue; + if (location.distance(targetLocation) > 25D) continue; + if (war.isPlayerInWar(targetPlayer)) continue; + + targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build()); + side.addPlayer(targetPlayer); + NameColorHandler.getInstance().calculatePlayerColors(targetPlayer); + final Title warTitle = Title.title( + ColorParser.of("War") + .build(), + ColorParser.of("You entered the war of !") + .parseMinimessagePlaceholder("war", war.getLabel()) + .build(), + Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)) + ); + final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F); + + targetPlayer.showTitle(warTitle); + targetPlayer.playSound(warSound); + } + } + protected static void warSurrender(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException { War war = (War) args.get("war"); if (war == null) return; @@ -359,8 +433,51 @@ public class WarCommands { } } + protected static void warKick(@NotNull Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException { + War war = (War) args.get("war"); + if (war == null) return; + + UUID uuid = (UUID) args.get("target"); + + boolean isNation = TownyAPI.getInstance().getNation(uuid) != null; + boolean isTown = TownyAPI.getInstance().getTown(uuid) != null; + boolean isPlayer = Bukkit.getOfflinePlayer(uuid) != null; + + Nation nation = TownyAPI.getInstance().getNation(uuid); + Town town = TownyAPI.getInstance().getTown(uuid); + OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); + + Side sideNation = war.getNationSide(nation); + Side sideTown = war.getTownSide(town); + Side sidePlayer = war.getPlayerSide(uuid); + + if (isNation && sideNation != null) { + sideNation.kickNation(nation); + p.sendMessage(ColorParser.of("Target yeeted.").build()); + nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1)); + return; + } + + if (isTown && sideTown != null) { + sideTown.kickTown(town); + p.sendMessage(ColorParser.of("Target yeeted.").build()); + town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1)); + return; + } + + if (isPlayer && sidePlayer != null) { + sidePlayer.kickPlayer(player.getUniqueId()); + p.sendMessage(ColorParser.of("Target yeeted.").build()); + if (player.getPlayer() != null) + NameColorHandler.getInstance().calculatePlayerColors(player.getPlayer()); + return; + } + + throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Failed to yeet from the war because the target is not in it.").build()); + } + private static void warList(@NotNull Player p, CommandArguments args) throws WrapperCommandSyntaxException { - Set wars = WarManager.getInstance().getWars(); + Set wars = WarController.getInstance().getWars(); if (wars.isEmpty()) { p.sendMessage(ColorParser.of("There are no wars at the moment, the world is at peace.").build()); diff --git a/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java b/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java new file mode 100644 index 0000000..6d247ee --- /dev/null +++ b/src/main/java/com/github/alathra/alathranwars/config/ConfigHandler.java @@ -0,0 +1,47 @@ +package com.github.alathra.alathranwars.config; + +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.Reloadable; +import com.github.milkdrinkers.Crate.Config; + +import javax.inject.Singleton; + +/** + * A class that generates/loads & provides access to a configuration file. + */ +@Singleton +public class ConfigHandler implements Reloadable { + private final AlathranWars alathranWars; + private Config cfg; + + /** + * Instantiates a new Config handler. + * + * @param alathranWars the plugin instance + */ + public ConfigHandler(AlathranWars alathranWars) { + this.alathranWars = alathranWars; + } + + @Override + public void onLoad() { + cfg = new Config("config", alathranWars.getDataFolder().getPath(), alathranWars.getResource("config.yml")); // Create a config file from the template in our resources folder + } + + @Override + public void onEnable() { + } + + @Override + public void onDisable() { + } + + /** + * Gets alathranWars config object. + * + * @return the alathranWars config object + */ + public Config getConfig() { + return cfg; + } +} diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java b/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java new file mode 100644 index 0000000..afe1843 --- /dev/null +++ b/src/main/java/com/github/alathra/alathranwars/conflict/Conflict.java @@ -0,0 +1,7 @@ +package com.github.alathra.alathranwars.conflict; + +import com.github.alathra.alathranwars.enums.ConflictType; + +public class Conflict { + private ConflictType conflictType; +} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/Occupation.java b/src/main/java/com/github/alathra/alathranwars/conflict/Occupation.java similarity index 60% rename from src/main/java/com/github/alathra/AlathranWars/conflict/Occupation.java rename to src/main/java/com/github/alathra/alathranwars/conflict/Occupation.java index 79d7553..03173f6 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/Occupation.java +++ b/src/main/java/com/github/alathra/alathranwars/conflict/Occupation.java @@ -1,4 +1,4 @@ -package com.github.alathra.AlathranWars.conflict; +package com.github.alathra.alathranwars.conflict; import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException; import com.palmergames.bukkit.towny.object.Nation; @@ -36,27 +36,27 @@ public class Occupation { if (isOccupied(town)) return; // Remove from current nation - final boolean hasPreviousNation = town.hasNation(); - final boolean hasNewNation = occupier != null; - final Nation previousNation = town.getNationOrNull(); - if (hasPreviousNation && hasNewNation && previousNation != occupier) - town.removeNation(); +// final boolean hasPreviousNation = town.hasNation(); +// final boolean hasNewNation = occupier != null; +// final Nation previousNation = town.getNationOrNull(); +// if (hasPreviousNation && hasNewNation && previousNation != occupier) +// town.removeNation(); - // Put town into occupiers nation - try { - if (hasNewNation) - town.setNation(occupier); - } catch (AlreadyRegisteredException e) { - e.printStackTrace(); - return; - } +// // Put town into occupiers nation +// try { +// if (hasNewNation) +// town.setNation(occupier); +// } catch (AlreadyRegisteredException e) { +// e.printStackTrace(); +// return; +// } town.setConquered(true); town.save(); - if (hasNewNation) - occupier.save(); - - if (hasPreviousNation && previousNation != occupier) - previousNation.save(); +// if (hasNewNation) +// occupier.save(); +// +// if (hasPreviousNation && previousNation != occupier) +// previousNation.save(); } } diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java new file mode 100644 index 0000000..763569f --- /dev/null +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/Battle.java @@ -0,0 +1,54 @@ +package com.github.alathra.alathranwars.conflict.battle; + +import com.github.alathra.alathranwars.enums.battle.BattleType; +import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; + +public interface Battle { + void start(); // Initiates battle + + void stop(); // Ends battle + + void resume(); // Resume battle after server restart or plugin reload + + void attackersWin(BattleVictoryReason reason); // A Attacker victory + + void defendersWin(BattleVictoryReason reason); // A Defender victory + + void equalWin(BattleVictoryReason reason); // A Draw + + + UUID uuid = null; // Battle UUID + + default @NotNull UUID getUUID() { + return uuid; + } + + /** + * Equals boolean. + * + * @param uuid the uuid + * @return the boolean + */ + default boolean equals(UUID uuid) { + return getUUID().equals(uuid); + } + + /** + * Equals boolean. + * + * @param battle the battle + * @return the boolean + */ + default boolean equals(@NotNull Battle battle) { + return getUUID().equals(battle.getUUID()); + } + + BattleType battleType = null; + + default BattleType getBattleType() { + return battleType; + } +} diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/CrystalLaser.java similarity index 95% rename from src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java rename to src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/CrystalLaser.java index 835d4fd..3a4c8b5 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/CrystalLaser.java @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -package com.github.alathra.AlathranWars.conflict.battle.beam; +package com.github.alathra.alathranwars.conflict.battle.beam; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -51,7 +51,7 @@ public class CrystalLaser extends Laser { * @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop */ public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException { - super(start, end, duration, distance); + super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration, distance); fakeCrystalDataWatcher = Packets.createFakeDataWatcher(); Packets.setCrystalWatcher(fakeCrystalDataWatcher, end); diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Laser.java similarity index 83% rename from src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java rename to src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Laser.java index 933d913..a9f0d48 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Laser.java @@ -22,9 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -package com.github.alathra.AlathranWars.conflict.battle.beam; +package com.github.alathra.alathranwars.conflict.battle.beam; -import com.github.alathra.AlathranWars.Main; +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.utility.Logger; +import com.github.milkdrinkers.colorparser.ColorParser; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; @@ -32,7 +34,10 @@ import org.bukkit.scheduler.BukkitRunnable; import space.arim.morepaperlib.scheduling.ScheduledTask; import java.time.Duration; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** @@ -65,8 +70,8 @@ public abstract class Laser { throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization."); if (start.getWorld() != end.getWorld()) throw new IllegalArgumentException("Locations do not belong to the same worlds."); - this.start = start; - this.end = end; + this.start = start.clone(); + this.end = end.clone(); this.duration = duration; distanceSquared = distance < 0 ? -1 : distance * distance; } @@ -103,7 +108,6 @@ public abstract class Laser { */ public void start(Plugin plugin) { if (task != null) throw new IllegalStateException("Task already started"); -// if (runnable != null) throw new IllegalStateException("Task already started"); this.plugin = plugin; Runnable runnable = new BukkitRunnable() { int time = 0; @@ -128,28 +132,11 @@ public abstract class Laser { } time++; } catch (ReflectiveOperationException e) { - e.printStackTrace(); + Logger.get().error(ColorParser.of("Laser packer exception: ").build(), e); } } - - /*@Override - public synchronized void cancel() throws IllegalStateException { - super.cancel(); - runnable = null; - try { - for (Player p : show) { - sendDestroyPackets(p); - } - show.clear(); - executeEnd.forEach(Runnable::run); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); - } - }*/ }; -// main.runTaskTimerAsynchronously(plugin, 0L, durationInTicks ? 1L : 20L); -// Main.getPaperLib().scheduling().asyncScheduler().run(main); - task = Main.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L)); + task = AlathranWars.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L)); } /** @@ -180,7 +167,7 @@ public abstract class Laser { /** * Gets laser status. * - * @return true if the laser is currently running + * @return true if the laser is currently running * (i.e. {@link #start} has been called and the duration is not over) */ public boolean isStarted() { @@ -200,7 +187,7 @@ public abstract class Laser { * @return where exactly is the start position of the laser located */ public Location getStart() { - return start; + return start.clone(); } /** @@ -209,7 +196,7 @@ public abstract class Laser { * @return where exactly is the end position of the laser located */ public Location getEnd() { - return end; + return end.clone(); } protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException; diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/LaserType.java similarity index 97% rename from src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java rename to src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/LaserType.java index 1377f83..fd90e4d 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/LaserType.java +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/LaserType.java @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -package com.github.alathra.AlathranWars.conflict.battle.beam; +package com.github.alathra.alathranwars.conflict.battle.beam; import org.bukkit.Location; import org.bukkit.plugin.Plugin; diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Packets.java similarity index 91% rename from src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java rename to src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Packets.java index b93711a..88094a9 100644 --- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/beam/Packets.java @@ -22,10 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -package com.github.alathra.AlathranWars.conflict.battle.beam; +package com.github.alathra.alathranwars.conflict.battle.beam; +import com.github.alathra.alathranwars.utility.Logger; +import com.github.milkdrinkers.colorparser.ColorParser; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.animal.Squid; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import org.bukkit.Bukkit; @@ -39,13 +40,9 @@ import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; class Packets { public static boolean enabled = false; - private static Logger logger; static int version; private static int versionMinor; private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; @@ -84,16 +81,6 @@ class Packets { static { try { - logger = new Logger("GuardianBeam", null) { - @Override - public void log(LogRecord logRecord) { - logRecord.setMessage("[GuardianBeam] " + logRecord.getMessage()); - super.log(logRecord); - } - }; - logger.setParent(Bukkit.getServer().getLogger()); - logger.setLevel(Level.ALL); - // e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1 String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_"); version = Integer.parseInt(versions[1]); // 1.X @@ -102,16 +89,13 @@ class Packets { versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\."); versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]); } else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y -// logger.info("Found server version 1." + version + "." + versionMinor); ProtocolMappings mappings = ProtocolMappings.getMappings(version); if (mappings == null) { mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1]; -// logger.warning("Loaded not matching version of the mappings for your server version (1." + version + "." + versionMinor + ")"); } -// logger.info("Loaded mappings " + mappings.name()); - Class entityTypesClass = EntityType.class; + Class entityTypesClass = getNMSClass("world.entity", "EntityTypes"); Class entityClass = Entity.class; Class crystalClass = EndCrystal.class; Class squidClass = Squid.class; @@ -161,7 +145,10 @@ class Packets { getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle"); playerConnection = getNMSClass("server.level", "EntityPlayer") .getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c")); - sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(version < 18 ? "sendPacket" : "a", getNMSClass("network.protocol", "Packet")); + playerConnection.setAccessible(true); + sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod( + version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"), + getNMSClass("network.protocol", "Packet")); if (version >= 17) { setUUID = entityClass.getDeclaredMethod("a_", UUID.class); @@ -170,12 +157,11 @@ class Packets { enabled = true; } catch (Exception e) { - e.printStackTrace(); - String errorMsg = "Laser Beam reflection failed to initialize. The util is disabled. Please ensure your version (" + Bukkit.getServer().getClass().getPackage().getName() + ") is supported."; - if (logger == null) - System.err.println(errorMsg); - else - logger.severe(errorMsg); + Logger.get().error( + ColorParser.of("Laser reflection failed to initialize. The utility is disabled. Please ensure your version () is supported.") + .parseMinimessagePlaceholder("version", Bukkit.getServer().getClass().getPackage().getName()) + .build() + , e); } } @@ -324,7 +310,12 @@ class Packets { } }, - V1_20(20, "an", "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g"), + V1_20(20, null, "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g") { + @Override + public String getWatcherFlags() { + return versionMinor < 2 ? "an" : "ao"; + } + }, ; private final int major; diff --git a/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java b/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java new file mode 100644 index 0000000..b484de5 --- /dev/null +++ b/src/main/java/com/github/alathra/alathranwars/conflict/battle/raid/Raid.java @@ -0,0 +1,636 @@ +package com.github.alathra.alathranwars.conflict.battle.raid; + +import com.github.alathra.alathranwars.AlathranWars; +import com.github.alathra.alathranwars.conflict.battle.Battle; +import com.github.alathra.alathranwars.conflict.war.War; +import com.github.alathra.alathranwars.conflict.war.side.Side; +import com.github.alathra.alathranwars.enums.CaptureProgressDirection; +import com.github.alathra.alathranwars.enums.battle.*; +import com.github.alathra.alathranwars.events.battle.BattleResultEvent; +import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent; +import com.github.milkdrinkers.colorparser.ColorParser; +import com.palmergames.bukkit.towny.object.Town; +import com.palmergames.bukkit.towny.object.TownBlock; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.title.Title; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.time.Duration; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Raid implements Battle { + public static final Duration RAID_DURATION = Duration.ofMinutes(60); + public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100% + public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second + public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win + public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting + public static final int BATTLEFIELD_RANGE = 500; + public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2; + public static final int BATTLEFIELD_START_MIN_RANGE = 75; + public static final double SIEGE_VICTORY_MONEY = 2500.0; + + private final @NotNull UUID uuid; + private final Set attackers = new HashSet<>(); // Players inside battlefield + private final Set defenders = new HashSet<>(); // Players inside battlefield + private final Set attackerPlayers = new HashSet<>(); + private final Set defenderPlayers = new HashSet<>(); + private final Set attackerPlayersIncludingOffline = new HashSet<>(); + private final Set defenderPlayersIncludingOffline = new HashSet<>(); + private @NotNull War war; // War which raid belongs to + private Instant endTime; + private int raidProgress = 0; + private Instant lastTouched; + private RaidRunnable raidRunnable; + private Town town; // Town of the raid + private boolean side1AreAttackers; // bool of if side1 being attacker + private OfflinePlayer raidLeader; + private @Nullable TownBlock homeBlock = null; + private @Nullable Location townSpawn = null; + private @Nullable BossBar activeBossBar = null; + private boolean stopped = false; // Used to track if the raid has been already deleted + + public Raid(final @NotNull War war, final Town town, Player raidLeader) { + uuid = UUID.randomUUID(); + + endTime = Instant.now().plus(RAID_DURATION); + lastTouched = Instant.now(); + + this.war = war; + this.town = town; + this.raidLeader = raidLeader; + + side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2); + + if (getSide1AreAttackers()) { + attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline()); + defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline()); + } else { + attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline()); + defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline()); + } + calculateOnlinePlayers(); + } + + // Construct when loading from DB + public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set attackerPlayersIncludingOffline, Set defenderPlayersIncludingOffline) { + this.war = war; + this.uuid = uuid; + this.town = town; + this.raidLeader = raidLeader; + this.endTime = endTime; + this.lastTouched = lastTouched; + this.raidProgress = raidProgress; + this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline); + this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline); + + side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2); + + calculateOnlinePlayers(); + } + + /** + * Starts a raid + */ + public void start() { + raidRunnable = new RaidRunnable(this); + if (!war.isEventWar()) + AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY); + + final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500)); + final Title defTitle = Title.title( + ColorParser.of("") + .parseMinimessagePlaceholder("town", town.getName()) + .build(), + ColorParser.of("Is under raid, defend!") + .build(), + times + ); + final Title attTitle = Title.title( + ColorParser.of("") + .parseMinimessagePlaceholder("town", town.getName()) + .build(), + ColorParser.of("Has been put to raid, attack!") + .build(), + times + ); + + final List soundList = List.of( + Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)), + Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)), + Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)), + Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)) + ); + + getDefenderPlayers().forEach(player -> { + player.showTitle(defTitle); + player.playSound(soundList.get(new Random().nextInt(1, soundList.size()))); + }); + + getAttackerPlayers().forEach(player -> { + player.showTitle(attTitle); + player.playSound(soundList.get(new Random().nextInt(1, soundList.size()))); + }); + } + + /** + * Resumes a raid (after a server restart e.t.c.) + */ + public void resume() { + raidRunnable = new RaidRunnable(this, getRaidProgress()); + } + + /** + * Stops a raid + */ + public void stop() { + if (stopped) return; + stopped = true; + raidRunnable.cancel(); +// DatabaseQueries.deleteRaid(this); // TODO Delete raid + war.removeRaid(this); + } + + public void attackersWin(BattleVictoryReason reason) { + if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return; + + if (!war.isEventWar()) { + AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY); + double amt; + + if (town.getAccount().getHoldingBalance() > 10000.0) { + amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0; + town.getAccount().withdraw(amt, "Raid Defeat"); + } else { + town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat"); + amt = SIEGE_VICTORY_MONEY; + } + + AlathranWars.econ.depositPlayer(raidLeader, amt); + } + + if (side1AreAttackers) { + war.getSide1().addScore(50); + war.getSide2().addScore(5); + } else { + war.getSide1().addScore(5); + war.getSide2().addScore(50); + } + + new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent(); + + stop(); + + if (!war.isEventWar()) { + Side townSide = getWar().getTownSide(town); + Side attackerSide = getAttackerSide(); + + if (attackerSide.equals(townSide)) { + if (townSide.isTownSurrendered(town)) + war.unsurrenderTown(town); + } else { + if (!townSide.isTownSurrendered(town)) + war.surrenderTown(town); + } + } + } + + public void defendersWin(BattleVictoryReason reason) { + if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return; + + if (!war.isEventWar()) + town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory"); + + if (side1AreAttackers) { + war.getSide2().addScore(10); + } else { + war.getSide1().addScore(10); + } + + new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent(); + + stop(); + } + + /** + * No winner declared + */ + public void equalWin(BattleVictoryReason reason) { + if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return; + + new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent(); + + stop(); + } + + @NotNull + public Instant getLastTouched() { + return lastTouched; + } + + public void setLastTouched(Instant lastTouched) { + this.lastTouched = lastTouched; + } + + public int getRaidProgress() { + return raidProgress; + } + + public void setRaidProgress(int raidProgress) { + if (raidProgress < 0) { + raidProgress = 0; + } else if (raidProgress > MAX_RAID_PROGRESS) { + raidProgress = MAX_RAID_PROGRESS; + } + this.raidProgress = raidProgress; + } + + public float getRaidProgressPercentage() { + return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS; + } + + @NotNull + public War getWar() { + return war; + } + + public void setWar(final War war) { + this.war = war; + } + + @NotNull + public Town getTown() { + return town; + } + + public void setTown(final Town town) { + this.town = town; + } + + /** + * Gets attacker name string + */ + @NotNull + public Side getAttackerSide() { + return side1AreAttackers ? war.getSide1() : war.getSide2(); + } + + /** + * Gets defender name string + */ + @NotNull + public Side getDefenderSide() { + return side1AreAttackers ? war.getSide2() : war.getSide1(); + } + + // SECTION Display Bar + + public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) { + if (activeBossBar == null) + createNewDisplayBar(); + + for (@NotNull Player p : Bukkit.getOnlinePlayers()) { + p.hideBossBar(activeBossBar); + } + + for (@Nullable Player p : this.getPlayersOnBattlefield()) { + if (p != null) + p.showBossBar(activeBossBar); + } + + final String color = switch (progressDirection) { + case UP -> { + if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) { + activeBossBar.color(BossBar.Color.RED); + yield ""; + } else { + activeBossBar.color(BossBar.Color.BLUE); + yield ""; + } + } + case CONTESTED -> { + activeBossBar.color(BossBar.Color.YELLOW); + yield ""; + } + case UNCONTESTED -> { + activeBossBar.color(BossBar.Color.WHITE); + yield ""; + } + case DOWN -> { + if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) { + activeBossBar.color(BossBar.Color.BLUE); + yield ""; + } else { + activeBossBar.color(BossBar.Color.RED); + yield ""; + } + } + }; + + if (Instant.now().isBefore(getEndTime())) { + activeBossBar.name( + ColorParser.of("Capture Progress: %s Time: %s