update buildscript

This commit is contained in:
Ryder Belserion 2023-11-11 12:53:47 -05:00
parent f6182d3b3e
commit 172df2dfa3
No known key found for this signature in database
111 changed files with 4871 additions and 152 deletions

26
.gitignore vendored
View File

@ -1,14 +1,22 @@
build
.gradle
.idea
\.idea/
buildSrc/.gradle
buildSrc/build
*.iml
common/.gradle
common/build
*.class
jars
target/classes/
paper/build
paper/.gradle
target/
\.DS_Store
dependency-reduced-pom.xml
run
!paper/run/config
!paper/run/spigot.yml
!paper/run/bukkit.yml
!paper/run/eula.txt
!paper/run/server.properties
!paper/run/plugins

22
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,22 @@
# Contributing to CrazyCrates
Contributions to the project are always welcome, Pull Requests do have some guidelines before being approved.
## You should always create the fork as a personal repository not in an organization.
Any pull request made by a fork in an organization prevents modifications. Everyone has their own way of doing things and rather asking you to change that. A personal fork lets us change the things
that we have a tick about.
If you do not use a personal fork, We have to manually merge your pull request which means it's marked as closed instead of merged.
## Requirements
* `git`
* Java 17 ( Adoptium is recommended )
Pull Requests must be labeled properly according to if it's a bug fix, a new feature or enhancements to the code base.
* `git checkout -b fix/your_fix`
* `git checkout -b feature/your_feature`
* `git checkout -b quality/your_enhancement`
* Commit your changes using `git commit -m 'your commit'`
* Push to your branch using `git push`
* Open a pull request to the `main` branch on our repository to add your change.
You must explain what your pull request is changing and if needed, Supply a video of your change as Pull Requests are a way to get feedback.

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2016 Crazy Crew
Copyright (c) 2016-2023 CrazyCrew
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

121
README.md
View File

@ -1,41 +1,110 @@
## Crazy Auctions
<br />
[![Join us on Discord](https://img.shields.io/discord/182615261403283459.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.badbones69.com)
[![crazyauctions](https://raw.githubusercontent.com/RyderBelserion/Assets/main/crazycrew/webp/CrazyAuctionsBanner.webp)](https://modrinth.com/plugin/crazyauctions)
[![CrazyAuctions's Stargazers](https://img.shields.io/github/stars/Crazy-Crew/Crazy-Auctions?label=stars&logo=github)](https://github.com/Crazy-Crew/Crazy-Auctions/stargazers)
[![CrazyAuctions's Forks](https://img.shields.io/github/forks/Crazy-Crew/Crazy-Auctions?label=forks&logo=github)](https://github.com/Crazy-Crew/Crazy-Auctions/network/members)
[![CrazyAuctions's Watchers](https://img.shields.io/github/watchers/Crazy-Crew/Crazy-Auctions?label=watchers&logo=github)](https://github.com/Crazy-Crew/Crazy-Auctions/watchers)
<div align="center">
CrazyAuctions is a simple auctions plugin where you can sell your items and bid on other items!
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![GPU License][license-shield]][license-url]
[![Contact][discord-shield]][discord-url]
![CodeFactor][codefactor-shield]
## Contact
[![Join us on Discord](https://img.shields.io/discord/182615261403283459.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.badbones69.com)
![Paper](https://cdn.jsdelivr.net/gh/intergrav/devins-badges/assets/compact/supported/paper_vector.svg)
![Purpur](https://cdn.jsdelivr.net/gh/intergrav/devins-badges/assets/compact/supported/purpur_vector.svg)
Join us on [Discord](https://discord.badbones69.com)
<p align="center">
Auction off your items in style!
<br />
<a href="https://github.com/Crazy-Crew/CrazyAuctions/wiki"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://github.com/Crazy-Crew/CrazyAuctions/issues">Report Bug</a>
·
<a href="https://github.com/Crazy-Crew/CrazyAuctions/discussions/categories/feature-requests">Request Feature</a>
·
<a href="https://discord.gg/badbones-s-live-chat-182615261403283459">Get Support</a>
</p>
</div>
## Downloads
[![Build Status](https://jenkins.badbones69.com/view/Stable/job/Crazy-Auctions/badge/icon)](https://jenkins.badbones69.com/view/Stable/job/Crazy-Auctions/)
<!-- TABLE OF CONTENTS -->
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#roadmap">Roadmap</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
</ol>
</details>
Downloads can be obtained from the [spigot page](https://www.spigotmc.org/resources/crazy-auctions.25219/) or the [Jenkins](https://jenkins.badbones69.com/view/Stable/job/Crazy-Auctions/).
## Resource Page
## Plugin Data
[![bStats Graph Data](https://bstats.org/signatures/bukkit/CrazyAuctions.svg)](https://bstats.org/plugin/bukkit/CrazyAuctions/4624)
### Beta Builds
All beta builds will be on Modrinth marked as beta.<br>
## API
In Progress.
<a href="https://modrinth.com/plugin/crazyauctions">![Modrinth](https://raw.githubusercontent.com/intergrav/devins-badges/v3/assets/cozy/available/modrinth_64h.png)</a>
### Dependency Information
## Getting Started
#### Maven
In Progress.
How to get started with contributing / maintaining your own version of CrazyAuctions!
#### Gradle
In Progress.
### Prerequisites
## Working with CrazyAuctions.
A list of things necessary to make sure you can build CrazyAuctions properly.
* Intellij IDEA
* > https://www.jetbrains.com/idea/download/
* Gradle
#### Contributing
Fork the project & open a pull request.
### Installation
#### Compiling
Clone the project & run the install task.
1. Clone the repo
```sh
git clone https://github.com/Crazy-Crew/CrazyAuctions.git
```
2. Open the repository using Intellij IDEA & wait until it finishes downloading/indexing.
3. Run the assemble task.
```gradle
./gradlew assemble
```
## Roadmap
Check our public [trello board](https://trello.com/b/CcPYmsBt) for our current plans, any bugs and general tracking of the project progress.
## Contributing
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/yourfeature`)
3. Commit your Changes (`git commit -m 'your amazing feature.'`)
4. Push to the Branch (`git push`)
5. Open a Pull Request to the dev branch to add your feature/fix.
## License
Distributed under the MIT License. See [`LICENSE`](/LICENSE) for more information.
[discord-shield]: https://img.shields.io/discord/182615261403283459.svg?style=flat&logo=appveyor
[discord-url]: https://discord.gg/crazycrew
[contributors-shield]: https://img.shields.io/github/contributors/Crazy-Crew/CrazyAuctions.svg?style=flat&logo=appveyor
[contributors-url]: https://github.com/Crazy-Crew/CrazyAuctions/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/Crazy-Crew/CrazyAuctions.svg?style=flat&logo=appveyor
[forks-url]: https://github.com/Crazy-Crew/CrazyAuctions/network/members
[stars-shield]: https://img.shields.io/github/stars/Crazy-Crew/CrazyAuctions.svg?style=flat&logo=appveyor
[stars-url]: https://github.com/Crazy-Crew/CrazyAuctions/stargazers
[issues-shield]: https://img.shields.io/github/issues/Crazy-Crew/CrazyAuctions.svg?style=flat&logo=appveyor
[issues-url]: https://github.com/Crazy-Crew/CrazyAuctions/issues
[license-shield]: https://img.shields.io/github/license/Crazy-Crew/CrazyAuctions.svg?style=flat&logo=appveyor
[license-url]: https://github.com/Crazy-Crew/CrazyAuctions/blob/master/LICENSE
[codefactor-shield]: https://img.shields.io/codefactor/grade/github/crazy-crew/CrazyAuctions/main?style=flat&logo=appveyor

29
build.gradle.kts Normal file
View File

@ -0,0 +1,29 @@
plugins {
id("root-plugin")
}
defaultTasks("build")
tasks {
assemble {
val jarsDir = File("$rootDir/jars")
if (jarsDir.exists()) jarsDir.delete()
subprojects.forEach { project ->
dependsOn(":${project.name}:build")
doLast {
if (!jarsDir.exists()) jarsDir.mkdirs()
if (project.name == "core") return@doLast
val file = file("${project.layout.buildDirectory.get()}/libs/${rootProject.name}-${rootProject.version}.jar")
copy {
from(file)
into(jarsDir)
}
}
}
}
}

11
buildSrc/build.gradle.kts Normal file
View File

@ -0,0 +1,11 @@
plugins {
`kotlin-dsl`
}
dependencies {
implementation(libs.paperweight.plugin)
implementation(libs.jpenilla.plugin)
implementation(libs.shadow.plugin)
}

View File

@ -0,0 +1,14 @@
dependencyResolutionManagement {
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
gradlePluginPortal()
mavenCentral()
}
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}

View File

@ -0,0 +1,23 @@
plugins {
id("io.papermc.paperweight.userdev")
id("root-plugin")
}
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
dependencies {
paperweight.paperDevBundle("1.20.2-R0.1-SNAPSHOT")
}
tasks {
assemble {
dependsOn(reobfJar)
}
reobfJar {
outputJar.set(file("${project.layout.buildDirectory.get()}/libs/${rootProject.name}-${rootProject.version}.jar"))
}
}

View File

@ -0,0 +1,46 @@
plugins {
id("com.github.johnrengelman.shadow")
`maven-publish`
`java-library`
}
repositories {
maven("https://repo.triumphteam.dev/snapshots/")
maven("https://repo.crazycrew.us/releases/")
maven("https://jitpack.io")
mavenCentral()
}
java {
toolchain.languageVersion.set(JavaLanguageVersion.of("17"))
}
tasks {
compileJava {
options.encoding = Charsets.UTF_8.name()
options.release.set(17)
}
shadowJar {
mergeServiceFiles()
exclude("META-INF/**")
}
}
publishing {
repositories {
maven {
credentials {
this.username = System.getenv("gradle_username")
this.password = System.getenv("gradle_password")
}
url = uri("https://repo.crazycrew.us/releases/")
}
}
}

14
common/build.gradle.kts Normal file
View File

@ -0,0 +1,14 @@
plugins {
id("root-plugin")
}
project.group = "${rootProject.group}.common"
project.version = "${rootProject.version}"
dependencies {
api(libs.configme) {
exclude("org.yaml", "snakeyaml")
}
compileOnly(libs.annotations)
}

View File

@ -0,0 +1,81 @@
package com.badbones69.crazyauctions.common;
import ch.jalu.configme.SettingsManager;
import ch.jalu.configme.SettingsManagerBuilder;
import com.badbones69.crazyauctions.common.config.ConfigBuilder;
import com.badbones69.crazyauctions.common.config.types.PluginConfig;
import java.io.File;
import java.nio.file.Path;
public class CrazyAuctionsPlugin {
private final Path path;
public CrazyAuctionsPlugin(Path path) {
this.path = path;
}
private static SettingsManager locale;
private static SettingsManager config;
private static SettingsManager pluginConfig;
public void load() {
File pluginConfigFile = new File(this.path.toFile(), "plugin-config.yml");
pluginConfig = SettingsManagerBuilder
.withYamlFile(pluginConfigFile)
.useDefaultMigrationService()
.configurationData(ConfigBuilder.buildPluginConfig())
.create();
File localeDir = new File(this.path.toFile(), "locale");
//FileUtils.extract("/locale/", this.path, false);
File localeFile = new File(localeDir, pluginConfig.getProperty(PluginConfig.LOCALE_FILE) + ".yml");
locale = SettingsManagerBuilder
.withYamlFile(localeFile)
.useDefaultMigrationService()
.configurationData(ConfigBuilder.buildLocale())
.create();
// Create config.yml
File configFile = new File(this.path.toFile(), "config.yml");
config = SettingsManagerBuilder
.withYamlFile(configFile)
.useDefaultMigrationService()
.configurationData(ConfigBuilder.buildConfig())
.create();
}
public void reload() {
// Reload configs.
pluginConfig.reload();
config.reload();
locale.reload();
File localeDir = new File(this.path.toFile(), "locale");
File localeFile = new File(localeDir, pluginConfig.getProperty(PluginConfig.LOCALE_FILE) + ".yml");
locale = SettingsManagerBuilder
.withYamlFile(localeFile)
.useDefaultMigrationService()
.configurationData(ConfigBuilder.buildLocale())
.create();
}
public static SettingsManager getPluginConfig() {
return pluginConfig;
}
public static SettingsManager getLocale() {
return locale;
}
public static SettingsManager getConfig() {
return config;
}
}

View File

@ -0,0 +1,30 @@
package com.badbones69.crazyauctions.common.config;
import ch.jalu.configme.configurationdata.ConfigurationData;
import ch.jalu.configme.configurationdata.ConfigurationDataBuilder;
import com.badbones69.crazyauctions.common.config.types.Config;
import com.badbones69.crazyauctions.common.config.types.Messages;
import com.badbones69.crazyauctions.common.config.types.PluginConfig;
public class ConfigBuilder {
private ConfigBuilder() {}
public static ConfigurationData buildPluginConfig() {
return ConfigurationDataBuilder.createConfiguration(
PluginConfig.class
);
}
public static ConfigurationData buildConfig() {
return ConfigurationDataBuilder.createConfiguration(
Config.class
);
}
public static ConfigurationData buildLocale() {
return ConfigurationDataBuilder.createConfiguration(
Messages.class
);
}
}

View File

@ -0,0 +1,43 @@
package com.badbones69.crazyauctions.common.config.types;
import ch.jalu.configme.Comment;
import ch.jalu.configme.SettingsHolder;
import ch.jalu.configme.configurationdata.CommentsConfiguration;
import ch.jalu.configme.properties.Property;
import static ch.jalu.configme.properties.PropertyInitializer.newProperty;
public class Config implements SettingsHolder {
public Config() {}
@Override
public void registerComments(CommentsConfiguration conf) {
String[] header = {
"Github: https://github.com/Crazy-Crew",
"",
"Issues: https://github.com/Crazy-Crew/CrazyAuctions/issues",
"Features: https://github.com/Crazy-Crew/CrazyAuctions//discussions/categories/features",
"",
"Legacy color codes such as &7,&c no longer work. You must use MiniMessage",
"https://docs.advntr.dev/minimessage/format.html#color"
};
String[] deprecation = {
"",
"Warning: This section is subject to change so it is considered deprecated.",
"This is your warning before the change happens.",
""
};
conf.setComment("misc", header);
}
@Comment("Allow damage items to be auctioned off.")
public static final Property<Boolean> damaged_items = newProperty("misc.allow-damaged-items", false);
@Comment("Whether or not to allow `ah sell` or not.")
public static final Property<Boolean> selling_module = newProperty("modules.selling-module", true);
@Comment("Whether or not to allow `ah buy` or not.")
public static final Property<Boolean> bidding_module = newProperty("modules.bidding-module", true);
}

View File

@ -0,0 +1,47 @@
package com.badbones69.crazyauctions.common.config.types;
import ch.jalu.configme.SettingsHolder;
import ch.jalu.configme.configurationdata.CommentsConfiguration;
import ch.jalu.configme.properties.Property;
import ch.jalu.configme.properties.PropertyInitializer;
public class Messages implements SettingsHolder {
public Messages() {}
@Override
public void registerComments(CommentsConfiguration conf) {
String[] header = {
"Submit your translations here: https://github.com/Crazy-Crew/CrazyAuctions/discussions/categories/translations",
"",
"Legacy color codes such as &7,&c no longer work. You must use MiniMessage",
"https://docs.advntr.dev/minimessage/format.html#color"
};
String[] deprecation = {
"",
"Warning: This section is subject to change so it is considered deprecated.",
"This is your warning before the change happens.",
""
};
conf.setComment("general", header);
}
public static final Property<String> unknown_command = PropertyInitializer.newProperty("general.unknown-command", "{prefix}<red>The command {command} is not known.</red>");
public static final Property<String> INVALID_SYNTAX = PropertyInitializer.newProperty("general.invalid-syntax", "{prefix}<gold>{value}</gold> <red>is an invalid {action}.</red>");
public static final Property<String> NO_PERMISSION = PropertyInitializer.newProperty("general.no-permission", "{prefix}<red>You do not have permission to use that command!</red>");
public static final Property<String> REQUIRED_ARGUMENT = PropertyInitializer.newProperty("general.checks.required-argument", "{prefix}<red>This argument is not optional</red>");
public static final Property<String> OPTIONAL_ARGUMENT = PropertyInitializer.newProperty("general.checks.optional-argument", "{prefix}<green>This argument is optional</green>");
public static final Property<String> NOT_ENOUGH_ARGS = PropertyInitializer.newProperty("general.checks.not-enough-args", "{prefix}<red>You did not supply enough arguments.</red>");
public static final Property<String> TOO_MANY_ARGS = PropertyInitializer.newProperty("general.checks.too-many-args", "{prefix}<red>You put more arguments then I can handle.</red>");
public static final Property<String> MUST_BE_PLAYER = PropertyInitializer.newProperty("general.player-checks.must-be-player", "{prefix}<red>You must be a player to use this command.</red>");
}

View File

@ -0,0 +1,33 @@
package com.badbones69.crazyauctions.common.config.types;
import ch.jalu.configme.Comment;
import ch.jalu.configme.SettingsHolder;
import ch.jalu.configme.properties.Property;
import ch.jalu.configme.properties.PropertyInitializer;
import static ch.jalu.configme.properties.PropertyInitializer.newProperty;
/**
* Description: The plugin-settings.yml options.
*/
public class PluginConfig implements SettingsHolder {
// Empty constructor required by SettingsHolder
protected PluginConfig() {}
@Comment({
"Choose what language you want the plugin to be in.",
"",
"Available Languages: en-US"
})
public static final Property<String> LOCALE_FILE = PropertyInitializer.newProperty("language", "en-US");
@Comment("Whether you want CrazyAuctions to shut up or not, This option is ignored by errors.")
public static final Property<Boolean> verbose_logging = newProperty("verbose_logging", true);
@Comment({
"Sends anonymous statistics about how the plugin is used to bstats.org.",
"bstats is a service for plugin developers to find out how the plugin being used,",
"This information helps us figure out how to better improve the plugin."
})
public static final Property<Boolean> toggle_metrics = newProperty("toggle_metrics", true);
}

View File

@ -0,0 +1,39 @@
package com.badbones69.crazyauctions.common.data;
import java.nio.file.Path;
import java.util.UUID;
public interface UserCache {
/**
* Add a player to the hashmap if absent.
*
* @param uuid player uuid
*/
void addPlayer(final UUID uuid);
/**
* Remove the player from the hashmap.
*
* @param uuid player uuid
*/
void removePlayer(final UUID uuid);
/**
* Fetch the player if online or offline.
*
* @param uuid player uuid
* @return player object
*/
String getPlayerName(final UUID uuid);
/**
* Fetch the uuid file of the player.
*
* @param path the path i.e. 'CrazyAuctions/userdata/random-uuid.'
* @param uuid the player uuid
* @return the complete path
*/
Path getFile(final Path path, UUID uuid);
}

15
gradle.properties Normal file
View File

@ -0,0 +1,15 @@
org.gradle.jvmargs = '-Xmx3G'
org.gradle.parallel = false
org.gradle.warning.mode = all
authors = ["Ryderbelserion, Badbones69"]
website = https://modrinth.com/plugin/crazycrates
sources = https://github.com/Crazy-Crew/CrazyCrates
issues = https://github.com/Crazy-Crew/CrazyCrates/issues
group = us.crazycrew.crazycrates
description = Add unlimited crates to your server with 10 different crate types to choose from!
version = 1.18
apiVersion = 1.20
minecraftVersion=1.20.2

46
gradle/libs.versions.toml Normal file
View File

@ -0,0 +1,46 @@
[versions]
paperweight_version = "1.5.8"
run_paper_version = "2.2.0"
shadow_version = "8.1.1"
jetbrains_kotlin = "1.9.10"
cluster_version = "2.4"
kyori_version = "4.14.0"
[plugins]
hangar = { id = "io.papermc.hangar-publish-plugin", version = "0.1.0" }
modrinth = { id = "com.modrinth.minotaur", version = "2.8.4" }
[libraries]
cluster_paper = { module = "com.ryderbelserion.cluster:cluster-paper", version.ref = "cluster_version" }
cluster_api = { module = "com.ryderbelserion.cluster:cluster-api", version.ref = "cluster_version" }
adventure = { module = "net.kyori:adventure-api", version.ref = "kyori_version" }
minimessage = { module = "net.kyori:adventure-text-minimessage", version.ref = "kyori_version" }
nbtapi = { module = "de.tr7zw:item-nbt-api", version = "2.12.0" }
annotations = { module = "org.jetbrains:annotations", version = "24.0.1" }
kotlin = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "jetbrains_kotlin" }
triumphcmds = { module = "dev.triumphteam:triumph-cmd-bukkit", version = "2.0.0-SNAPSHOT" }
configme = { module = "ch.jalu:configme", version = "1.4.1" }
metrics = { module = "org.bstats:bstats-bukkit", version = "3.0.2" }
itemsadder = { module = "com.github.LoneDev6:api-itemsadder", version = "3.6.1" }
oraxen = { module = "com.github.oraxen:oraxen", version = "1.162.0" }
holographicdisplays = { module = "me.filoghost.holographicdisplays:holographicdisplays-api", version = "3.0.0" }
decentholograms = { module = "com.github.decentsoftware-eu:decentholograms", version = "2.8.4" }
placeholderapi = { module = "me.clip:placeholderapi", version = "2.11.4" }
# Plugins
paperweight_plugin = { module = "io.papermc.paperweight:paperweight-userdev", version.ref = "paperweight_version" }
jpenilla_plugin = { module = "xyz.jpenilla:run-task", version.ref = "run_paper_version" }
shadow_plugin = { module = "com.github.johnrengelman:shadow", version.ref = "shadow_version" }
kotlin_plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "jetbrains_kotlin" }

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

Binary file not shown.

View File

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

249
gradlew vendored Normal file
View File

@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

125
paper/build.gradle.kts Normal file
View File

@ -0,0 +1,125 @@
import io.papermc.hangarpublishplugin.model.Platforms
plugins {
alias(libs.plugins.modrinth)
alias(libs.plugins.hangar)
id("xyz.jpenilla.run-paper")
id("paper-plugin")
}
project.group = "${rootProject.group}.paper"
repositories {
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/")
maven("https://repo.codemc.org/repository/maven-public/")
maven("https://repo.crazycrew.us/first-party/")
maven("https://repo.crazycrew.us/third-party/")
flatDir { dirs("libs") }
}
dependencies {
}
tasks {
runServer {
jvmArgs("-Dnet.kyori.ansi.colorLevel=truecolor")
minecraftVersion("1.20.2")
}
shadowJar {
listOf(
"de.tr7zw.changeme.nbtapi",
"org.bstats",
"ch.jalu"
).forEach {
relocate(it, "libs.$it")
}
}
processResources {
val props = mapOf(
"name" to rootProject.name,
"group" to project.group.toString(),
"version" to rootProject.version,
"description" to rootProject.description,
"authors" to rootProject.properties["authors"],
"apiVersion" to "1.20",
"website" to "https://modrinth.com/plugin/${rootProject.name.lowercase()}"
)
filesMatching("plugin.yml") {
expand(props)
}
}
}
val isSnapshot = true
val type = if (isSnapshot) "beta" else "release"
val other = if (isSnapshot) "Beta" else "Release"
val file = file("${rootProject.rootDir}/jars/${rootProject.name}-${rootProject.version}.jar")
val description = """
## Fixes:
* Fix not crates being wrongly labeled as virtual crates if they are quadcrate, quickcrate or ones that need to be in the physical world.
## Other:
* [Feature Requests](https://github.com/Crazy-Crew/${rootProject.name}/issues)
* [Bug Reports](https://github.com/Crazy-Crew/${rootProject.name}/issues)
""".trimIndent()
val versions = listOf(
"1.20",
"1.20.1",
"1.20.2"
)
modrinth {
autoAddDependsOn.set(false)
token.set(System.getenv("modrinth_token"))
projectId.set(rootProject.name.lowercase())
versionName.set("${rootProject.name} ${rootProject.version}")
versionNumber.set("${rootProject.version}")
versionType.set(type)
uploadFile.set(file("${rootProject.rootDir}/jars/${rootProject.name}-${rootProject.version}.jar"))
gameVersions.addAll(versions)
changelog.set(description)
loaders.addAll("paper", "purpur")
}
hangarPublish {
publications.register("plugin") {
version.set(rootProject.version as String)
id.set(rootProject.name)
channel.set(if (isSnapshot) "Beta" else "Release")
changelog.set(description)
apiKey.set(System.getenv("hangar_key"))
platforms {
register(Platforms.PAPER) {
jar.set(file("${rootProject.rootDir}/jars/${rootProject.name}-${rootProject.version}.jar"))
platformVersions.set(versions)
}
}
}
}

View File

@ -0,0 +1,55 @@
package com.badbones69.crazyauctions;
import com.badbones69.crazyauctions.api.CrazyManager;
import com.badbones69.crazyauctions.api.frame.PaperCore;
import com.badbones69.crazyauctions.api.frame.command.CommandManager;
import com.badbones69.crazyauctions.commands.inventories.AuctionInventoryClick;
import com.badbones69.crazyauctions.events.DataListener;
import org.bukkit.plugin.java.JavaPlugin;
public class CrazyAuctions extends JavaPlugin {
private final ApiManager apiManager;
private final PaperCore paperCore;
private CommandManager commandManager;
private CrazyManager crazyManager;
public CrazyAuctions(ApiManager apiManager, PaperCore paperCore) {
this.apiManager = apiManager;
this.paperCore = paperCore;
}
@Override
public void onEnable() {
this.commandManager = CommandManager.create();
this.crazyManager = new CrazyManager();
this.crazyManager.load(true);
getServer().getPluginManager().registerEvents(new DataListener(), this);
getServer().getPluginManager().registerEvents(new AuctionInventoryClick(), this);
}
@Override
public void onDisable() {
if (this.crazyManager != null) this.crazyManager.stop();
}
public ApiManager getApiManager() {
return this.apiManager;
}
public PaperCore getPaperCore() {
return this.paperCore;
}
public CommandManager getCommandManager() {
return this.commandManager;
}
public CrazyManager getCrazyManager() {
return this.crazyManager;
}
}

View File

@ -0,0 +1,30 @@
package com.badbones69.crazyauctions;
import com.badbones69.crazyauctions.api.frame.PaperCore;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
import io.papermc.paper.plugin.bootstrap.PluginProviderContext;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import com.badbones69.crazyauctions.config.types.PluginConfig;
@SuppressWarnings("ALL")
public class CrazyStarter implements PluginBootstrap {
private ApiManager apiManager;
@Override
public void bootstrap(@NotNull BootstrapContext context) {
this.apiManager = new ApiManager(context.getDataDirectory());
this.apiManager.load();
}
@Override
public @NotNull JavaPlugin createPlugin(@NotNull PluginProviderContext context) {
PaperCore paperCore = new PaperCore(context.getDataDirectory(), Bukkit.getConsoleSender(), ApiManager.getPluginConfig().getProperty(PluginConfig.COMMAND_PREFIX), ApiManager.getPluginConfig().getProperty(PluginConfig.CONSOLE_PREFIX));
paperCore.enable();
return new CrazyAuctions(this.apiManager, paperCore);
}
}

View File

@ -0,0 +1,34 @@
package com.badbones69.crazyauctions.api;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.storage.types.StorageManager;
import org.bukkit.plugin.java.JavaPlugin;
public class CrazyManager {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private StorageManager storageManager;
public void load(boolean serverStart) {
if (serverStart) {
this.storageManager = new StorageManager();
this.storageManager.init();
}
}
public void reload() {
if (this.plugin.getApiManager() != null) this.plugin.getApiManager().reload();
if (this.storageManager.getUserManager() != null) this.storageManager.getUserManager().save(false);
}
public void stop() {
}
public StorageManager getStorageManager() {
return this.storageManager;
}
}

View File

@ -0,0 +1,38 @@
package com.badbones69.crazyauctions.api.enums;
import org.bukkit.permissions.PermissionDefault;
public enum Permissions {
PLAYER_HELP("player.help", "Gives access to the help command.", PermissionDefault.TRUE);
private final String node;
private final String description;
private final PermissionDefault permissionDefault;
Permissions(String node, String description, PermissionDefault permissionDefault) {
this.node = node;
this.description = description;
this.permissionDefault = permissionDefault;
}
public String getNode() {
return this.node;
}
public String getDescription() {
return this.description;
}
public PermissionDefault getPermissionDefault() {
return this.permissionDefault;
}
public String getBuiltPermission(String action) {
return "crazyauctions." + action + "." + this.node;
}
public String getBuiltPermission() {
return "crazyauctions.command." + this.node;
}
}

View File

@ -0,0 +1,19 @@
package com.badbones69.crazyauctions.api.enums.support;
import com.badbones69.crazyauctions.storage.interfaces.UserManager;
import com.badbones69.crazyauctions.storage.types.file.yaml.YamlUserManager;
public enum DataSupport {
yaml(YamlUserManager.class);
private final Class<? extends UserManager> classObject;
DataSupport(Class<? extends UserManager> classObject) {
this.classObject = classObject;
}
public Class<? extends UserManager> getClassObject() {
return this.classObject;
}
}

View File

@ -0,0 +1,62 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.manager.interfaces.AuctionItem;
import com.badbones69.crazyauctions.api.manager.objects.AuctionHouse;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when an item is added to an auction house.
*/
public class AuctionAddEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final AuctionItem auctionItem;
private final AuctionHouse auctionHouse;
/**
* A constructor to include values for a bid event.
*
* @param uuid the uuid of the player who placed the bid.
* @param auctionHouse the auction house the item is being added to.
* @param auctionItem the auction item being added.
*/
public AuctionAddEvent(UUID uuid, AuctionHouse auctionHouse, AuctionItem auctionItem) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.auctionHouse = auctionHouse;
this.auctionItem = auctionItem;
}
public AuctionItem getAuctionItem() {
return auctionItem;
}
public AuctionHouse getAuctionHouse() {
return auctionHouse;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,65 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when a player bids on an auction.
*/
public class AuctionBidEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final ItemStack item;
private final long bidPrice;
/**
* A constructor to include values for a bid event.
*
* @param uuid the uuid of the player who placed the bid.
* @param item the item that was bid on.
* @param bidPrice the amount of money that was bid.
*/
public AuctionBidEvent(UUID uuid, ItemStack item, long bidPrice) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.item = item;
this.bidPrice = bidPrice;
}
public ItemStack getBidItem() {
return this.item;
}
public long getBidPrice() {
return this.bidPrice;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,65 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when a player buys an item.
*/
public class AuctionBuyEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final ItemStack item;
private final long price;
/**
* A constructor to include values for a buy event.
*
* @param uuid the uuid of the player who purchased the item.
* @param item the item that was purchased.
* @param price the amount of money used to buy.
*/
public AuctionBuyEvent(UUID uuid, ItemStack item, long price) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.item = item;
this.price = price;
}
public ItemStack getWinningItem() {
return this.item;
}
public long getBuyPrice() {
return this.price;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,82 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when an auction is cancelled.
*/
public class AuctionCancelEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final OfflinePlayer offlinePlayer;
private final ItemStack item;
/**
* A constructor to include values for when an item is cancelled.
*
* @param uuid the uuid of the player whose item cancelled.
*/
public AuctionCancelEvent(UUID uuid, ItemStack item) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.offlinePlayer = this.plugin.getServer().getOfflinePlayer(uuid);
this.item = item;
}
/**
* @return the expired item.
*/
public ItemStack getExpiredItem() {
return this.item;
}
/**
* Only use this when the player is online.
*
* @return the online player.
*/
public Player getPlayer() {
return this.player;
}
/**
* Only use this when the player is offline.
*
* @return the offline player.
*/
public OfflinePlayer getOfflinePlayer() {
return this.offlinePlayer;
}
/**
* @return the player's uuid.
*/
public UUID getUUID() {
return this.uuid;
}
/**
* @return the handler list.
*/
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,55 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when an auction expires.
*/
public class AuctionExpireEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final ItemStack item;
/**
* A constructor to include values for when an item expired.
*
* @param uuid the uuid of the player whose auction expired.
*/
public AuctionExpireEvent(UUID uuid, ItemStack item) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.item = item;
}
public ItemStack getExpiredItem() {
return this.item;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,65 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when a player lists an item.
*/
public class AuctionListEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final ItemStack item;
private final long bidPrice;
/**
* A constructor to include values for a bid event.
*
* @param uuid the uuid of the player who placed the bid.
* @param item the item that was bid on.
* @param bidPrice the amount of money that was bid.
*/
public AuctionListEvent(UUID uuid, ItemStack item, long bidPrice) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.item = item;
this.bidPrice = bidPrice;
}
public ItemStack getBidItem() {
return this.item;
}
public long getBidPrice() {
return this.bidPrice;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,65 @@
package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
/**
* Description: This event is fired when an auction has a winner.
*/
public class AuctionWinEvent extends Event {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private static final HandlerList handlerList = new HandlerList();
private final UUID uuid;
private final Player player;
private final ItemStack item;
private final long price;
/**
* A constructor to include values for a win event.
*
* @param uuid the uuid of the player who won the bid.
* @param item the item that was won.
* @param price the amount of money that was bid.
*/
public AuctionWinEvent(UUID uuid, ItemStack item, long price) {
this.uuid = uuid;
this.player = this.plugin.getServer().getPlayer(uuid);
this.item = item;
this.price = price;
}
public ItemStack getWinningItem() {
return this.item;
}
public long getWinningPrice() {
return this.price;
}
public Player getPlayer() {
return this.player;
}
public UUID getUUID() {
return this.uuid;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -0,0 +1,27 @@
package com.badbones69.crazyauctions.api.frame;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class ItemUtils {
private final Material skull = Material.PLAYER_HEAD;
public ItemStack skull() {
return new ItemStack(skull);
}
public boolean isPlayerSkull(Material itemStack) {
return itemStack != skull;
}
private String getVersion() {
String version = Bukkit.getServer().getClass().getPackage().getName();
return version.substring(version.lastIndexOf('.') + 1);
}
public Class<?> craftClass(String name) throws ClassNotFoundException {
return Class.forName("org.bukkit.craftbukkit." + getVersion() + "." + name);
}
}

View File

@ -0,0 +1,140 @@
package com.badbones69.crazyauctions.api.frame;
import com.badbones69.crazyauctions.ApiManager;
import com.badbones69.crazyauctions.config.types.Locale;
import com.badbones69.crazyauctions.config.types.PluginConfig;
import com.badbones69.crazyauctions.frame.CrazyCore;
import com.badbones69.crazyauctions.frame.storage.FileHandler;
import net.kyori.adventure.audience.Audience;
import java.nio.file.Path;
public class PaperCore extends CrazyCore {
private final Path path;
private final Audience audience;
private final FileHandler fileHandler;
private final String prefix;
private final String consolePrefix;
public PaperCore(Path path, Audience audience, String prefix, String consolePrefix) {
// Create directory.
this.path = path;
this.path.toFile().mkdir();
this.audience = audience;
this.prefix = prefix;
this.consolePrefix = consolePrefix;
this.fileHandler = new FileHandler();
}
@Override
public void enable() {
super.enable();
}
@Override
public void disable() {
super.disable();
}
@Override
public Path getDirectory() {
return this.path;
}
@Override
public String getPrefix() {
return this.prefix;
}
@Override
public String getConsolePrefix() {
return this.consolePrefix;
}
@Override
public FileHandler getFileHandler() {
return this.fileHandler;
}
@Override
public Audience adventure() {
return this.audience;
}
@Override
public String commandTooFewArgs() {
return ApiManager.getLocale().getProperty(Locale.NOT_ENOUGH_ARGS);
}
@Override
public String commandTooManyArgs() {
return ApiManager.getLocale().getProperty(Locale.TOO_MANY_ARGS);
}
@Override
public String commandOptionalMsg() {
return ApiManager.getLocale().getProperty(Locale.OPTIONAL_ARGUMENT);
}
@Override
public String commandRequiredMsg() {
return ApiManager.getLocale().getProperty(Locale.REQUIRED_ARGUMENT);
}
@Override
public String commandRequirementNotPlayer() {
return ApiManager.getLocale().getProperty(Locale.MUST_BE_PLAYER);
}
@Override
public String commandRequirementNoPermission() {
return ApiManager.getLocale().getProperty(Locale.NO_PERMISSION);
}
@Override
public String commandHelpHeader() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_HEADER);
}
@Override
public String commandHelpFooter() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_FOOTER);
}
@Override
public String commandInvalidPage() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.INVALID_HELP_PAGE);
}
@Override
public String commandPageFormat() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_FORMAT);
}
@Override
public String commandHoverFormat() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_HOVER_FORMAT);
}
@Override
public String commandHoverAction() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_HOVER_ACTION);
}
@Override
public String commandNavigationText() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_GO_TO_PAGE);
}
@Override
public String commandNavigationNextButton() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_NEXT);
}
@Override
public String commandNavigationBackButton() {
return ApiManager.getPluginConfig().getProperty(PluginConfig.HELP_PAGE_BACK);
}
}

View File

@ -0,0 +1,25 @@
package com.badbones69.crazyauctions.api.frame;
public class PaperUtils {
private static boolean hasClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
public static boolean isSpigot() {
return hasClass("org.spigotmc.SpigotConfig") && !hasClass("io.papermc.paper.configuration.Configuration") || !hasClass("com.destroystokyo.paper.PaperConfig");
}
public static boolean isPaper() {
return hasClass("io.papermc.paper.configuration.Configuration") || hasClass("com.destroystokyo.paper.PaperConfig");
}
public static boolean isFolia() {
return hasClass("io.papermc.paper.threadedregions.RegionizedServer");
}
}

View File

@ -0,0 +1,52 @@
package com.badbones69.crazyauctions.api.frame.adapters;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import java.io.IOException;
public class LocationTypeAdapter extends TypeAdapter<Location> {
@Override
public void write(JsonWriter out, Location location) throws IOException {
out.beginObject();
out.name("world").value(location.getWorld().getName());
out.name("x").value(location.getX());
out.name("y").value(location.getY());
out.name("z").value(location.getZ());
out.name("yaw").value(location.getYaw());
out.name("pitch").value(location.getPitch());
out.endObject();
}
@Override
public Location read(JsonReader reader) throws IOException {
reader.beginObject();
String worldName = null;
double x = 0, y = 0, z = 0;
float yaw = 0, pitch = 0;
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "world" -> worldName = reader.nextString();
case "x" -> x = reader.nextDouble();
case "y" -> y = reader.nextDouble();
case "z" -> z = reader.nextDouble();
case "yaw" -> yaw = (float) reader.nextDouble();
case "pitch" -> pitch = (float) reader.nextDouble();
default -> reader.skipValue();
}
}
reader.endObject();
assert worldName != null;
return new Location(Bukkit.getWorld(worldName), x, y, z, yaw, pitch);
}
}

View File

@ -0,0 +1,268 @@
package com.badbones69.crazyauctions.api.frame.command;
import com.badbones69.crazyauctions.ApiManager;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandActor;
import com.badbones69.crazyauctions.api.frame.command.builders.args.CommandArgs;
import com.badbones69.crazyauctions.config.types.Locale;
import com.badbones69.crazyauctions.frame.utils.AdventureUtils;
import com.badbones69.crazyauctions.support.PlaceholderSupport;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class CommandContext implements CommandActor, CommandArgs {
private final Audience audience;
private final List<String> args;
private String label;
private Player player;
public CommandContext(Audience audience, String label, List<String> args) {
this.audience = audience;
if (audience instanceof Player) {
this.player = (Player) audience;
}
this.label = label;
this.args = args;
}
@Override
public void reply(String message) {
if (message.isBlank() || message.isEmpty()) return;
Component component = AdventureUtils.parse(message);
this.audience.sendMessage(component);
}
@Override
public void reply(boolean hasPrefix, String prefix, String message) {
if (message.isBlank() || message.isEmpty()) return;
if (hasPrefix) {
Component component = AdventureUtils.parse(prefix).append(AdventureUtils.parse(prefix));
this.audience.sendMessage(component);
return;
}
Component component = AdventureUtils.parse(message);
this.audience.sendMessage(component);
}
@Override
public void reply(boolean hasPrefix, String prefix, Component component) {
if (hasPrefix) {
this.audience.sendMessage(AdventureUtils.parse(prefix).append(component));
return;
}
this.audience.sendMessage(component);
}
@Override
public void reply(Component component) {
this.audience.sendMessage(component);
}
@Override
public void send(Audience audience, String message) {
if (message.isBlank() || message.isEmpty()) return;
Component component = AdventureUtils.parse(message);
audience.sendMessage(component);
}
@Override
public void send(Audience audience, Component component) {
audience.sendMessage(component);
}
@Override
public void send(Audience audience, String message, String prefix, boolean hasPrefix) {
if (hasPrefix) {
audience.sendMessage(AdventureUtils.parse(prefix).append(AdventureUtils.parse(message)));
return;
}
send(audience, message);
}
@Override
public void send(Audience audience, Component message, String prefix, boolean hasPrefix) {
if (hasPrefix) {
audience.sendMessage(AdventureUtils.parse(prefix).append(message));
return;
}
send(audience, message);
}
@Override
public Audience getSender() {
return this.audience;
}
@Override
public boolean isPlayer() {
return getPlayer() != null;
}
@Override
public Player getPlayer() {
return this.player;
}
@Override
public boolean hasPermission(Permission permission) {
return this.player.hasPermission(permission);
}
@Override
public boolean hasPermission(String rawPermission) {
return this.player.hasPermission(rawPermission);
}
@Override
public void setLabel(String label) {
this.label = label;
}
@Override
public String getLabel() {
return this.label;
}
public List<String> getArgs() {
return Collections.unmodifiableList(this.args);
}
@Override
public void removeArgs(int arg) {
this.args.remove(arg);
}
@Override
public int getArgAsInt(int index, boolean notifySender) {
Integer value = null;
try {
value = Integer.parseInt(this.args.get(index));
} catch (NumberFormatException exception) {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index))
.replaceAll("\\{action}", "number")));
}
if (value != null) return value;
return 1;
}
@Override
public long getArgAsLong(int index, boolean notifySender) {
Long value = null;
try {
value = Long.parseLong(this.args.get(index));
} catch (NumberFormatException exception) {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index))
.replaceAll("\\{action}", "number")));
}
if (value != null) return value;
return 1L;
}
@Override
public double getArgAsDouble(int index, boolean notifySender) {
Double value = null;
try {
value = Double.parseDouble(this.args.get(index));
} catch (NumberFormatException exception) {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index))
.replaceAll("\\{action}", "number")));
}
if (value != null) return value;
return 0.1;
}
@Override
public boolean getArgAsBoolean(int index, boolean notifySender) {
String lowercase = this.args.get(index).toLowerCase();
switch (lowercase) {
case "true", "on", "1" -> {
return true;
}
case "false", "off", "0" -> {
return false;
}
default -> {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index).toLowerCase())
.replaceAll("\\{action}", "boolean")));
return false;
}
}
}
@Override
public float getArgAsFloat(int index, boolean notifySender) {
Float value = null;
try {
value = Float.parseFloat(this.args.get(index));
} catch (NumberFormatException exception) {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index))
.replaceAll("\\{action}", "number")));
}
if (value != null) return value;
return 1F;
}
@Override
public Player getArgAsPlayer(int index, boolean notifySender) {
Player player = Bukkit.getServer().getPlayer(this.args.get(index));
if (player == null) {
if (notifySender) reply(PlaceholderSupport.setPlaceholders(ApiManager.getLocale().getProperty(Locale.INVALID_SYNTAX)
.replaceAll("\\{value}", this.args.get(index))
.replaceAll("\\{action}", "player")));
return null;
}
return player;
}
@Override
public OfflinePlayer getArgAsOfflinePlayer(int index) {
CompletableFuture<UUID> future = CompletableFuture.supplyAsync(() -> Bukkit.getServer().getOfflinePlayer(this.args.get(index))).thenApply(OfflinePlayer::getUniqueId);
return Bukkit.getServer().getOfflinePlayer(future.join());
}
}

View File

@ -0,0 +1,164 @@
package com.badbones69.crazyauctions.api.frame.command;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandDataEntry;
import com.badbones69.crazyauctions.api.frame.command.builders.args.Argument;
import com.badbones69.crazyauctions.frame.CrazyCore;
import com.badbones69.crazyauctions.frame.utils.AdventureUtils;
import com.badbones69.crazyauctions.support.PlaceholderSupport;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public abstract class CommandEngine extends Command {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final LinkedList<String> labels = new LinkedList<>();
public final LinkedList<Argument> requiredArgs = new LinkedList<>();
public final LinkedList<Argument> optionalArgs = new LinkedList<>();
private final HashMap<String, CommandDataEntry> commandData = new HashMap<>();
protected CommandEngine(@NotNull String name, @NotNull String description, @NotNull String usageMessage, @NotNull List<String> aliases) {
super(name, description, usageMessage, aliases);
}
public void execute(CommandContext context, String[] args) {
perform(context, args);
}
public void execute(CommandContext context) {
StringBuilder label = new StringBuilder(context.getLabel());
if (!context.getArgs().isEmpty()) {
for (CommandEngine engine : this.plugin.getCommandManager().getClasses()) {
boolean isPresent = context.getArgs().stream().findFirst().isPresent();
if (isPresent) {
label.append(" ").append(context.getArgs().get(0));
context.removeArgs(0);
context.setLabel(label.toString());
engine.execute(context);
return;
}
}
}
if (!validate(context)) return;
perform(context, new String[0]);
}
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
List<String> arguments = Arrays.asList(args);
CommandContext context = new CommandContext(
sender,
label,
arguments
);
if (arguments.isEmpty()) {
execute(context);
return true;
}
execute(context, args);
return true;
}
protected abstract void perform(CommandContext context, String[] args);
private boolean validate(CommandContext context) {
if (context.getArgs().size() < this.requiredArgs.size()) {
context.reply(CrazyCore.api().commandTooFewArgs());
sendValidFormat(context);
return false;
}
if (context.getArgs().size() > this.requiredArgs.size() + this.optionalArgs.size()) {
context.reply(CrazyCore.api().commandTooManyArgs());
sendValidFormat(context);
return false;
}
return true;
}
private void sendValidFormat(CommandContext context) {
ArrayList<Argument> arguments = new ArrayList<>();
arguments.addAll(this.requiredArgs);
arguments.addAll(this.optionalArgs);
this.requiredArgs.sort(Comparator.comparing(Argument::order));
if (context.isPlayer()) {
StringBuilder format = new StringBuilder("/" + "crazycrates:" + getLabel());
TextComponent.@NotNull Builder emptyComponent = Component.text();
StringBuilder types = new StringBuilder();
for (Argument arg : arguments) {
String value = this.optionalArgs.contains(arg) ? " (" + arg.name() + ") " : " <" + arg.name() + ">";
String msg = this.optionalArgs.contains(arg) ? CrazyCore.api().commandOptionalMsg() : CrazyCore.api().commandRequiredMsg();
Component argComponent = AdventureUtils.parse(value).hoverEvent(HoverEvent.showText(AdventureUtils.parse(PlaceholderSupport.setPlaceholders(msg)))).asComponent();
emptyComponent.append(argComponent);
boolean isPresent = arg.argumentType().getPossibleValues().stream().findFirst().isPresent();
if (isPresent) types.append(" ").append(arg.argumentType().getPossibleValues().stream().findFirst().get());
}
TextComponent.@NotNull Builder finalComponent = emptyComponent
.hoverEvent(HoverEvent.showText(AdventureUtils.parse("<gold>Click me to insert into chat</gold>")))
.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.SUGGEST_COMMAND, format.append(types).toString()))
.append(emptyComponent.build());
context.reply(finalComponent.build());
return;
}
StringBuilder format = new StringBuilder("/" + "crazycrates:" + getLabel());
for (Argument arg : arguments) {
String value = this.optionalArgs.contains(arg) ? "(" + arg.name() + ") " : "<" + arg.name() + "> ";
format.append(value);
}
context.reply(format.toString());
}
public List<String> getLabels() {
return Collections.unmodifiableList(this.labels);
}
public Map<String, CommandDataEntry> getCommandData() {
return Collections.unmodifiableMap(this.commandData);
}
public List<Argument> getRequiredArgs() {
return Collections.unmodifiableList(this.requiredArgs);
}
public List<Argument> getOptionalArgs() {
return Collections.unmodifiableList(this.optionalArgs);
}
}

View File

@ -0,0 +1,30 @@
package com.badbones69.crazyauctions.api.frame.command;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandActor;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandDataEntry;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandHelpEntry;
import java.util.List;
import java.util.Map;
public interface CommandFlow {
void addCommand(CommandEngine engine);
boolean hasCommand(String label);
CommandHelpEntry generateCommandHelp(CommandActor actor);
int defaultHelpPerPage();
void updateHelpPerPage(int newAmount);
CommandDataEntry getCommand(String label);
void removeCommand(String label);
Map<String, CommandDataEntry> getCommands();
List<CommandEngine> getClasses();
List<String> handleTabComplete(String[] args, CommandEngine engine);
}

View File

@ -0,0 +1,123 @@
package com.badbones69.crazyauctions.api.frame.command;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandActor;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandDataEntry;
import com.badbones69.crazyauctions.api.frame.command.builders.CommandHelpEntry;
import com.badbones69.crazyauctions.api.frame.command.builders.annotations.Hidden;
import com.badbones69.crazyauctions.api.frame.command.builders.args.Argument;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import java.util.*;
public class CommandManager implements CommandFlow {
private final HashMap<String, CommandDataEntry> commands = new HashMap<>();
private final LinkedList<CommandEngine> classes = new LinkedList<>();
private int defaultHelpPerPage = 10;
public static CommandManager create() {
return new CommandManager();
}
@Override
public void addCommand(CommandEngine engine) {
// If the label already exists. We return!
if (hasCommand(engine.getLabel())) return;
// Create data entry.
CommandDataEntry entry = new CommandDataEntry();
// Set visibility if annotation is present.
entry.setHidden(engine.getClass().isAnnotationPresent(Hidden.class));
if (entry.isHidden()) return;
// Add to the hash-map & linked list!
this.commands.put(engine.getLabel(), entry);
this.classes.add(engine);
// Add command to the server map!
Bukkit.getServer().getCommandMap().register("crazycrates", engine);
}
@Override
public boolean hasCommand(String label) {
return this.commands.containsKey(label);
}
@Override
public CommandHelpEntry generateCommandHelp(CommandActor actor) {
return new CommandHelpEntry(this, actor);
}
@Override
public int defaultHelpPerPage() {
return this.defaultHelpPerPage;
}
@Override
public void updateHelpPerPage(int newAmount) {
this.defaultHelpPerPage = newAmount;
}
@Override
public CommandDataEntry getCommand(String label) {
if (hasCommand(label)) return this.commands.get(label);
return null;
}
@Override
public void removeCommand(String label) {
if (!hasCommand(label)) return;
Command value = Bukkit.getServer().getCommandMap().getCommand(label);
if (value != null && value.isRegistered()) value.unregister(Bukkit.getServer().getCommandMap());
this.commands.remove(label);
}
@Override
public Map<String, CommandDataEntry> getCommands() {
return Collections.unmodifiableMap(this.commands);
}
@Override
public List<CommandEngine> getClasses() {
return Collections.unmodifiableList(this.classes);
}
@Override
public List<String> handleTabComplete(String[] args, CommandEngine engine) {
List<String> completions = Arrays.asList(args);
if (completions.size() >= 1) {
int relativeIndex = this.classes.size();
int argToComplete = completions.size() + 1 - relativeIndex;
if (engine.requiredArgs.size() >= argToComplete) {
ArrayList<Argument> arguments = new ArrayList<>();
arguments.addAll(engine.requiredArgs);
arguments.addAll(engine.optionalArgs);
ArrayList<String> possibleValues = new ArrayList<>();
for (Argument argument : arguments) {
if (argument.order() == argToComplete) {
List<String> possibleValuesArgs = argument.argumentType().getPossibleValues();
possibleValues = new ArrayList<>(possibleValuesArgs);
break;
}
}
return possibleValues;
}
}
return Collections.emptyList();
}
}

View File

@ -0,0 +1,48 @@
package com.badbones69.crazyauctions.api.frame.command.builders;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import java.util.List;
public interface CommandActor {
void reply(String message);
void reply(boolean hasPrefix, String prefix, String message);
void reply(boolean hasPrefix, String prefix, Component component);
void reply(Component component);
void send(Audience audience, String message);
void send(Audience audience, Component component);
void send(Audience audience, String message, String prefix, boolean hasPrefix);
void send(Audience audience, Component message, String prefix, boolean hasPrefix);
Audience getSender();
boolean isPlayer();
Player getPlayer();
boolean hasPermission(Permission permission);
boolean hasPermission(String rawPermission);
void setLabel(String alias);
String getLabel();
List<String> getArgs();
void removeArgs(int arg);
//CommandHelpEntry getHelpEntry();
}

View File

@ -0,0 +1,14 @@
package com.badbones69.crazyauctions.api.frame.command.builders;
public class CommandDataEntry {
private boolean isHidden = false;
public void setHidden(boolean value) {
this.isHidden = value;
}
public boolean isHidden() {
return this.isHidden;
}
}

View File

@ -0,0 +1,156 @@
package com.badbones69.crazyauctions.api.frame.command.builders;
import com.badbones69.crazyauctions.ApiManager;
import com.badbones69.crazyauctions.api.frame.command.CommandEngine;
import com.badbones69.crazyauctions.api.frame.command.CommandManager;
import com.badbones69.crazyauctions.api.frame.command.builders.args.Argument;
import com.badbones69.crazyauctions.api.frame.command.builders.other.ComponentBuilder;
import com.badbones69.crazyauctions.config.types.PluginConfig;
import com.badbones69.crazyauctions.frame.CrazyCore;
import com.badbones69.crazyauctions.support.PlaceholderSupport;
import net.kyori.adventure.text.event.ClickEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;
import static com.badbones69.crazyauctions.frame.utils.AdventureUtils.hover;
import static com.badbones69.crazyauctions.frame.utils.AdventureUtils.send;
public class CommandHelpEntry {
private final CommandManager manager;
private final CommandActor actor;
private int page = 1;
private int perPage;
private int totalPages;
private int totalResults;
private boolean lastPage;
public CommandHelpEntry(CommandManager manager, CommandActor actor) {
this.manager = manager;
this.actor = actor;
this.perPage = manager.defaultHelpPerPage();
}
public void showHelp() {
this.showHelp(this.actor);
}
public void showHelp(CommandActor actor) {
int min = this.perPage * (this.page - 1);
int max = min + this.perPage;
this.totalResults = this.manager.getCommands().size();
this.totalPages = this.totalResults / this.perPage;
if (min >= this.totalResults) {
actor.reply(ApiManager.getPluginConfig().getProperty(PluginConfig.INVALID_HELP_PAGE).replaceAll("\\{page}", String.valueOf(page)));
return;
}
Map<String, CommandDataEntry> entries = this.manager.getCommands();
for (int value = min; value < max; value++) {
if (this.totalResults - 1 < value) continue;
CommandEngine command = this.manager.getClasses().get(value);
CommandDataEntry dataEntry = entries.get(command.getLabel());
boolean isHidden = dataEntry.isHidden();
StringBuilder baseFormat = new StringBuilder("/" + command.getLabel());
String format = CrazyCore.api().commandPageFormat()
.replaceAll("\\{command}", baseFormat.toString())
.replaceAll("\\{description}", command.getDescription());
// Only add aliases if the list isn't empty.
if (!command.getAliases().isEmpty()) baseFormat.append(" ").append(command.getLabels().get(0));
ArrayList<Argument> arguments = new ArrayList<>();
arguments.addAll(command.getOptionalArgs());
arguments.addAll(command.getRequiredArgs());
arguments.sort(Comparator.comparingInt(Argument::order));
if (actor.isPlayer()) {
StringBuilder types = new StringBuilder();
ComponentBuilder builder = new ComponentBuilder();
for (Argument arg : arguments) {
String argValue = command.optionalArgs.contains(arg) ? " (" + arg.name() + ") " : " <" + arg.name() + ">";
types.append(argValue);
}
builder.setMessage(format.replaceAll("\\{args}", String.valueOf(types)));
String hoverShit = baseFormat.append(types).toString();
String hoverFormat = CrazyCore.api().commandHoverFormat();
builder.hover(PlaceholderSupport.setPlaceholders(hoverFormat).replaceAll("\\{commands}", hoverShit)).click(hoverShit, ClickEvent.Action.valueOf(CrazyCore.api().commandHoverAction().toUpperCase()));
actor.reply(builder.build());
}
String footer = CrazyCore.api().commandHelpFooter();
if (actor.isPlayer()) {
String text = CrazyCore.api().commandNavigationText();
if (page > 1) {
int number = page-1;
hover(actor.getPlayer(), footer.replaceAll("\\{page}", String.valueOf(page)), text.replaceAll("\\{page}", String.valueOf(number)), CrazyCore.api().commandNavigationBackButton(), "/crazycrates help " + number, ClickEvent.Action.RUN_COMMAND);
} else if (page < this.manager.getClasses().size()) {
int number = page+1;
hover(actor.getPlayer(), footer.replaceAll("\\{page}", String.valueOf(page)), text.replaceAll("\\{page}", String.valueOf(number)), CrazyCore.api().commandNavigationNextButton(), "/crazycrates help " + number, ClickEvent.Action.RUN_COMMAND);
}
} else {
send(actor.getSender(), footer.replaceAll("\\{page}", String.valueOf(page)), false, "");
}
}
this.lastPage = max >= this.totalResults;
}
public void setPage(int page) {
this.page = page;
}
public void setPerPage(int perPage) {
this.perPage = perPage;
}
public void setPage(int page, int perPage) {
this.setPage(page);
this.setPerPage(perPage);
}
public int getPage() {
return this.page;
}
public int getPerPage() {
return this.perPage;
}
public int getTotalResults() {
return this.totalResults;
}
public int getTotalPages() {
return this.totalPages;
}
public boolean isLastPage() {
return this.lastPage;
}
}

View File

@ -0,0 +1,7 @@
package com.badbones69.crazyauctions.api.frame.command.builders.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Hidden {}

View File

@ -0,0 +1,3 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args;
public record Argument(String name, int order, ArgumentType argumentType) {}

View File

@ -0,0 +1,9 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args;
import java.util.List;
public abstract class ArgumentType {
public abstract List<String> getPossibleValues();
}

View File

@ -0,0 +1,22 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public interface CommandArgs {
int getArgAsInt(int index, boolean notifySender);
long getArgAsLong(int index, boolean notifySender);
double getArgAsDouble(int index, boolean notifySender);
boolean getArgAsBoolean(int index, boolean notifySender);
float getArgAsFloat(int index, boolean notifySender);
Player getArgAsPlayer(int index, boolean notifySender);
OfflinePlayer getArgAsOfflinePlayer(int index);
}

View File

@ -0,0 +1,12 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args.builder;
import com.badbones69.crazyauctions.api.frame.command.builders.args.ArgumentType;
import java.util.List;
public class BooleanArgument extends ArgumentType {
@Override
public List<String> getPossibleValues() {
return List.of("true", "false");
}
}

View File

@ -0,0 +1,34 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args.builder;
import com.badbones69.crazyauctions.api.frame.command.builders.args.ArgumentType;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class DoubleArgument extends ArgumentType {
private final int numberCap;
public DoubleArgument(Integer numberCap) {
if (numberCap == null) {
this.numberCap = 100;
return;
}
this.numberCap = numberCap;
}
@Override
public List<String> getPossibleValues() {
List<String> numbers = new ArrayList<>();
DecimalFormat decimalFormat = new DecimalFormat("0.0");
for (double value = 0.1; value <= this.numberCap; value += 0.1) {
String formattedNumber = decimalFormat.format(value);
numbers.add(formattedNumber);
}
return numbers;
}
}

View File

@ -0,0 +1,34 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args.builder;
import com.badbones69.crazyauctions.api.frame.command.builders.args.ArgumentType;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class FloatArgument extends ArgumentType {
private final int numberCap;
public FloatArgument(Integer numberCap) {
if (numberCap == null) {
this.numberCap = 100;
return;
}
this.numberCap = numberCap;
}
@Override
public List<String> getPossibleValues() {
List<String> numbers = new ArrayList<>();
DecimalFormat decimalFormat = new DecimalFormat("0.0f");
for (float value = 0.1f; value <= this.numberCap; value += 0.1f) {
String formattedValue = decimalFormat.format(value);
numbers.add(formattedValue);
}
return numbers;
}
}

View File

@ -0,0 +1,28 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args.builder;
import com.badbones69.crazyauctions.api.frame.command.builders.args.ArgumentType;
import java.util.ArrayList;
import java.util.List;
public class IntArgument extends ArgumentType {
private final int numberCap;
public IntArgument(Integer numberCap) {
if (numberCap == null) {
this.numberCap = 100;
return;
}
this.numberCap = numberCap;
}
@Override
public List<String> getPossibleValues() {
List<String> numbers = new ArrayList<>();
for (int value = 1; value <= this.numberCap; value += 1) numbers.add(String.valueOf(value));
return numbers;
}
}

View File

@ -0,0 +1,15 @@
package com.badbones69.crazyauctions.api.frame.command.builders.args.builder.custom;
import com.badbones69.crazyauctions.api.frame.command.builders.args.ArgumentType;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.stream.Collectors;
public class PlayerArgument extends ArgumentType {
@Override
public List<String> getPossibleValues() {
return Bukkit.getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,94 @@
package com.badbones69.crazyauctions.api.frame.command.builders.other;
import com.badbones69.crazyauctions.frame.utils.AdventureUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import org.jetbrains.annotations.NotNull;
public class ComponentBuilder {
private String message;
private final TextComponent.@NotNull Builder builder = Component.text();
private final PreciseComponentBuilder preciseBuilder;
public ComponentBuilder() {
this.preciseBuilder = new PreciseComponentBuilder();
}
public void setMessage(String message) {
this.message = message;
}
public ComponentBuilder append(Component component) {
this.builder.append(component);
return this;
}
public Component parse(String value) {
return AdventureUtils.parse(value);
}
public ComponentBuilder hover(String hoverText) {
this.builder.hoverEvent(HoverEvent.showText(parse(hoverText)));
return this;
}
public ComponentBuilder click(String clickText, ClickEvent.Action action) {
this.builder.clickEvent(ClickEvent.clickEvent(action, clickText));
return this;
}
public class PreciseComponentBuilder {
private final TextComponent.@NotNull Builder preciseBuilder = Component.text();
public PreciseComponentBuilder text(String text) {
this.preciseBuilder.append(parse(text));
return this;
}
public PreciseComponentBuilder hoverText(String text, String hoverText) {
this.preciseBuilder.append(parse(text));
this.preciseBuilder.hoverEvent(HoverEvent.showText(parse(hoverText)));
return this;
}
public PreciseComponentBuilder hoverText(String hoverText) {
this.preciseBuilder.hoverEvent(HoverEvent.showText(parse(hoverText)));
return this;
}
public PreciseComponentBuilder click(String clickText, ClickEvent.Action action) {
this.preciseBuilder.clickEvent(ClickEvent.clickEvent(action, clickText));
return this;
}
public @NotNull TextComponent getPreciseBuilder() {
return this.preciseBuilder.build();
}
}
public PreciseComponentBuilder getPreciseComponent() {
return this.preciseBuilder;
}
public @NotNull TextComponent build() {
Component message = AdventureUtils.parse(this.message);
if (getPreciseComponent() != null) {
return this.builder.append(message).append(getPreciseComponent().getPreciseBuilder()).build();
}
return this.builder.append(message).build();
}
}

View File

@ -0,0 +1,57 @@
package com.badbones69.crazyauctions.api.frame.command.builders.reqs;
import com.badbones69.crazyauctions.api.frame.command.CommandContext;
import com.badbones69.crazyauctions.frame.CrazyCore;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.permissions.Permission;
public class CommandRequirements {
private final boolean asPlayer;
private Permission permission;
private String rawPermission;
public CommandRequirements(boolean asPlayer, Permission permission, String rawPermission) {
this.asPlayer = asPlayer;
if (permission != null) this.permission = permission;
if (!rawPermission.isEmpty() || !rawPermission.isBlank()) this.rawPermission = rawPermission;
}
public boolean checkRequirements(boolean notifySender, CommandContext context) {
if (asPlayer && !context.isPlayer()) {
if (notifySender) context.reply(CrazyCore.api().commandRequirementNotPlayer());
// The command is not valid.
return false;
}
// The sender is console sender so automatically valid.
if (context.getSender() instanceof ConsoleCommandSender) return true;
if (this.permission != null && !context.hasPermission(this.permission) || this.rawPermission != null && !context.hasPermission(this.rawPermission)) {
String value = this.permission != null ? this.permission.getName() : this.rawPermission;
if (notifySender) context.reply(CrazyCore.api().commandRequirementNoPermission().replaceAll("\\{permission}", value));
// The command is not valid.
return false;
}
// The command is valid.
return true;
}
public Permission getPermission() {
return this.permission;
}
public String getRawPermission() {
return this.rawPermission;
}
public boolean isPlayer() {
return this.asPlayer;
}
}

View File

@ -0,0 +1,33 @@
package com.badbones69.crazyauctions.api.frame.command.builders.reqs;
import org.bukkit.permissions.Permission;
public class CommandRequirementsBuilder {
private boolean asPlayer = false;
private Permission permission = null;
private String rawPermission = "";
public CommandRequirementsBuilder asPlayer(boolean value) {
this.asPlayer = value;
return this;
}
public CommandRequirementsBuilder withPermission(Permission permission) {
this.permission = permission;
return this;
}
public CommandRequirementsBuilder withOutPermission(Permission permission) {
return this;
}
public CommandRequirementsBuilder withRawPermission(String rawPermission) {
this.rawPermission = rawPermission;
return this;
}
public CommandRequirements build() {
return new CommandRequirements(asPlayer, permission, rawPermission);
}
}

View File

@ -0,0 +1,673 @@
package com.badbones69.crazyauctions.api.frame.items;
import com.badbones69.crazyauctions.api.frame.ItemUtils;
import com.badbones69.crazyauctions.frame.CrazyLogger;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Banner;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ArmorMeta;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.FireworkEffectMeta;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.inventory.meta.trim.ArmorTrim;
import org.bukkit.inventory.meta.trim.TrimMaterial;
import org.bukkit.inventory.meta.trim.TrimPattern;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import org.bukkit.util.Consumer;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
public class BaseItemBuilder<Base extends BaseItemBuilder<Base>> {
private final ItemUtils SKULL_CHECKER = new ItemUtils();
private final GsonComponentSerializer gson = GsonComponentSerializer.gson();
// Core.
private ItemStack itemStack;
private ItemMeta itemMeta;
private Material material;
// Custom Lore.
private Field LORE_FIELD;
// Custom Model Data.
private boolean isCustomModelData;
private int customModelData;
// Custom Heads.
private boolean isHead;
private Field profile;
private String texture;
// Potions
private boolean isPotion;
private boolean isTippedArrow;
private Color potionColor;
private PotionType potionType;
// Leather.
private boolean isLeather;
private boolean isArmor;
private TrimMaterial trimMaterial;
private TrimPattern trimPattern;
private Color armorColor;
// Banners.
private boolean isBanner;
private List<Pattern> patterns;
// Shields.
private boolean isShield;
// Firework.
private boolean isFirework;
private boolean isFireworkStar;
// Enchantments/Flags
private boolean isDurable;
private boolean hideFlags;
private boolean isGlowing;
protected BaseItemBuilder() {
this.itemStack = null;
this.itemMeta = null;
this.material = Material.AIR;
this.LORE_FIELD = null;
this.isCustomModelData = false;
this.customModelData = 0;
this.isHead = false;
this.profile = null;
this.texture = "";
this.isPotion = false;
this.isTippedArrow = false;
this.potionColor = Color.WHITE;
this.potionType = PotionType.MUNDANE;
this.isLeather = false;
this.armorColor = Color.WHITE;
this.isBanner = false;
this.patterns = Collections.emptyList();
this.isShield = false;
this.isFirework = false;
this.isFireworkStar = false;
this.isDurable = false;
this.hideFlags = false;
this.isGlowing = false;
}
protected BaseItemBuilder(ItemStack itemStack) {
this.itemStack = itemStack;
try {
Class<?> metaClass = SKULL_CHECKER.craftClass("inventory.CraftMetaItem");
LORE_FIELD = metaClass.getDeclaredField("lore");
LORE_FIELD.setAccessible(true);
} catch (NoSuchFieldException | ClassNotFoundException exception) {
CrazyLogger.warn("Failed to make the lore field accessible as it was not found. Perhaps an invalid item was supplied?");
}
this.material = itemStack.getType();
switch (this.material) {
case PLAYER_HEAD -> this.isHead = true;
case POTION, SPLASH_POTION -> this.isPotion = true;
case TIPPED_ARROW -> this.isTippedArrow = true;
case LEATHER_HELMET, LEATHER_CHESTPLATE, LEATHER_LEGGINGS, LEATHER_BOOTS, LEATHER_HORSE_ARMOR -> this.isLeather = true;
case SHIELD -> this.isShield = true;
case FIREWORK_ROCKET -> this.isFirework = true;
case FIREWORK_STAR -> this.isFireworkStar = true;
}
String name = this.material.name();
this.isArmor = name.endsWith("_HELMET") || name.endsWith("_CHESTPLATE") || name.endsWith("_LEGGINGS") || name.endsWith("_BOOTS");
// Accounts for all banners.
if (this.material.name().contains("BANNER")) this.isBanner = true;
// if (this.material.name().contains("SPAWN_EGG")) this.isEgg = true;
this.itemMeta = itemStack.hasItemMeta() ? itemStack.getItemMeta() : Bukkit.getServer().getItemFactory().getItemMeta(material);
}
public Base setDisplayName(Component displayName) {
this.itemMeta.displayName(displayName.decorationIfAbsent(TextDecoration.ITALIC, TextDecoration.State.FALSE));
return (Base) this;
}
public Base setLore(Component ... lore) {
return setLore(Arrays.asList(lore));
}
public Base setLore(List<Component> lore) {
List<String> jsonLore = lore.stream().filter(Objects::nonNull).map(this.gson::serialize).toList();
try {
LORE_FIELD.set(this.itemMeta, jsonLore);
} catch (IllegalAccessException exception) {
exception.printStackTrace();
}
return (Base) this;
}
public Base addLore(Consumer<List<Component>> lore) {
List<Component> components;
try {
List<String> jsonLore = (List<String>) LORE_FIELD.get(this.itemMeta);
components = (jsonLore == null) ? new ArrayList<>() : jsonLore.stream().map(this.gson::deserialize).collect(Collectors.toList());
} catch (Exception exception) {
components = new ArrayList<>();
exception.printStackTrace();
}
lore.accept(components);
return (Base) this;
}
public Base setAmount(int amount) {
this.itemStack.setAmount(amount);
return (Base) this;
}
public Base addEnchantment(Enchantment enchantment, int level, boolean ignoreLevelRestriction) {
this.itemMeta.addEnchant(enchantment, level, ignoreLevelRestriction);
return (Base) this;
}
public Base removeEnchantment(Enchantment enchantment) {
this.itemMeta.removeEnchant(enchantment);
return (Base) this;
}
public Base setEnchantments(HashMap<Enchantment, Integer> enchantments, boolean ignoreLevelRestriction) {
enchantments.forEach((enchantment, integer) -> this.itemMeta.addEnchant(enchantment, integer, ignoreLevelRestriction));
return (Base) this;
}
public Base addPatterns(List<String> patterns) {
patterns.forEach(this::addPatterns);
return (Base) this;
}
public Base addPattern(Pattern pattern) {
this.patterns.add(pattern);
return (Base) this;
}
public Base setPattern(List<Pattern> patterns) {
this.patterns = patterns;
return (Base) this;
}
public Base addItemFlags(List<String> flags) {
flags.forEach(flag -> {
try {
ItemFlag itemFlag = ItemFlag.valueOf(flag.toUpperCase());
addItemFlag(itemFlag);
} catch (Exception exception) {
CrazyLogger.warn("Failed to add item flag: " + flag + ". The flag is invalid!");
}
});
return (Base) this;
}
public Base setTexture(String texture) {
this.texture = texture;
return (Base) this;
}
public Base setValue(String material) {
if (material == null || material.isEmpty()) {
CrazyLogger.warn("Material cannot be null or empty, Output: " + material + ".");
CrazyLogger.warn("Please take a screenshot of this before asking for support.");
return (Base) this;
}
String metaData;
if (isPotion || isTippedArrow) {
if (material.contains(";")) {
String[] section = material.split(";");
String[] sectionOne = section[0].split(":");
String[] sectionTwo = section[1].split(":");
try {
this.potionType = PotionType.valueOf(sectionOne[1]);
} catch (Exception exception) {
CrazyLogger.warn("Failed to set potion type " + sectionOne[1] + ". The potion type inputted is invalid.");
}
this.potionColor = getColor(sectionTwo[1]);
}
return (Base) this;
}
if (material.contains(":")) { // Sets the durability or another value option.
String[] materialSplit = material.split(":");
material = materialSplit[0];
metaData = materialSplit[1];
if (metaData.contains("#")) { // <ID>:<Durability>#<CustomModelData>
String modelData = metaData.split("#")[1];
if (isValidInteger(modelData)) {
this.isCustomModelData = true;
this.customModelData = Integer.parseInt(modelData);
}
}
metaData = metaData.replace("#" + customModelData, "");
if (isValidInteger(metaData)) { // Value is durability.
int damage = Integer.parseInt(metaData);
if (this.itemMeta instanceof Damageable) ((Damageable) this.itemMeta).setDamage(damage);
} else { // Value is something else.
if (isPotion) {
this.potionType = PotionType.valueOf(metaData);
if (getColor(metaData) != null) this.potionColor = getColor(metaData);
}
if (isLeather) this.armorColor = getColor(metaData);
}
} else if (material.contains("#")) {
String[] materialSplit = material.split("#");
material = materialSplit[0];
if (isValidInteger(materialSplit[1])) { // Value is a number.
this.isCustomModelData = true;
this.customModelData = Integer.parseInt(materialSplit[1]);
}
}
Material matchedMaterial = Material.matchMaterial(material);
if (matchedMaterial != null) this.material = matchedMaterial;
if (this.isArmor) ((ArmorMeta) itemMeta).setTrim(new ArmorTrim(this.trimMaterial, this.trimPattern));
this.itemStack.setType(this.material);
setItemMeta(this.itemStack.getItemMeta());
return (Base) this;
}
public Base hideFlags(boolean hideFlags) {
this.hideFlags = hideFlags;
return (Base) this;
}
public Base setGlow(boolean isGlowing) {
this.isGlowing = isGlowing;
return (Base) this;
}
public Base setTrim(TrimMaterial trimMaterial, TrimPattern trimPattern) {
this.trimMaterial = trimMaterial;
this.trimPattern = trimPattern;
return (Base) this;
}
public Base setDurable(boolean isDurable) {
this.isDurable = isDurable;
return (Base) this;
}
public Base setEffect(FireworkEffect... effects) {
return setEffect(Arrays.asList(effects));
}
public Base setEffect(List<FireworkEffect> effects) {
if (effects.isEmpty()) return (Base) this;
if (this.isFireworkStar) {
FireworkEffectMeta effectMeta = (FireworkEffectMeta) this.getItemMeta();
effectMeta.setEffect(effects.get(0));
this.setItemMeta(effectMeta);
}
if (this.isFirework) {
FireworkMeta fireworkMeta = (FireworkMeta) this.getItemMeta();
fireworkMeta.addEffects(effects);
this.setItemMeta(fireworkMeta);
}
return (Base) this;
}
public Base setPower(int power) {
if (this.isFirework) {
FireworkMeta fireworkMeta = (FireworkMeta) this.getItemMeta();
fireworkMeta.setPower(power);
this.setItemMeta(fireworkMeta);
}
return (Base) this;
}
public ItemStack build() {
if (this.material != Material.AIR) {
if (this.isHead) {
// Set the field to accessible.
exposeField();
setPlayerTexture(this.texture);
}
if (this.isPotion || this.isTippedArrow && (this.potionType != null || this.potionColor != null)) {
PotionMeta potionMeta = (PotionMeta) this.itemMeta;
if (this.potionType != null) potionMeta.setBasePotionData(new PotionData(this.potionType));
if (this.potionColor != null) potionMeta.setColor(this.potionColor);
this.setItemMeta(potionMeta);
}
if (this.isLeather && this.armorColor != null) {
LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) this.itemMeta;
leatherArmorMeta.setColor(this.armorColor);
}
if (this.isBanner && !this.patterns.isEmpty()) {
BannerMeta bannerMeta = (BannerMeta) this.itemMeta;
bannerMeta.setPatterns(this.patterns);
}
if (this.isShield && !this.patterns.isEmpty()) {
BlockStateMeta shieldMeta = (BlockStateMeta) this.itemMeta;
Banner banner = (Banner) shieldMeta.getBlockState();
banner.setPatterns(this.patterns);
banner.update();
shieldMeta.setBlockState(banner);
}
if (this.isCustomModelData) this.itemMeta.setCustomModelData(this.customModelData);
if (this.hideFlags) this.itemMeta.addItemFlags(ItemFlag.values());
this.itemMeta.setUnbreakable(this.isDurable);
this.addGlow();
} else {
CrazyLogger.warn("Material cannot be AIR.");
}
this.itemStack.setItemMeta(this.itemMeta);
return this.itemStack;
}
private void addItemFlag(ItemFlag itemFlag) {
this.itemMeta.addItemFlags(itemFlag);
}
private void setPlayerTexture(String texture) {
this.texture = texture;
Player player = Bukkit.getServer().getPlayer(this.texture);
if (player != null) {
setOwner(player);
return;
}
if (this.texture.startsWith("http")) {
setTexture(convert(this.texture), UUID.randomUUID());
return;
}
setTexture(this.texture, UUID.randomUUID());
}
private void setOwner(OfflinePlayer player) {
if (this.SKULL_CHECKER.isPlayerSkull(this.material)) return;
SkullMeta skullMeta = (SkullMeta) this.getItemMeta();
skullMeta.setOwningPlayer(player);
this.setItemMeta(skullMeta);
}
private void addGlow() {
if (this.isGlowing) {
if (this.itemMeta.hasEnchants()) return;
this.itemMeta.addEnchant(Enchantment.LUCK, 1, false);
this.setItemMeta(this.itemMeta);
}
}
private void exposeField() {
if (this.SKULL_CHECKER.isPlayerSkull(this.material)) return;
Field field;
try {
SkullMeta skullMeta = (SkullMeta) this.SKULL_CHECKER.skull().getItemMeta();
field = skullMeta.getClass().getDeclaredField("profile");
field.setAccessible(true);
} catch (NoSuchFieldException exception) {
CrazyLogger.warn("Failed to make the meta field for profile accessible as it was not found. Perhaps an invalid item meta or field supplied?");
field = null;
}
this.profile = field;
}
private boolean isValidInteger(String value) {
try {
Integer.parseInt(value);
} catch (NumberFormatException exception) {
return false;
}
return true;
}
private Color getColor(String color) {
if (color != null) {
switch (color.toUpperCase()) {
case "AQUA" -> {
return Color.AQUA;
}
case "BLACK" -> {
return Color.BLACK;
}
case "BLUE" -> {
return Color.BLUE;
}
case "FUCHSIA" -> {
return Color.FUCHSIA;
}
case "GRAY" -> {
return Color.GRAY;
}
case "GREEN" -> {
return Color.GREEN;
}
case "LIME" -> {
return Color.LIME;
}
case "MAROON" -> {
return Color.MAROON;
}
case "NAVY" -> {
return Color.NAVY;
}
case "OLIVE" -> {
return Color.OLIVE;
}
case "ORANGE" -> {
return Color.ORANGE;
}
case "PURPLE" -> {
return Color.PURPLE;
}
case "RED" -> {
return Color.RED;
}
case "SILVER" -> {
return Color.SILVER;
}
case "TEAL" -> {
return Color.TEAL;
}
case "WHITE" -> {
return Color.WHITE;
}
case "YELLOW" -> {
return Color.YELLOW;
}
}
try {
String[] rgb = color.split(",");
return Color.fromRGB(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2]));
} catch (Exception ignore) {}
}
return null;
}
private void addPatterns(String stringPattern) {
try {
String[] split = stringPattern.split(":");
for (PatternType pattern : PatternType.values()) {
if (split[0].equalsIgnoreCase(pattern.name()) || split[0].equalsIgnoreCase(pattern.getIdentifier())) {
DyeColor color = getDyeColor(split[1]);
if (color != null) this.addPattern(new Pattern(color, pattern));
break;
}
}
} catch (Exception ignored) {}
}
public DyeColor getDyeColor(String color) {
if (color != null) {
try {
return DyeColor.valueOf(color.toUpperCase());
} catch (Exception exception) {
try {
String[] rgb = color.split(",");
return DyeColor.getByColor(Color.fromRGB(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])));
} catch (Exception ignore) {}
}
}
return null;
}
private void setTexture(String texture, UUID uuid) {
if (this.SKULL_CHECKER.isPlayerSkull(this.material)) return;
if (this.profile == null) return;
SkullMeta skullMeta = (SkullMeta) this.itemMeta;
GameProfile gameProfile = new GameProfile(uuid, null);
gameProfile.getProperties().put("textures", new Property("textures", texture));
try {
this.profile.set(skullMeta, gameProfile);
} catch (Exception exception) {
CrazyLogger.warn("Failed to set the meta & game profile. Perhaps an invalid texture?");
CrazyLogger.warn("Your Input: " + texture + ".");
}
setItemMeta(skullMeta);
}
private String convert(String url) {
URL actualLink;
try {
actualLink = new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
String encode = "{\"textures\":{\"SKIN\":{\"url\":\"" + actualLink + "\"}}}";
return Base64.getEncoder().encodeToString(encode.getBytes());
}
// Protected getters for extended builders.
protected ItemStack getItemStack() {
return this.itemStack;
}
protected void setItemStack(ItemStack itemStack) {
this.itemStack = itemStack;
}
protected ItemMeta getItemMeta() {
return this.itemMeta;
}
protected void setItemMeta(ItemMeta itemMeta) {
this.itemMeta = itemMeta;
}
}

View File

@ -0,0 +1,23 @@
package com.badbones69.crazyauctions.api.frame.items;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class ItemBuilder extends BaseItemBuilder<ItemBuilder> {
public ItemBuilder() {
super();
}
public ItemBuilder(ItemStack itemStack) {
super(itemStack);
}
public static ItemBuilder setStack(ItemStack itemStack) {
return new ItemBuilder(itemStack);
}
public static ItemBuilder setMaterial(Material material) {
return new ItemBuilder(new ItemStack(material));
}
}

View File

@ -0,0 +1,57 @@
package com.badbones69.crazyauctions.api.frame.items;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
public class ItemNbt {
private final JavaPlugin plugin;
public ItemNbt(JavaPlugin plugin) {
this.plugin = plugin;
}
public ItemStack setString(ItemStack itemStack, String key, String value) {
ItemMeta meta = itemStack.getItemMeta();
if (meta == null) return null;
meta.getPersistentDataContainer().set(new NamespacedKey(this.plugin, key), PersistentDataType.STRING, value);
itemStack.setItemMeta(meta);
return itemStack;
}
public String getString(ItemStack itemStack, String key) {
ItemMeta meta = itemStack.getItemMeta();
if (meta == null) return null;
return meta.getPersistentDataContainer().get(new NamespacedKey(this.plugin, key), PersistentDataType.STRING);
}
public ItemStack setBoolean(ItemStack itemStack, String key, boolean value) {
ItemMeta meta = itemStack.getItemMeta();
if (meta == null) return null;
meta.getPersistentDataContainer().set(new NamespacedKey(this.plugin, key), PersistentDataType.BOOLEAN, value);
itemStack.setItemMeta(meta);
return itemStack;
}
public ItemStack removeTag(ItemStack itemStack, String key) {
ItemMeta meta = itemStack.getItemMeta();
if (meta == null) return null;
meta.getPersistentDataContainer().remove(new NamespacedKey(this.plugin, key));
itemStack.setItemMeta(meta);
return itemStack;
}
}

View File

@ -0,0 +1,28 @@
package com.badbones69.crazyauctions.api.manager.enums;
/**
* Description: Defines the auction type to use
*/
public enum AuctionType {
BID("Bid"),
SELL("Sell");
private final String name;
AuctionType(String name) {
this.name = name;
}
public static AuctionType getTypeFromName(String name) {
for (AuctionType type : AuctionType.values()) {
if (type.getName().equalsIgnoreCase(name)) return type;
}
return null;
}
public String getName() {
return this.name;
}
}

View File

@ -0,0 +1,25 @@
package com.badbones69.crazyauctions.api.manager.interfaces;
import com.badbones69.crazyauctions.api.manager.enums.AuctionType;
import org.bukkit.inventory.ItemStack;
import java.util.UUID;
public interface AuctionItem {
UUID auctionID = UUID.randomUUID();
default UUID getAuctionID() {
return auctionID;
}
AuctionType getAuctionType();
UUID getSeller();
long getPrice();
long getExpireTime();
ItemStack getSellingItem();
}

View File

@ -0,0 +1,88 @@
package com.badbones69.crazyauctions.api.manager.objects;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.plugin.java.JavaPlugin;
public class AuctionButtons {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
/*
private final ItemBuilder sellingItemsButton;
private final ItemBuilder sellingInfoButton;
private final ItemBuilder biddingInfoButton;
private final ItemBuilder currentListingsInfoButton;
private final ItemBuilder expiredItemsButton;
private final ItemBuilder expiredInfoButton;
private final ItemBuilder categoriesButton;
private final ItemBuilder categoriesInfoButton;
private final ItemBuilder nextPageButton;
private final ItemBuilder refreshPageButton;
private final ItemBuilder backPageButton;
private final ItemBuilder switchModeButton;
public AuctionButtons(FileConfiguration file) {
String path = "auction-house.settings.buttons.";
sellingItemsButton = ItemUtils.convertString(file.getString(path + "selling-items"));
sellingInfoButton = ItemUtils.convertString(file.getString(path + "info.selling-items"));
biddingInfoButton = ItemUtils.convertString(file.getString(path + "info.bidding"));
currentListingsInfoButton = ItemUtils.convertString(file.getString(path + "info.current-listings"));
expiredItemsButton = ItemUtils.convertString(file.getString(path + "expired-items"));
expiredInfoButton = ItemUtils.convertString(file.getString(path + "info.expired-items"));
categoriesButton = ItemUtils.convertString(file.getString(path + "categories"));
categoriesInfoButton = ItemUtils.convertString(file.getString(path + "info.categories"));
nextPageButton = ItemUtils.convertString(file.getString(path + "next-page"));
refreshPageButton = ItemUtils.convertString(file.getString(path + "refresh-page"));
backPageButton = ItemUtils.convertString(file.getString(path + "back-page"));
switchModeButton = ItemUtils.convertString(file.getString(path + "switch-mode"));
}
public ItemBuilder getSellingItemsButton() {
return sellingItemsButton;
}
public ItemBuilder getSellingInfoButton() {
return sellingInfoButton;
}
public ItemBuilder getBiddingInfoButton() {
return biddingInfoButton;
}
public ItemBuilder getCurrentListingsInfoButton() {
return currentListingsInfoButton;
}
public ItemBuilder getExpiredItemsButton() {
return expiredItemsButton;
}
public ItemBuilder getExpiredInfoButton() {
return expiredInfoButton;
}
public ItemBuilder getCategoriesButton() {
return categoriesButton;
}
public ItemBuilder getCategoriesInfoButton() {
return categoriesInfoButton;
}
public ItemBuilder getNextPageButton() {
return nextPageButton;
}
public ItemBuilder getRefreshPageButton() {
return refreshPageButton;
}
public ItemBuilder getBackPageButton() {
return backPageButton;
}
public ItemBuilder getSwitchModeButton() {
return switchModeButton;
}*/
}

View File

@ -0,0 +1,44 @@
package com.badbones69.crazyauctions.api.manager.objects;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.frame.items.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
/**
* Description: Creates the auction categories
*/
public class AuctionCategory {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private String name;
private int slot;
//private ItemBuilder displayItem;
private List<Material> categoryItemList;
//TODO make it so each AH can have their own categories and the default ones should be able to be disabled.
public AuctionCategory(String name, int slot, ItemBuilder displayItem, List<Material> categoryItemList) {
this.name = name;
this.slot = slot;
//this.displayItem = displayItem;
this.categoryItemList = categoryItemList;
}
public String getName() {
return name;
}
public int getSlot() {
return slot;
}
//public ItemBuilder getDisplayItem() {
// return displayItem;
//}
public List<Material> getCategoryItemList() {
return categoryItemList;
}
}

View File

@ -0,0 +1,91 @@
package com.badbones69.crazyauctions.api.manager.objects;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.manager.enums.AuctionType;
import com.badbones69.crazyauctions.api.manager.interfaces.AuctionItem;
import com.badbones69.crazyauctions.api.manager.objects.auctiontype.BiddingAuction;
import com.badbones69.crazyauctions.api.manager.objects.auctiontype.SellingAuction;
import com.badbones69.crazyauctions.api.events.AuctionAddEvent;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Description: Creates the main auction house menu
*/
public class AuctionHouse {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private String name;
private FileConfiguration auctionFile;
private InventorySettings inventorySettings;
private List<AuctionItem> auctionItems = new ArrayList<>();
private List<AuctionCategory> auctionCategories = new ArrayList<>();
public AuctionHouse(FileConfiguration file) {
this.name = file.getString("auction-house.settings.name");
this.auctionFile = file;
this.inventorySettings = new InventorySettings(file);
//Loads the auction house listings into the auction house.
//TODO this needs to be moved to a seperated data file that doesnt hold all the auction house settings.
for (String auctionID : file.getConfigurationSection("auction-house.item-on-auction").getKeys(false)) {
String path = "auction-house.item-on-auction" + auctionID + ".";
AuctionType auctionType = AuctionType.getTypeFromName(file.getString(path + "auction-type"));
if (auctionType == AuctionType.SELL) {
auctionItems.add(new SellingAuction(
UUID.fromString(file.getString(path + "seller-uuid")),
file.getLong(path + "price"),
file.getLong(path + "expire-time"),
file.getItemStack(path + "selling-item")));
} else {
auctionItems.add(new BiddingAuction(
UUID.fromString(file.getString(path + "seller-uuid")),
UUID.fromString(file.getString(path + "highest-bidder-uuid")),
file.getLong(path + "price"),
file.getLong(path + "current-bid"),
file.getLong(path + "expire-time"),
file.getItemStack(path + "selling-item")));
}
}
//Loads the category items into the auction house.
//TODO Need to add the default categories like isPotion, isArmor, isFood, Ect...
//for (String category : file.getConfigurationSection("auction-house.categories").getKeys(false)) {
// String path = "auction-house.categories." + category + ".";
// auctionCategories.add(new AuctionCategory(
// category,
// file.getInt(path + "slot"),
//ItemUtils.convertString(file.getString(path + "item")),
//file.getStringList(path + "items").stream().map(Material :: matchMaterial).collect(Collectors.toList())));
//}
}
public String getName() {
return name;
}
public FileConfiguration getAuctionFile() {
return auctionFile;
}
public InventorySettings getInventorySettings() {
return inventorySettings;
}
public List<AuctionItem> getAuctionItems() {
return auctionItems;
}
public long getAuctionCount(AuctionType auctionType) {
return auctionItems.stream().filter(auctionItem -> auctionType == auctionItem.getAuctionType()).count();
}
public void addAuctionItem(AuctionItem auctionItem) {
auctionItems.add(auctionItem);
AuctionAddEvent event = new AuctionAddEvent(auctionItem.getSeller(), this, auctionItem);
Bukkit.getServer().getPluginManager().callEvent(event);
}
}

View File

@ -0,0 +1,30 @@
package com.badbones69.crazyauctions.api.manager.objects;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Description: Creates the auction house inventory settings
*/
public class InventorySettings {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final String title;
private final AuctionButtons auctionButtons = null;
public InventorySettings(FileConfiguration file) {
String path = "auction-house.settings.";
this.title = file.getString(path + "inventory-title");
//this.auctionButtons = new AuctionButtons(file);
}
public String getTitle() {
return title;
}
public AuctionButtons getAuctionButtons() {
return auctionButtons;
}
}

View File

@ -0,0 +1,74 @@
package com.badbones69.crazyauctions.api.manager.objects.auctiontype;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.manager.enums.AuctionType;
import com.badbones69.crazyauctions.api.manager.interfaces.AuctionItem;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
/**
* Description: Creates the bidding auction type
*/
public class BiddingAuction implements AuctionItem {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
AuctionType auctionType = AuctionType.BID;
UUID seller;
UUID highestBidder;
long price;
long currentBid;
long expireTime;
ItemStack sellingItem;
public BiddingAuction(UUID seller, UUID highestBidder, long price, long currentBid, long expireTime, ItemStack sellingItem) {
this.seller = seller;
this.highestBidder = highestBidder;
this.price = price;
this.currentBid = 0;
this.expireTime = expireTime;
this.sellingItem = sellingItem;
}
@Override
public AuctionType getAuctionType() {
return auctionType;
}
@Override
public UUID getSeller() {
return seller;
}
public UUID getHighestBidder() {
return highestBidder;
}
public void setHighestBidder(UUID highestBidder) {
this.highestBidder = highestBidder;
}
@Override
public long getPrice() {
return price;
}
public long getCurrentBid() {
return currentBid;
}
public void setCurrentBid(long currentBid) {
this.currentBid = currentBid;
}
@Override
public long getExpireTime() {
return expireTime;
}
@Override
public ItemStack getSellingItem() {
return sellingItem;
}
}

View File

@ -0,0 +1,54 @@
package com.badbones69.crazyauctions.api.manager.objects.auctiontype;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.manager.enums.AuctionType;
import com.badbones69.crazyauctions.api.manager.interfaces.AuctionItem;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
/**
* Description: Creates the selling auction type
*/
public class SellingAuction implements AuctionItem {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
AuctionType auctionType = AuctionType.SELL;
UUID seller;
long price;
long expireTime;
ItemStack sellingItem;
public SellingAuction(UUID seller, long price, long expireTime, ItemStack sellingItem) {
this.seller = seller;
this.price = price;
this.expireTime = expireTime;
this.sellingItem = sellingItem;
}
@Override
public AuctionType getAuctionType() {
return auctionType;
}
@Override
public UUID getSeller() {
return seller;
}
@Override
public long getPrice() {
return price;
}
@Override
public long getExpireTime() {
return expireTime;
}
@Override
public ItemStack getSellingItem() {
return sellingItem;
}
}

View File

@ -0,0 +1,21 @@
package com.badbones69.crazyauctions.commands;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.frame.command.CommandContext;
import com.badbones69.crazyauctions.api.frame.command.CommandEngine;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Collections;
public class AuctionCommand extends CommandEngine {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
protected AuctionCommand() {
super("auctions", "Opens the auction house", "/crazyauctions:auctions", Collections.emptyList());
}
@Override
protected void perform(CommandContext context, String[] args) {
}
}

View File

@ -0,0 +1,23 @@
package com.badbones69.crazyauctions.commands.admin;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.api.CrazyManager;
import com.badbones69.crazyauctions.api.frame.command.CommandContext;
import com.badbones69.crazyauctions.api.frame.command.CommandEngine;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Collections;
public class CommandReload extends CommandEngine {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final CrazyManager crazyManager = this.plugin.getCrazyManager();
public CommandReload() {
super("reload", "Reloads the plugin.", "/crazyauctions:reload", Collections.emptyList());
}
@Override
protected void perform(CommandContext context, String[] args) {
this.crazyManager.reload();
}
}

View File

@ -0,0 +1,23 @@
package com.badbones69.crazyauctions.commands.inventories;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
public class AuctionInventory implements InventoryHolder {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final Inventory inventory;
public AuctionInventory() {
this.inventory = plugin.getServer().createInventory(this, 9);
}
@Override
public @NotNull Inventory getInventory() {
return this.inventory;
}
}

View File

@ -0,0 +1,35 @@
package com.badbones69.crazyauctions.commands.inventories;
import com.badbones69.crazyauctions.api.frame.items.ItemBuilder;
import com.badbones69.crazyauctions.frame.utils.AdventureUtils;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class AuctionInventoryClick implements Listener {
@EventHandler
public void onAuctionClick(InventoryClickEvent event) {
Inventory inventory = event.getClickedInventory();
if (inventory == null || (!(inventory.getHolder() instanceof AuctionInventory auctionInventory))) return;
event.setCancelled(true);
ItemStack clicked = event.getCurrentItem();
if (clicked != null) {
event.getWhoClicked().sendMessage("Beep Boo Boo Beep!");
ItemBuilder builder = ItemBuilder.setStack(new ItemStack(Material.DIAMOND_SWORD));
builder.setAmount(3);
builder.setDisplayName(AdventureUtils.parse("<red>This is a test</red>"));
auctionInventory.getInventory().addItem(builder.build());
}
}
}

View File

@ -0,0 +1,27 @@
package com.badbones69.crazyauctions.events;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.storage.interfaces.UserManager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class DataListener implements Listener {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final UserManager userManager = this.plugin.getCrazyManager().getStorageManager().getUserManager();
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
this.userManager.load(event.getPlayer().getUniqueId());
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) {
this.userManager.saveSingular(event.getPlayer().getUniqueId(), true);
}
}

View File

@ -0,0 +1,28 @@
package com.badbones69.crazyauctions.storage.interfaces;
import com.badbones69.crazyauctions.frame.storage.enums.StorageType;
import com.badbones69.crazyauctions.storage.objects.UserData;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;
public interface UserManager {
void load(UUID uuid);
void saveSingular(UUID uuid, boolean serverExit);
void save(boolean serverExit);
void convert(File file, UUID uuid, StorageType storageType);
void addAuction(UUID uuid);
File getFile(Path path, UUID uuid);
UserData getUser(UUID uuid);
Map<UUID, UserData> getUsers();
}

View File

@ -0,0 +1,24 @@
package com.badbones69.crazyauctions.storage.objects;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class UserData {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final UUID uuid;
private ConcurrentHashMap<String, String> auctionData = new ConcurrentHashMap<>();
public UserData(UUID uuid) {
this.uuid = uuid;
}
public Player getPlayer() {
return this.plugin.getServer().getPlayer(this.uuid);
}
}

View File

@ -0,0 +1,17 @@
package com.badbones69.crazyauctions.storage.types;
import com.badbones69.crazyauctions.storage.interfaces.UserManager;
import com.badbones69.crazyauctions.storage.types.file.yaml.YamlUserManager;
public class StorageManager {
private UserManager userManager;
public void init() {
this.userManager = new YamlUserManager();
}
public UserManager getUserManager() {
return this.userManager;
}
}

View File

@ -0,0 +1,110 @@
package com.badbones69.crazyauctions.storage.types.file.yaml;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.frame.storage.enums.StorageType;
import com.badbones69.crazyauctions.storage.interfaces.UserManager;
import com.badbones69.crazyauctions.storage.objects.UserData;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class YamlUserManager extends YamlConfiguration implements UserManager {
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
private final ConcurrentHashMap<UUID, UserData> userData = new ConcurrentHashMap<>();
public YamlUserManager() {
}
@Override
public void load(UUID uuid) {
try {
File file = new File(this.plugin.getDataFolder() + "/users/" + uuid + ".yml");
if (!file.exists()) file.createNewFile();
load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
@Override
public void saveSingular(UUID uuid, boolean serverExit) {
// If user data empty return.
if (this.userData.isEmpty()) return;
// Check if user data contains keys.
if (this.userData.containsKey(uuid)) {
// Remove user when done.
this.userData.remove(uuid);
// Save the file then load the changes back in.
reload(uuid, serverExit);
}
}
private void reload(UUID uuid, boolean serverExit) {
try {
File file = new File(this.plugin.getDataFolder() + "/users/" + uuid + ".yml");
save(file);
if (!serverExit) load(uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void save(boolean serverExit) {
// If user data empty return.
if (this.userData.isEmpty()) return;
// If the player is not leaving, continue here as we are stopping the server or doing periodic save.
this.userData.forEach((id, user) -> {
//user.getKeys().forEach((crateMap, keys) -> set("users." + id + "." + crateMap, keys));
// Save the file then load the changes back in.
reload(id, serverExit);
});
}
@Override
public void convert(File file, UUID uuid, StorageType storageType) {
}
@Override
public void addAuction(UUID uuid) {
Player player = this.plugin.getServer().getPlayer(uuid);
}
@Override
public File getFile(Path path, UUID uuid) {
return new File(this.plugin.getDataFolder() + "/users/" + uuid + ".yml");
}
@Override
public UserData getUser(UUID uuid) {
Player player = this.plugin.getServer().getPlayer(uuid);
// Return with their user data.
return this.userData.get(uuid);
}
@Override
public Map<UUID, UserData> getUsers() {
return Collections.unmodifiableMap(this.userData);
}
}

View File

@ -0,0 +1,17 @@
package com.badbones69.crazyauctions.support;
import com.badbones69.crazyauctions.ApiManager;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.config.types.PluginConfig;
import org.bukkit.plugin.java.JavaPlugin;
public class PlaceholderSupport {
private static final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
public static String setPlaceholders(String placeholder) {
placeholder = placeholder.replaceAll("\\{prefix}", ApiManager.getPluginConfig().getProperty(PluginConfig.COMMAND_PREFIX));
return placeholder;
}
}

View File

@ -0,0 +1,51 @@
package com.badbones69.crazyauctions.support.economy;
/**
* Description: This event is fired when an item is added to an auction house.
*/
public enum Currency {
VAULT("Vault"),
XP_LEVEL("XP_Level"),
XP_TOTAL("XP_Total");
private final String name;
Currency(String name) {
this.name = name;
}
/**
* Checks if it is a compatible currency.
* @param currency The currency name you are checking.
* @return True if it is supported and false if not.
*/
public static boolean isCurrency(String currency) {
for (Currency value : Currency.values()) {
if (currency.equalsIgnoreCase(value.getName())) return true;
}
return false;
}
/**
* Get a currency enum.
* @param currency The currency you want.
* @return The currency enum.
*/
public static Currency getCurrency(String currency) {
for (Currency value : Currency.values()) {
if (currency.equalsIgnoreCase(value.getName())) return value;
}
return null;
}
/**
* Get the name of the currency.
* @return The name of the currency.
*/
public String getName() {
return name;
}
}

View File

@ -0,0 +1,131 @@
package com.badbones69.crazyauctions.support.economy;
import com.badbones69.crazyauctions.CrazyAuctions;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
/**
* Description: Defines what currency to use.
*/
public class CurrencyAPI {
// TODO() Add item support as a currency.
private final CrazyAuctions plugin = JavaPlugin.getPlugin(CrazyAuctions.class);
/**
* Get the amount that a player has from a specific currency.
*
* @param uuid - The uuid of the player.
* @param currency - The currency you wish to get from.
* @return amount that the player has of that currency.
*/
public int getCurrency(UUID uuid, Currency currency) {
try {
OfflinePlayer offlinePlayer = plugin.getServer().getOfflinePlayer(uuid);
Player player = plugin.getServer().getPlayer(uuid);
switch (currency) {
case VAULT: //if (player != null) return (int) plugin.getVaultSupport().getVault().getBalance(player);
case XP_LEVEL: if (player != null) return player.getLevel();
case XP_TOTAL: if (player != null) return getTotalExperience(player);
}
} catch (Exception | NoClassDefFoundError ignored) {}
return 0;
}
/**
* Take an amount from a player's currency.
*
* @param uuid - The uuid of the player.
* @param currency - The currency you wish to use.
* @param amount - The amount you want to take.
*/
public void takeCurrency(UUID uuid, Currency currency, int amount) {
try {
Player player = plugin.getServer().getPlayer(uuid);
switch (currency) {
//case VAULT: if (player != null) plugin.getVaultSupport().getVault().withdrawPlayer(player, amount);
case XP_LEVEL: if (player != null) player.setLevel(player.getLevel() - amount);
case XP_TOTAL: if (player != null) takeTotalExperience(player, amount);
}
} catch (Exception | NoClassDefFoundError ignored) {}
}
/**
* Give an amount to a player's currency.
*
* @param uuid - The uuid of the player.
* @param currency - The currency you want to use.
* @param amount - The amount you are giving to the player.
*/
public void giveCurrency(UUID uuid, Currency currency, int amount) {
try {
Player player = plugin.getServer().getPlayer(uuid);
switch (currency) {
//case VAULT: if (player != null) plugin.getVaultSupport().getVault().depositPlayer(player, amount);
case XP_LEVEL: if (player != null) player.setLevel(player.getLevel() + amount);
case XP_TOTAL: if (player != null) takeTotalExperience(player, -amount);
}
} catch (Exception | NoClassDefFoundError ignored) {}
}
/**
* Checks if the player has enough of a currency.
*
* @param uuid - The uuid of the player.
* @param currency The currency you wish to check.
* @param cost The cost of the item you are checking.
* @return true if they have enough to buy it or false if they don't.
*/
public boolean canBuy(UUID uuid, Currency currency, int cost) {
return getCurrency(uuid, currency) >= cost;
}
private void takeTotalExperience(Player player, int amount) {
int total = getTotalExperience(player) - amount;
player.setTotalExperience(0);
player.setTotalExperience(total);
player.setLevel(0);
player.setExp(0);
while (total > player.getExpToLevel()) {
total -= player.getExpToLevel();
player.setLevel(player.getLevel() + 1);
}
float xp = (float) total / (float) player.getExpToLevel();
player.setExp(xp);
}
private int getTotalExperience(Player player) { // https://www.spigotmc.org/threads/72804
int experience;
int level = player.getLevel();
if (level >= 0 && level <= 15) {
experience = (int) Math.ceil(Math.pow(level, 2) + (6 * level));
int requiredExperience = 2 * level + 7;
double currentExp = Double.parseDouble(Float.toString(player.getExp()));
experience += Math.ceil(currentExp * requiredExperience);
return experience;
} else if (level > 15 && level <= 30) {
experience = (int) Math.ceil((2.5 * Math.pow(level, 2) - (40.5 * level) + 360));
int requiredExperience = 5 * level - 38;
double currentExp = Double.parseDouble(Float.toString(player.getExp()));
experience += Math.ceil(currentExp * requiredExperience);
return experience;
} else {
experience = (int) Math.ceil((4.5 * Math.pow(level, 2) - (162.5 * level) + 2220));
int requiredExperience = 9 * level - 158;
double currentExp = Double.parseDouble(Float.toString(player.getExp()));
experience += Math.ceil(currentExp * requiredExperience);
return experience;
}
}
}

Some files were not shown because too many files have changed in this diff Show More