From f6182d3b3e97a04a2bab20b175529f842b358dc6 Mon Sep 17 00:00:00 2001 From: Ryder Belserion Date: Mon, 21 Aug 2023 14:06:07 -0400 Subject: [PATCH] add actual v1 code --- .gitignore | 17 +- README.md | 120 +- build.gradle.kts | 80 -- gradle/libs.versions.toml | 30 - gradle/wrapper/gradle-wrapper.properties | 5 - pom.xml | 116 ++ settings.gradle.kts | 3 - .../crazyauctions/CrazyAuctions.java | 72 - .../com/badbones69/crazyauctions/Main.java | 479 +++++++ .../com/badbones69/crazyauctions/Methods.java | 436 +++++- .../com/badbones69/crazyauctions/Starter.java | 50 - .../AuctionCategories.java => Category.java} | 208 ++- .../{CrazyManager.java => CrazyAuctions.java} | 36 +- .../crazyauctions/api/FileManager.java | 307 ++-- .../api/{enums => }/Messages.java | 79 +- .../crazyauctions/api/ShopType.java | 36 + .../badbones69/crazyauctions/api/Version.java | 128 ++ .../crazyauctions/api/economy/Currency.java | 48 - .../api/economy/CurrencyAPI.java | 158 --- .../api/economy/vault/VaultSupport.java | 25 - .../api/enums/CancelledReason.java | 1 + .../api/enums/ShopCategories.java | 92 -- .../api/events/AuctionBuyEvent.java | 18 +- .../api/events/AuctionCancelledEvent.java | 17 +- .../api/events/AuctionExpireEvent.java | 15 +- .../api/events/AuctionListEvent.java | 24 +- .../api/events/AuctionNewBidEvent.java | 15 +- .../api/events/AuctionWinBidEvent.java | 16 +- .../crazyauctions/controllers/DupePatch.java | 22 + .../crazyauctions/controllers/GUI.java | 950 +++++++++++++ .../currency/CurrencyManager.java | 119 ++ .../crazyauctions/currency/Vault.java | 57 + .../crazyauctions/utils/ItemBuilder.java | 1261 ----------------- .../crazyauctions/utils/SkullCreator.java | 275 ---- .../utils/func/PluginSupport.java | 27 - .../utils/func/ServerProtocol.java | 120 -- src/main/resources/config1.12.2-Down.yml | 306 ++++ .../{config.yml => config1.13-Up.yml} | 2 + src/main/resources/plugin.yml | 26 +- 39 files changed, 3039 insertions(+), 2757 deletions(-) delete mode 100644 build.gradle.kts delete mode 100644 gradle/libs.versions.toml delete mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 pom.xml delete mode 100644 settings.gradle.kts delete mode 100644 src/main/java/com/badbones69/crazyauctions/CrazyAuctions.java create mode 100644 src/main/java/com/badbones69/crazyauctions/Main.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/Starter.java rename src/main/java/com/badbones69/crazyauctions/api/{enums/AuctionCategories.java => Category.java} (51%) rename src/main/java/com/badbones69/crazyauctions/api/{CrazyManager.java => CrazyAuctions.java} (69%) rename src/main/java/com/badbones69/crazyauctions/api/{enums => }/Messages.java (77%) create mode 100644 src/main/java/com/badbones69/crazyauctions/api/ShopType.java create mode 100644 src/main/java/com/badbones69/crazyauctions/api/Version.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/api/economy/Currency.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/api/economy/CurrencyAPI.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/api/economy/vault/VaultSupport.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/api/enums/ShopCategories.java create mode 100644 src/main/java/com/badbones69/crazyauctions/controllers/DupePatch.java create mode 100644 src/main/java/com/badbones69/crazyauctions/controllers/GUI.java create mode 100644 src/main/java/com/badbones69/crazyauctions/currency/CurrencyManager.java create mode 100644 src/main/java/com/badbones69/crazyauctions/currency/Vault.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/utils/ItemBuilder.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/utils/SkullCreator.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/utils/func/PluginSupport.java delete mode 100644 src/main/java/com/badbones69/crazyauctions/utils/func/ServerProtocol.java create mode 100644 src/main/resources/config1.12.2-Down.yml rename src/main/resources/{config.yml => config1.13-Up.yml} (99%) diff --git a/.gitignore b/.gitignore index ce181e5..72db3d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,14 @@ -.idea -.gradle -build \ No newline at end of file + +\.idea/ + +*.iml + +*.class + +target/classes/ + +target/ + +\.DS_Store + +dependency-reduced-pom.xml diff --git a/README.md b/README.md index dd15306..07ed220 100644 --- a/README.md +++ b/README.md @@ -1,111 +1,41 @@ -
+## Crazy Auctions -[![CrazyAuctions](https://raw.githubusercontent.com/RyderBelserion/Assets/main/crazycrew/banners/CrazyAuctions.png)](https://www.spigotmc.org/resources/crazy-crates.17599/) +[![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'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) -[![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] +CrazyAuctions is a simple auctions plugin where you can sell your items and bid on other items! - - - +## 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) -

- A simple auctions plugin where you can sell your items and bid on other items! -
- Explore the docs » -
-
- Report Bug - · - Request Feature - · - Get Support -

-
- - -
- Table of Contents -
    -
  1. - Getting Started - -
  2. -
  3. Roadmap
  4. -
  5. Contributing
  6. -
  7. License
  8. -
  9. Contact
  10. -
-
+Join us on [Discord](https://discord.badbones69.com) ## Downloads -#### Stable Builds -https://modrinth.com/plugin/crazyauctions ( Soon ) +[![Build Status](https://jenkins.badbones69.com/view/Stable/job/Crazy-Auctions/badge/icon)](https://jenkins.badbones69.com/view/Stable/job/Crazy-Auctions/) -#### Beta Builds -https://ci.badbones69.com/view/Beta/job/CrazyAuctions-Beta/ +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/). -## Getting Started +## Plugin Data +[![bStats Graph Data](https://bstats.org/signatures/bukkit/CrazyAuctions.svg)](https://bstats.org/plugin/bukkit/CrazyAuctions/4624) -How to get started with contributing / maintaining your own version of CrazyAuctions! +## API +In Progress. -### Prerequisites +### Dependency Information -A list of things necessary to make sure you can build CrazyAuctions properly. -* Intellij IDEA - * https://www.jetbrains.com/idea/download/ -* Gradle +#### Maven +In Progress. -### Installation +#### Gradle +In Progress. -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 shadowJar task. - ```gradle - ./gradlew shadowJar or gradle shadowJar - ``` +## Working with CrazyAuctions. -## Roadmap +#### Contributing +Fork the project & open a pull request. -Check our public [trello board](https://trello.com/b/bzQ5TwXo) 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 - -## License - -Distributed under the MIT License. See [`LICENSE`](/LICENSE) for more information. - -[discord-shield]: https://img.shields.io/discord/182615261403283459.svg?style=for-the-badge -[discord-url]: https://discord.gg/crazycrew - -[contributors-shield]: https://img.shields.io/github/contributors/Crazy-Crew/CrazyAuctions.svg?style=for-the-badge -[contributors-url]: https://github.com/Crazy-Crew/CrazyAuctions/graphs/contributors -[forks-shield]: https://img.shields.io/github/forks/Crazy-Crew/CrazyAuctions.svg?style=for-the-badge -[forks-url]: https://github.com/Crazy-Crew/CrazyAuctions/network/members -[stars-shield]: https://img.shields.io/github/stars/Crazy-Crew/CrazyAuctions.svg?style=for-the-badge -[stars-url]: https://github.com/Crazy-Crew/CrazyAuctions/stargazers -[issues-shield]: https://img.shields.io/github/issues/Crazy-Crew/CrazyAuctions.svg?style=for-the-badge -[issues-url]: https://github.com/Crazy-Crew/CrazyAuctions/issues -[license-shield]: https://img.shields.io/github/license/Crazy-Crew/CrazyAuctions.svg?style=for-the-badge -[license-url]: https://github.com/Crazy-Crew/CrazyAuctions/blob/master/LICENSE.MD - -[codefactor-shield]: https://img.shields.io/codefactor/grade/github/crazy-crew/CrazyAuctions/main?style=for-the-badge \ No newline at end of file +#### Compiling +Clone the project & run the install task. diff --git a/build.gradle.kts b/build.gradle.kts deleted file mode 100644 index 454b621..0000000 --- a/build.gradle.kts +++ /dev/null @@ -1,80 +0,0 @@ -plugins { - java - - id("com.github.johnrengelman.shadow") version "7.1.2" -} - -val buildNumber: String? = System.getenv("BUILD_NUMBER") - -val jenkinsVersion = "1.2.18-b$buildNumber" - -group = "com.badbones69.crazyauctions" -version = "1.2.18" -description = "A simple auctions plugin where you can sell your items and bid on other items! " - -repositories { - /** - * Paper Team - */ - maven("https://repo.papermc.io/repository/maven-public/") - - /** - * NBT Team - */ - maven("https://repo.codemc.org/repository/maven-public/") - - /** - * Everything else we need. - */ - maven("https://jitpack.io/") - - mavenCentral() -} - -dependencies { - implementation(libs.bukkit.bstats) - - implementation(libs.nbt.api) - - compileOnly(libs.reserve.api) - - compileOnly(libs.vault.api) - - compileOnly(libs.paper) -} - -java { - toolchain.languageVersion.set(JavaLanguageVersion.of(17)) -} - -tasks { - shadowJar { - if (buildNumber != null) { - archiveFileName.set("${rootProject.name}-[v${jenkinsVersion}].jar") - } else { - archiveFileName.set("${rootProject.name}-[v${rootProject.version}].jar") - } - - listOf( - "de.tr7zw", - "org.bstats" - ).forEach { - relocate(it, "${rootProject.group}.plugin.lib.$it") - } - } - - compileJava { - options.release.set(17) - } - - processResources { - filesMatching("plugin.yml") { - expand( - "name" to rootProject.name, - "group" to rootProject.group, - "version" to rootProject.version, - "description" to rootProject.description - ) - } - } -} \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml deleted file mode 100644 index 4f9523f..0000000 --- a/gradle/libs.versions.toml +++ /dev/null @@ -1,30 +0,0 @@ -[versions] - -# Paper Team -paper = "1.19.2-R0.1-SNAPSHOT" - -# Bukkit -bukkit-bstats = "3.0.0" - -# Placeholders -placeholder-api = "2.11.2" - -# Misc Libraries -nbt-api = "2.10.0" -vault-api = "1.7" -reserve-api = "0.1.5.0" - -[libraries] - -# Paper Team -paper = { module = "io.papermc.paper:paper-api", version.ref = "paper" } - -# Bukkit -bukkit-bstats = { module = "org.bstats:bstats-bukkit", version.ref = "bukkit-bstats" } - -# Misc Libraries -vault-api = { module = "com.github.MilkBowl:VaultAPI", version.ref = "vault-api" } - -nbt-api = { module = "de.tr7zw:nbt-data-api", version.ref = "nbt-api" } - -reserve-api = { module = "net.tnemc:Reserve", version.ref = "reserve-api" } \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index ae04661..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..d3a603e --- /dev/null +++ b/pom.xml @@ -0,0 +1,116 @@ + + + 4.0.0 + + com.badbones69 + crazyauctions + 1.2.19 + Crazy-Auctions + + + UTF-8 + + + + + + + crazycrew-repo-releases + CrazyCrew Team + https://repo.badbones69.com/releases + + + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + vault-repo + http://nexus.hc.to/content/repositories/pub_releases + + + codemc-repo + https://repo.codemc.io/repository/maven-public/ + + + + + + org.spigotmc + spigot-api + 1.19.3-R0.1-SNAPSHOT + provided + + + net.milkbowl.vault + VaultAPI + 1.7 + provided + + + bukkit + org.bukkit + + + + + net.tnemc + Reserve + 0.1.5.0 + provided + + + org.bstats + bstats-bukkit + 3.0.0 + provided + + + + + ${project.name}-[v${project.version}] + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + + org.bstats + + com.badbones69.crazyauctions.libraries + + + + + + package + + shade + + + + + + + \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts deleted file mode 100644 index 8b522d1..0000000 --- a/settings.gradle.kts +++ /dev/null @@ -1,3 +0,0 @@ -rootProject.name = "CrazyAuctions" - -enableFeaturePreview("VERSION_CATALOGS") \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/CrazyAuctions.java b/src/main/java/com/badbones69/crazyauctions/CrazyAuctions.java deleted file mode 100644 index 1980b26..0000000 --- a/src/main/java/com/badbones69/crazyauctions/CrazyAuctions.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.badbones69.crazyauctions; - -import com.badbones69.crazyauctions.api.CrazyManager; -import com.badbones69.crazyauctions.api.FileManager; -import com.badbones69.crazyauctions.api.FileManager.Files; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; - -public class CrazyAuctions extends JavaPlugin implements Listener { - - private static CrazyAuctions plugin; - - private Starter starter; - - private final FileManager fileManager = getStarter().getFileManager(); - - private final CrazyManager crazyManager = getStarter().getCrazyManager(); - - private final Methods methods = getStarter().getMethods(); - - private boolean isEnabled = false; - - @Override - public void onEnable() { - try { - plugin = this; - - starter = new Starter(); - - starter.run(); - - fileManager.setup(); - - crazyManager.load(); - - // methods.updateAuction(); - } catch (Exception e) { - e.printStackTrace(); - - isEnabled = false; - - return; - } - - isEnabled = true; - - enable(); - } - - @Override - public void onDisable() { - if (!isEnabled) return; - - disable(); - } - - private void enable() { - - } - - private void disable() { - Files.DATA.saveFile(); - } - - public static CrazyAuctions getPlugin() { - return plugin; - } - - public Starter getStarter() { - return starter; - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/Main.java b/src/main/java/com/badbones69/crazyauctions/Main.java new file mode 100644 index 0000000..eb29de7 --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/Main.java @@ -0,0 +1,479 @@ +package com.badbones69.crazyauctions; + +import com.badbones69.crazyauctions.api.*; +import com.badbones69.crazyauctions.api.FileManager.Files; +import com.badbones69.crazyauctions.api.events.AuctionListEvent; +import com.badbones69.crazyauctions.controllers.DupePatch; +import com.badbones69.crazyauctions.controllers.GUI; +import com.badbones69.crazyauctions.currency.Vault; +import org.bstats.bukkit.Metrics; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.error.YAMLException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Random; + +public class Main extends JavaPlugin implements Listener { + + public static FileManager fileManager = FileManager.getInstance(); + public static CrazyAuctions crazyAuctions = CrazyAuctions.getInstance(); + + @Override + public void onEnable() { + fileManager.logInfo(true).setup(this); + crazyAuctions.loadCrazyAuctions(); + Bukkit.getServer().getPluginManager().registerEvents(this, this); + Bukkit.getServer().getPluginManager().registerEvents(new GUI(), this); + Bukkit.getServer().getPluginManager().registerEvents(new DupePatch(), this); + Methods.updateAuction(); + startCheck(); + + if (!Vault.setupEconomy()) { saveDefaultConfig(); } + + Messages.addMissingMessages(); + new Metrics(this, 4624); //Starts up bStats + } + + @Override + public void onDisable() { + int file = 0; + Bukkit.getScheduler().cancelTask(file); + Files.DATA.saveFile(true); + } + + public boolean onCommand(CommandSender sender, Command cmd, String commandLable, String[] args) { + if (commandLable.equalsIgnoreCase("CrazyAuctions") || commandLable.equalsIgnoreCase("CrazyAuction") || commandLable.equalsIgnoreCase("CA") || commandLable.equalsIgnoreCase("AH") || commandLable.equalsIgnoreCase("HDV")) { + if (args.length == 0) { + if (!Methods.hasPermission(sender, "Access")) return true; + if (!(sender instanceof Player)) { + sender.sendMessage(Messages.PLAYERS_ONLY.getMessage()); + return true; + } + Player player = (Player) sender; + if (Files.CONFIG.getFile().contains("Settings.Category-Page-Opens-First")) { + if (Files.CONFIG.getFile().getBoolean("Settings.Category-Page-Opens-First")) { + GUI.openCategories(player, ShopType.SELL); + return true; + } + } + if (crazyAuctions.isSellingEnabled()) { + GUI.openShop(player, ShopType.SELL, Category.NONE, 1); + } else if (crazyAuctions.isBiddingEnabled()) { + GUI.openShop(player, ShopType.BID, Category.NONE, 1); + } else { + player.sendMessage(Methods.getPrefix() + Methods.color("&cThe bidding and selling options are both disabled. Please contact the admin about this.")); + } + return true; + } + if (args.length >= 1) { + if (args[0].equalsIgnoreCase("Help")) {// CA Help + if (!Methods.hasPermission(sender, "Access")) return true; + sender.sendMessage(Messages.HELP.getMessage()); + return true; + } + if (args[0].equalsIgnoreCase("test")) {// CA test [times] + if (!Methods.hasPermission(sender, "test")) return true; + int times = 1; + if (args.length >= 2) { + if (!Methods.isInt(args[1])) { + HashMap placeholders = new HashMap<>(); + placeholders.put("%Arg%", args[1]); + placeholders.put("%arg%", args[1]); + sender.sendMessage(Messages.NOT_A_NUMBER.getMessage(placeholders)); + return true; + } + times = Integer.parseInt(args[1]); + } + int price = 10; + int amount = 1; + ItemStack item = Methods.getItemInHand((Player) sender); + if (item != null && item.getType() != Material.AIR) { + // For testing as another player + String seller = "Test-Account"; + for (int it = 1; it <= times; it++) { + int num = 1; + Random r = new Random(); + for (; Files.DATA.getFile().contains("Items." + num); num++) ; + Files.DATA.getFile().set("Items." + num + ".Price", price); + Files.DATA.getFile().set("Items." + num + ".Seller", seller); + if (args[0].equalsIgnoreCase("Bid")) { + Files.DATA.getFile().set("Items." + num + ".Time-Till-Expire", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Bid-Time"))); + } else { + Files.DATA.getFile().set("Items." + num + ".Time-Till-Expire", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Sell-Time"))); + } + Files.DATA.getFile().set("Items." + num + ".Full-Time", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Full-Expire-Time"))); + int id = r.nextInt(Integer.MAX_VALUE); + for (String i : Files.DATA.getFile().getConfigurationSection("Items").getKeys(false)) + if (Files.DATA.getFile().getInt("Items." + i + ".StoreID") == id) id = r.nextInt(Integer.MAX_VALUE); + Files.DATA.getFile().set("Items." + num + ".StoreID", id); + ShopType type = ShopType.SELL; + Files.DATA.getFile().set("Items." + num + ".Biddable", args[0].equalsIgnoreCase("Bid")); + Files.DATA.getFile().set("Items." + num + ".TopBidder", "None"); + ItemStack I = item.clone(); + I.setAmount(amount); + Files.DATA.getFile().set("Items." + num + ".Item", I); + } + Files.DATA.saveFile(); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Price%", price + ""); + placeholders.put("%price%", price + ""); + sender.sendMessage(Messages.ADDED_ITEM_TO_AUCTION.getMessage(placeholders)); + if (item.getAmount() <= 1 || (item.getAmount() - amount) <= 0) { + Methods.setItemInHand((Player) sender, new ItemStack(Material.AIR)); + } else { + item.setAmount(item.getAmount() - amount); + } + } else { + sender.sendMessage(Messages.DOSENT_HAVE_ITEM_IN_HAND.getMessage()); + } + return true; + } + if (args[0].equalsIgnoreCase("Reload")) {// CA Reload + if (!Methods.hasPermission(sender, "Admin")) return true; + fileManager.logInfo(true).setup(this); + crazyAuctions.loadCrazyAuctions(); + sender.sendMessage(Messages.RELOAD.getMessage()); + return true; + } + if (args[0].equalsIgnoreCase("View")) {// CA View + if (!Methods.hasPermission(sender, "View")) return true; + if (!(sender instanceof Player)) { + sender.sendMessage(Messages.PLAYERS_ONLY.getMessage()); + return true; + } + if (args.length >= 2) { + Player player = (Player) sender; + GUI.openViewer(player, args[1], 1); + return true; + } + sender.sendMessage(Messages.CRAZYAUCTIONS_VIEW.getMessage()); + return true; + } + if (args[0].equalsIgnoreCase("Expired") || args[0].equalsIgnoreCase("Collect")) {// CA Expired + if (!Methods.hasPermission(sender, "Access")) return true; + if (!(sender instanceof Player)) { + sender.sendMessage(Messages.PLAYERS_ONLY.getMessage()); + return true; + } + Player player = (Player) sender; + GUI.openPlayersExpiredList(player, 1); + return true; + } + if (args[0].equalsIgnoreCase("Listed")) {// CA Listed + if (!Methods.hasPermission(sender, "Access")) return true; + if (!(sender instanceof Player)) { + sender.sendMessage(Messages.PLAYERS_ONLY.getMessage()); + return true; + } + Player player = (Player) sender; + GUI.openPlayersCurrentList(player, 1); + return true; + } + if (args[0].equalsIgnoreCase("Sell") || args[0].equalsIgnoreCase("Bid")) {// /CA Sell/Bid [Amount of Items] + if (!(sender instanceof Player)) { + sender.sendMessage(Messages.PLAYERS_ONLY.getMessage()); + return true; + } + if (args.length >= 2) { + Player player = (Player) sender; + if (args[0].equalsIgnoreCase("Sell")) { + if (!crazyAuctions.isSellingEnabled()) { + player.sendMessage(Messages.SELLING_DISABLED.getMessage()); + return true; + } + if (!Methods.hasPermission(player, "Sell")) return true; + } + if (args[0].equalsIgnoreCase("Bid")) { + if (!crazyAuctions.isBiddingEnabled()) { + player.sendMessage(Messages.BIDDING_DISABLED.getMessage()); + return true; + } + if (!Methods.hasPermission(player, "Bid")) return true; + } + ItemStack item = Methods.getItemInHand(player); + int amount = item.getAmount(); + if (args.length >= 3) { + if (!Methods.isInt(args[2])) { + HashMap placeholders = new HashMap<>(); + placeholders.put("%Arg%", args[2]); + placeholders.put("%arg%", args[2]); + player.sendMessage(Messages.NOT_A_NUMBER.getMessage(placeholders)); + return true; + } + amount = Integer.parseInt(args[2]); + if (amount <= 0) amount = 1; + if (amount > item.getAmount()) amount = item.getAmount(); + } + if (!Methods.isLong(args[1])) { + HashMap placeholders = new HashMap<>(); + placeholders.put("%Arg%", args[1]); + placeholders.put("%arg%", args[1]); + player.sendMessage(Messages.NOT_A_NUMBER.getMessage(placeholders)); + return true; + } + if (Methods.getItemInHand(player).getType() == Material.AIR) { + player.sendMessage(Messages.DOSENT_HAVE_ITEM_IN_HAND.getMessage()); + return false; + } + long price = Long.parseLong(args[1]); + if (args[0].equalsIgnoreCase("Bid")) { + if (price < Files.CONFIG.getFile().getLong("Settings.Minimum-Bid-Price")) { + player.sendMessage(Messages.BID_PRICE_TO_LOW.getMessage()); + return true; + } + if (price > Files.CONFIG.getFile().getLong("Settings.Max-Beginning-Bid-Price")) { + player.sendMessage(Messages.BID_PRICE_TO_HIGH.getMessage()); + return true; + } + } else { + if (price < Files.CONFIG.getFile().getLong("Settings.Minimum-Sell-Price")) { + player.sendMessage(Messages.SELL_PRICE_TO_LOW.getMessage()); + return true; + } + if (price > Files.CONFIG.getFile().getLong("Settings.Max-Beginning-Sell-Price")) { + player.sendMessage(Messages.SELL_PRICE_TO_HIGH.getMessage()); + return true; + } + } + if (!player.hasPermission("crazyauctions.bypass")) { + int SellLimit = 0; + int BidLimit = 0; + for (PermissionAttachmentInfo permission : player.getEffectivePermissions()) { + String perm = permission.getPermission(); + if (perm.startsWith("crazyauctions.sell.")) { + perm = perm.replace("crazyauctions.sell.", ""); + if (Methods.isInt(perm)) { + if (Integer.parseInt(perm) > SellLimit) { + SellLimit = Integer.parseInt(perm); + } + } + } + if (perm.startsWith("crazyauctions.bid.")) { + perm = perm.replace("crazyauctions.bid.", ""); + if (Methods.isInt(perm)) { + if (Integer.parseInt(perm) > BidLimit) { + BidLimit = Integer.parseInt(perm); + } + } + } + } + for (int i = 1; i < 100; i++) { + if (SellLimit < i) { + if (player.hasPermission("crazyauctions.sell." + i)) { + SellLimit = i; + } + } + if (BidLimit < i) { + if (player.hasPermission("crazyauctions.bid." + i)) { + BidLimit = i; + } + } + } + if (args[0].equalsIgnoreCase("Sell")) { + if (crazyAuctions.getItems(player, ShopType.SELL).size() >= SellLimit) { + player.sendMessage(Messages.MAX_ITEMS.getMessage()); + return true; + } + } + if (args[0].equalsIgnoreCase("Bid")) { + if (crazyAuctions.getItems(player, ShopType.BID).size() >= BidLimit) { + player.sendMessage(Messages.MAX_ITEMS.getMessage()); + return true; + } + } + } + for (String id : Files.CONFIG.getFile().getStringList("Settings.BlackList")) { + if (item.getType() == Methods.makeItem(id, 1).getType()) { + player.sendMessage(Messages.ITEM_BLACKLISTED.getMessage()); + return true; + } + } + if (!Files.CONFIG.getFile().getBoolean("Settings.Allow-Damaged-Items")) { + for (Material i : getDamageableItems()) { + if (item.getType() == i) { + if (item.getDurability() > 0) { + player.sendMessage(Messages.ITEM_DAMAGED.getMessage()); + return true; + } + } + } + } + if (!allowBook(item)) { + player.sendMessage(Messages.BOOK_NOT_ALLOWED.getMessage()); + return true; + } + String seller = player.getName(); + // For testing as another player + //String seller = "Test-Account"; + int num = 1; + Random r = new Random(); + for (; Files.DATA.getFile().contains("Items." + num); num++) ; + Files.DATA.getFile().set("Items." + num + ".Price", price); + Files.DATA.getFile().set("Items." + num + ".Seller", seller); + if (args[0].equalsIgnoreCase("Bid")) { + Files.DATA.getFile().set("Items." + num + ".Time-Till-Expire", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Bid-Time"))); + } else { + Files.DATA.getFile().set("Items." + num + ".Time-Till-Expire", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Sell-Time"))); + } + Files.DATA.getFile().set("Items." + num + ".Full-Time", Methods.convertToMill(Files.CONFIG.getFile().getString("Settings.Full-Expire-Time"))); + int id = r.nextInt(999999); + // Runs 3x to check for same ID. + for (String i : Files.DATA.getFile().getConfigurationSection("Items").getKeys(false)) + if (Files.DATA.getFile().getInt("Items." + i + ".StoreID") == id) id = r.nextInt(Integer.MAX_VALUE); + for (String i : Files.DATA.getFile().getConfigurationSection("Items").getKeys(false)) + if (Files.DATA.getFile().getInt("Items." + i + ".StoreID") == id) id = r.nextInt(Integer.MAX_VALUE); + for (String i : Files.DATA.getFile().getConfigurationSection("Items").getKeys(false)) + if (Files.DATA.getFile().getInt("Items." + i + ".StoreID") == id) id = r.nextInt(Integer.MAX_VALUE); + Files.DATA.getFile().set("Items." + num + ".StoreID", id); + ShopType type = ShopType.SELL; + if (args[0].equalsIgnoreCase("Bid")) { + Files.DATA.getFile().set("Items." + num + ".Biddable", true); + type = ShopType.BID; + } else { + Files.DATA.getFile().set("Items." + num + ".Biddable", false); + } + Files.DATA.getFile().set("Items." + num + ".TopBidder", "None"); + ItemStack I = item.clone(); + I.setAmount(amount); + Files.DATA.getFile().set("Items." + num + ".Item", I); + Files.DATA.saveFile(); + Bukkit.getPluginManager().callEvent(new AuctionListEvent(player, type, I, price)); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Price%", price + ""); + placeholders.put("%price%", price + ""); + player.sendMessage(Messages.ADDED_ITEM_TO_AUCTION.getMessage(placeholders)); + if (item.getAmount() <= 1 || (item.getAmount() - amount) <= 0) { + Methods.setItemInHand(player, new ItemStack(Material.AIR)); + } else { + item.setAmount(item.getAmount() - amount); + } + return false; + } + sender.sendMessage(Messages.CRAZYAUCTIONS_SELL_BID.getMessage()); + return true; + } + } + } + sender.sendMessage(Messages.CRAZYAUCTIONS_HELP.getMessage()); + return false; + } + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + final Player player = e.getPlayer(); + if (player.getName().equalsIgnoreCase("BadBones69")) { + Bukkit.getScheduler().runTaskLater(this, () -> player.sendMessage(Methods.getPrefix() + Methods.color("&7This server is running your Crazy Auctions Plugin. " + "&7It is running version &av" + Bukkit.getServer().getPluginManager().getPlugin("CrazyAuctions").getDescription().getVersion() + "&7.")), 40); + } + } + + private void startCheck() { + Bukkit.getScheduler().runTaskTimer(this, Methods :: updateAuction, 20, 5 * 20); + } + + private ArrayList getDamageableItems() { + ArrayList ma = new ArrayList<>(); + if (Version.isNewer(Version.v1_12_R1)) { + ma.add(Material.matchMaterial("GOLDEN_HELMET")); + ma.add(Material.matchMaterial("GOLDEN_CHESTPLATE")); + ma.add(Material.matchMaterial("GOLDEN_LEGGINGS")); + ma.add(Material.matchMaterial("GOLDEN_BOOTS")); + ma.add(Material.matchMaterial("WOODEN_SWORD")); + ma.add(Material.matchMaterial("WOODEN_AXE")); + ma.add(Material.matchMaterial("WOODEN_PICKAXE")); + ma.add(Material.matchMaterial("WOODEN_AXE")); + ma.add(Material.matchMaterial("WOODEN_SHOVEL")); + ma.add(Material.matchMaterial("STONE_SHOVEL")); + ma.add(Material.matchMaterial("IRON_SHOVEL")); + ma.add(Material.matchMaterial("DIAMOND_SHOVEL")); + ma.add(Material.matchMaterial("WOODEN_HOE")); + ma.add(Material.matchMaterial("GOLDEN_HOE")); + ma.add(Material.matchMaterial("CROSSBOW")); + ma.add(Material.matchMaterial("TRIDENT")); + ma.add(Material.matchMaterial("TURTLE_HELMET")); + } else { + ma.add(Material.matchMaterial("GOLD_HELMET")); + ma.add(Material.matchMaterial("GOLD_CHESTPLATE")); + ma.add(Material.matchMaterial("GOLD_LEGGINGS")); + ma.add(Material.matchMaterial("GOLD_BOOTS")); + ma.add(Material.matchMaterial("WOOD_SWORD")); + ma.add(Material.matchMaterial("WOOD_AXE")); + ma.add(Material.matchMaterial("WOOD_PICKAXE")); + ma.add(Material.matchMaterial("WOOD_AXE")); + ma.add(Material.matchMaterial("WOOD_SPADE")); + ma.add(Material.matchMaterial("STONE_SPADE")); + ma.add(Material.matchMaterial("IRON_SPADE")); + ma.add(Material.matchMaterial("DIAMOND_SPADE")); + ma.add(Material.matchMaterial("WOOD_HOE")); + ma.add(Material.matchMaterial("GOLD_HOE")); + } + ma.add(Material.DIAMOND_HELMET); + ma.add(Material.DIAMOND_CHESTPLATE); + ma.add(Material.DIAMOND_LEGGINGS); + ma.add(Material.DIAMOND_BOOTS); + ma.add(Material.CHAINMAIL_HELMET); + ma.add(Material.CHAINMAIL_CHESTPLATE); + ma.add(Material.CHAINMAIL_LEGGINGS); + ma.add(Material.CHAINMAIL_BOOTS); + ma.add(Material.IRON_HELMET); + ma.add(Material.IRON_CHESTPLATE); + ma.add(Material.IRON_LEGGINGS); + ma.add(Material.IRON_BOOTS); + ma.add(Material.LEATHER_HELMET); + ma.add(Material.LEATHER_CHESTPLATE); + ma.add(Material.LEATHER_LEGGINGS); + ma.add(Material.LEATHER_BOOTS); + ma.add(Material.BOW); + ma.add(Material.STONE_SWORD); + ma.add(Material.IRON_SWORD); + ma.add(Material.DIAMOND_SWORD); + ma.add(Material.STONE_AXE); + ma.add(Material.IRON_AXE); + ma.add(Material.DIAMOND_AXE); + ma.add(Material.STONE_PICKAXE); + ma.add(Material.IRON_PICKAXE); + ma.add(Material.DIAMOND_PICKAXE); + ma.add(Material.STONE_AXE); + ma.add(Material.IRON_AXE); + ma.add(Material.DIAMOND_AXE); + ma.add(Material.STONE_HOE); + ma.add(Material.IRON_HOE); + ma.add(Material.DIAMOND_HOE); + ma.add(Material.FLINT_AND_STEEL); + ma.add(Material.ANVIL); + ma.add(Material.FISHING_ROD); + return ma; + } + + private boolean allowBook(ItemStack item) { + if (item != null && item.hasItemMeta() && item.getItemMeta() instanceof BookMeta) { + Bukkit.getLogger().info("Checking " + item.getType() + " for illegal unicode."); + try { + Files.TEST_FILE.getFile().set("Test", item); + Files.TEST_FILE.saveFile(); + Bukkit.getLogger().info("" + item.getType() + " has passed unicode checks."); + } catch (YAMLException e) { + Bukkit.getLogger().info("" + item.getType() + " has failed unicode checks and has been denied."); + return false; + } + return ((BookMeta) item.getItemMeta()).getPages().stream().mapToInt(String :: length).sum() < 2000; + } + return true; + } + + public Material getMaterial(String newMaterial, String oldMaterial) { + return Material.matchMaterial(Version.isNewer(Version.v1_12_R1) ? newMaterial : oldMaterial); + } + +} diff --git a/src/main/java/com/badbones69/crazyauctions/Methods.java b/src/main/java/com/badbones69/crazyauctions/Methods.java index e298339..c2c098c 100644 --- a/src/main/java/com/badbones69/crazyauctions/Methods.java +++ b/src/main/java/com/badbones69/crazyauctions/Methods.java @@ -1,117 +1,277 @@ package com.badbones69.crazyauctions; import com.badbones69.crazyauctions.api.FileManager.Files; -import com.badbones69.crazyauctions.api.enums.Messages; -import com.badbones69.crazyauctions.utils.ItemBuilder; -import com.badbones69.crazyauctions.utils.func.ServerProtocol; -import net.md_5.bungee.api.chat.TextComponent; +import com.badbones69.crazyauctions.api.Messages; +import com.badbones69.crazyauctions.api.Version; +import com.badbones69.crazyauctions.api.events.AuctionExpireEvent; +import com.badbones69.crazyauctions.api.events.AuctionWinBidEvent; +import com.badbones69.crazyauctions.currency.CurrencyManager; import org.bukkit.*; import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -@SuppressWarnings("deprecation") public class Methods { - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); + public final static Pattern HEX_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}"); - public final Pattern HEX_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}"); - - public String color(String message) { - if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) { + public static String color(String message) { + if (Version.isNewer(Version.v1_15_R1)) { Matcher matcher = HEX_PATTERN.matcher(message); - StringBuilder buffer = new StringBuilder(); - + StringBuffer buffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buffer, net.md_5.bungee.api.ChatColor.of(matcher.group()).toString()); } - return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString()); } - return ChatColor.translateAlternateColorCodes('&', message); } - public String getPrefix() { + public static String getPrefix() { return color(Files.CONFIG.getFile().getString("Settings.Prefix", "")); } - public String getPrefix(String msg) { + public static String getPrefix(String msg) { return color(Files.CONFIG.getFile().getString("Settings.Prefix", "") + msg); } - - public String sanitizeColor(String msg) { - return sanitizeFormat(color(msg)); - } - public String removeColor(String msg) { + public static String removeColor(String msg) { return ChatColor.stripColor(msg); } - - public static String sanitizeFormat(String string) { - return TextComponent.toLegacyText(TextComponent.fromLegacyText(string)); - } - public ItemStack makeItem(Material material, int amount, String name, List lore, HashMap enchants) { - ItemBuilder newItem = new ItemBuilder().setMaterial(material).setAmount(amount).setName(name).setLore(lore).setEnchantments(enchants); - return newItem.build(); - } - - public ItemStack getItemInHand(Player player) { - return player.getInventory().getItemInMainHand(); - } - - public void setItemInHand(Player player, ItemStack item) { - player.getInventory().setItemInMainHand(item); - } - - public Player getPlayer(String name) { + public static ItemStack makeItem(String type, int amount) { + int ty = 0; + if (type.contains(":")) { + String[] b = type.split(":"); + type = b[0]; + ty = Integer.parseInt(b[1]); + } + Material m = Material.matchMaterial(type); + ItemStack item; try { - return plugin.getServer().getPlayer(name); + item = new ItemStack(m, amount, (short) ty); + } catch (Exception e) { + if (Version.isNewer(Version.v1_12_R1)) { + item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1); + + } else { + item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14); + } + } + return item; + } + + public static ItemStack makeItem(String type, int amount, String name) { + int ty = 0; + if (type.contains(":")) { + String[] b = type.split(":"); + type = b[0]; + ty = Integer.parseInt(b[1]); + } + Material m = Material.matchMaterial(type); + ItemStack item; + try { + item = new ItemStack(m, amount, (short) ty); + } catch (Exception e) { + if (Version.isNewer(Version.v1_12_R1)) { + item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1); + + } else { + item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14); + } + } + ItemMeta me = item.getItemMeta(); + me.setDisplayName(color(name)); + item.setItemMeta(me); + return item; + } + + public static ItemStack makeItem(String type, int amount, String name, List lore) { + ArrayList l = new ArrayList<>(); + int ty = 0; + if (type.contains(":")) { + String[] b = type.split(":"); + type = b[0]; + ty = Integer.parseInt(b[1]); + } + Material m = Material.matchMaterial(type); + ItemStack item; + try { + item = new ItemStack(m, amount, (short) ty); + } catch (Exception e) { + if (Version.isNewer(Version.v1_12_R1)) { + item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1); + + } else { + item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14); + } + } + ItemMeta me = item.getItemMeta(); + me.setDisplayName(color(name)); + for (String L : lore) + l.add(color(L)); + me.setLore(l); + item.setItemMeta(me); + return item; + } + + public static ItemStack makeItem(Material material, int amount, int type, String name) { + ItemStack item = new ItemStack(material, amount, (short) type); + ItemMeta m = item.getItemMeta(); + m.setDisplayName(color(name)); + item.setItemMeta(m); + return item; + } + + public static ItemStack makeItem(Material material, int amount, int type, String name, List lore) { + ArrayList l = new ArrayList<>(); + ItemStack item = new ItemStack(material, amount, (short) type); + ItemMeta m = item.getItemMeta(); + m.setDisplayName(color(name)); + for (String L : lore) + l.add(color(L)); + m.setLore(l); + item.setItemMeta(m); + return item; + } + + public static ItemStack makeItem(Material material, int amount, int type, String name, List lore, Map enchants) { + ItemStack item = new ItemStack(material, amount, (short) type); + ItemMeta m = item.getItemMeta(); + m.setDisplayName(name); + m.setLore(lore); + item.setItemMeta(m); + item.addUnsafeEnchantments(enchants); + return item; + } + + public static ItemStack addLore(ItemStack item, String i) { + ArrayList lore = new ArrayList<>(); + ItemMeta m = item.getItemMeta(); + if (item.getItemMeta().hasLore()) { + lore.addAll(item.getItemMeta().getLore()); + } + lore.add(i); + m.setLore(lore); + item.setItemMeta(m); + return item; + } + + public static ItemStack addLore(ItemStack item, List list) { + if (item != null && item.getType() != Material.AIR) { + ArrayList lore = new ArrayList<>(); + ItemMeta m = item.getItemMeta(); + if (item.hasItemMeta() && item.getItemMeta().hasLore()) { + lore.addAll(item.getItemMeta().getLore()); + } + for (String i : list) + lore.add(color(i)); + m.setLore(lore); + item.setItemMeta(m); + } + return item; + } + + public static Integer getVersion() { + String ver = Bukkit.getServer().getClass().getPackage().getName(); + ver = ver.substring(ver.lastIndexOf('.') + 1); + ver = ver.replace("_", "").replace("R", "").replace("v", ""); + return Integer.parseInt(ver); + } + + @SuppressWarnings("deprecation") + public static ItemStack getItemInHand(Player player) { + if (getVersion() >= 191) { + return player.getInventory().getItemInMainHand(); + } else { + return player.getItemInHand(); + } + } + + @SuppressWarnings("deprecation") + public static void setItemInHand(Player player, ItemStack item) { + if (getVersion() >= 191) { + player.getInventory().setItemInMainHand(item); + } else { + player.setItemInHand(item); + } + } + + public static boolean isInt(String s) { + try { + Integer.parseInt(s); + } catch (NumberFormatException nfe) { + return false; + } + return true; + } + + public static boolean isLong(String s) { + try { + Long.parseLong(s); + } catch (NumberFormatException nfe) { + return false; + } + return true; + } + + public static Player getPlayer(String name) { + try { + return Bukkit.getServer().getPlayer(name); } catch (Exception e) { return null; } } @SuppressWarnings("deprecation") - public OfflinePlayer getOfflinePlayer(String name) { - return plugin.getServer().getOfflinePlayer(name); + public static OfflinePlayer getOfflinePlayer(String name) { + return Bukkit.getServer().getOfflinePlayer(name); } - public boolean isOnline(String name) { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (player.getName().equalsIgnoreCase(name)) return true; + public static Location getLoc(Player player) { + return player.getLocation(); + } + + public static void runCMD(Player player, String CMD) { + player.performCommand(CMD); + } + + public static boolean isOnline(String name) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.getName().equalsIgnoreCase(name)) { + return true; + } } - return false; } - public boolean isOnline(String name, CommandSender commandSender) { - for (Player player : plugin.getServer().getOnlinePlayers()) { - if (player.getName().equalsIgnoreCase(name)) return true; + public static boolean isOnline(String name, CommandSender p) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.getName().equalsIgnoreCase(name)) { + return true; + } } - - commandSender.sendMessage(Messages.NOT_ONLINE.getMessage()); + p.sendMessage(Messages.NOT_ONLINE.getMessage()); return false; } - public boolean hasPermission(Player player, String perm) { + public static boolean hasPermission(Player player, String perm) { if (!player.hasPermission("crazyauctions." + perm)) { player.sendMessage(Messages.NO_PERMISSION.getMessage()); return false; } - return true; } - public boolean hasPermission(CommandSender sender, String perm) { + public static boolean hasPermission(CommandSender sender, String perm) { if (sender instanceof Player) { Player player = (Player) sender; - if (!player.hasPermission("crazyauctions." + perm)) { player.sendMessage(Messages.NO_PERMISSION.getMessage()); return false; @@ -123,7 +283,171 @@ public class Methods { } } - public boolean isInvFull(Player player) { + public static List getPage(List list, Integer page) { + List items = new ArrayList<>(); + if (page <= 0) page = 1; + int max = 45; + int index = page * max - max; + int endIndex = index >= list.size() ? list.size() - 1 : index + max; + for (; index < endIndex; index++) { + if (index < list.size()) items.add(list.get(index)); + } + for (; items.size() == 0; page--) { + if (page <= 0) break; + index = page * max - max; + endIndex = index >= list.size() ? list.size() - 1 : index + max; + for (; index < endIndex; index++) { + if (index < list.size()) items.add(list.get(index)); + } + } + return items; + } + + public static List getPageInts(List list, Integer page) { + List items = new ArrayList<>(); + if (page <= 0) page = 1; + int max = 45; + int index = page * max - max; + int endIndex = index >= list.size() ? list.size() - 1 : index + max; + for (; index < endIndex; index++) { + if (index < list.size()) items.add(list.get(index)); + } + for (; items.size() == 0; page--) { + if (page <= 0) break; + index = page * max - max; + endIndex = index >= list.size() ? list.size() - 1 : index + max; + for (; index < endIndex; index++) { + if (index < list.size()) items.add(list.get(index)); + } + } + return items; + } + + public static int getMaxPage(List list) { + int maxPage = 1; + int amount = list.size(); + for (; amount > 45; amount -= 45, maxPage++) ; + return maxPage; + } + + public static String convertToTime(long time) { + Calendar C = Calendar.getInstance(); + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(time); + int total = ((int) (cal.getTimeInMillis() / 1000) - (int) (C.getTimeInMillis() / 1000)); + int D = 0; + int H = 0; + int M = 0; + int S = 0; + for (; total > 86400; total -= 86400, D++) ; + for (; total > 3600; total -= 3600, H++) ; + for (; total > 60; total -= 60, M++) ; + S += total; + return D + "d " + H + "h " + M + "m " + S + "s "; + } + + public static long convertToMill(String time) { + Calendar cal = Calendar.getInstance(); + for (String i : time.split(" ")) { + if (i.contains("D") || i.contains("d")) { + cal.add(Calendar.DATE, Integer.parseInt(i.replace("D", "").replace("d", ""))); + } + if (i.contains("H") || i.contains("h")) { + cal.add(Calendar.HOUR, Integer.parseInt(i.replace("H", "").replace("h", ""))); + } + if (i.contains("M") || i.contains("m")) { + cal.add(Calendar.MINUTE, Integer.parseInt(i.replace("M", "").replace("m", ""))); + } + if (i.contains("S") || i.contains("s")) { + cal.add(Calendar.SECOND, Integer.parseInt(i.replace("S", "").replace("s", ""))); + } + } + return cal.getTimeInMillis(); + } + + public static boolean isInvFull(Player player) { return player.getInventory().firstEmpty() == -1; } + + public static void updateAuction() { + FileConfiguration data = Files.DATA.getFile(); + Calendar cal = Calendar.getInstance(); + Calendar expireTime = Calendar.getInstance(); + Calendar fullExpireTime = Calendar.getInstance(); + boolean shouldSave = false; + if (data.contains("OutOfTime/Cancelled")) { + for (String i : data.getConfigurationSection("OutOfTime/Cancelled").getKeys(false)) { + fullExpireTime.setTimeInMillis(data.getLong("OutOfTime/Cancelled." + i + ".Full-Time")); + if (cal.after(fullExpireTime)) { + data.set("OutOfTime/Cancelled." + i, null); + shouldSave = true; + } + } + } + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + expireTime.setTimeInMillis(data.getLong("Items." + i + ".Time-Till-Expire")); + fullExpireTime.setTimeInMillis(data.getLong("Items." + i + ".Full-Time")); + if (cal.after(expireTime)) { + int num = 1; + for (; data.contains("OutOfTime/Cancelled." + num); num++) ; + if (data.getBoolean("Items." + i + ".Biddable") && !data.getString("Items." + i + ".TopBidder").equalsIgnoreCase("None") && CurrencyManager.getMoney(getPlayer(data.getString("Items." + i + ".TopBidder"))) >= data.getInt("Items." + i + ".Price")) { + String winner = data.getString("Items." + i + ".TopBidder"); + String seller = data.getString("Items." + i + ".Seller"); + Long price = data.getLong("Items." + i + ".Price"); + CurrencyManager.addMoney(getOfflinePlayer(seller), price); + CurrencyManager.removeMoney(getOfflinePlayer(winner), price); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Price%", getPrice(i, false)); + placeholders.put("%price%", getPrice(i, false)); + placeholders.put("%Player%", winner); + placeholders.put("%player%", winner); + if (isOnline(winner) && getPlayer(winner) != null) { + Player player = getPlayer(winner); + Bukkit.getPluginManager().callEvent(new AuctionWinBidEvent(player, data.getItemStack("Items." + i + ".Item"), price)); + player.sendMessage(Messages.WIN_BIDDING.getMessage(placeholders)); + } + if (isOnline(seller) && getPlayer(seller) != null) { + Player player = getPlayer(seller); + player.sendMessage(Messages.SOMEONE_WON_PLAYERS_BID.getMessage(placeholders)); + } + data.set("OutOfTime/Cancelled." + num + ".Seller", winner); + data.set("OutOfTime/Cancelled." + num + ".Full-Time", fullExpireTime.getTimeInMillis()); + data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID")); + data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item")); + } else { + String seller = data.getString("Items." + i + ".Seller"); + Player player = getPlayer(seller); + if (isOnline(seller) && getPlayer(seller) != null) { + player.sendMessage(Messages.ITEM_HAS_EXPIRED.getMessage()); + } + AuctionExpireEvent event = new AuctionExpireEvent(player, data.getItemStack("Items." + i + ".Item")); + Bukkit.getPluginManager().callEvent(event); + data.set("OutOfTime/Cancelled." + num + ".Seller", data.getString("Items." + i + ".Seller")); + data.set("OutOfTime/Cancelled." + num + ".Full-Time", fullExpireTime.getTimeInMillis()); + data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID")); + data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item")); + } + data.set("Items." + i, null); + shouldSave = true; + } + } + } + if (shouldSave) Files.DATA.saveFile(); + } + + public static String getPrice(String ID, Boolean Expired) { + long price = 0L; + if (Expired) { + if (Files.DATA.getFile().contains("OutOfTime/Cancelled." + ID + ".Price")) { + price = Files.DATA.getFile().getLong("OutOfTime/Cancelled." + ID + ".Price"); + } + } else { + if (Files.DATA.getFile().contains("Items." + ID + ".Price")) { + price = Files.DATA.getFile().getLong("Items." + ID + ".Price"); + } + } + return String.valueOf(price); + } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/Starter.java b/src/main/java/com/badbones69/crazyauctions/Starter.java deleted file mode 100644 index 24d59db..0000000 --- a/src/main/java/com/badbones69/crazyauctions/Starter.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.badbones69.crazyauctions; - -import com.badbones69.crazyauctions.api.CrazyManager; -import com.badbones69.crazyauctions.api.FileManager; -import com.badbones69.crazyauctions.api.economy.vault.VaultSupport; -import com.badbones69.crazyauctions.utils.SkullCreator; - -public class Starter { - - private FileManager fileManager; - - private CrazyManager crazyManager; - - private VaultSupport vaultSupport; - - private Methods methods; - - private SkullCreator skullCreator; - - public void run() { - fileManager = new FileManager(); - crazyManager = new CrazyManager(); - - vaultSupport = new VaultSupport(); - - methods = new Methods(); - - skullCreator = new SkullCreator(); - } - - public FileManager getFileManager() { - return fileManager; - } - - public CrazyManager getCrazyManager() { - return crazyManager; - } - - public VaultSupport getVaultSupport() { - return vaultSupport; - } - - public Methods getMethods() { - return methods; - } - - public SkullCreator getSkullCreator() { - return skullCreator; - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/enums/AuctionCategories.java b/src/main/java/com/badbones69/crazyauctions/api/Category.java similarity index 51% rename from src/main/java/com/badbones69/crazyauctions/api/enums/AuctionCategories.java rename to src/main/java/com/badbones69/crazyauctions/api/Category.java index 0de5742..11e46ee 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/enums/AuctionCategories.java +++ b/src/main/java/com/badbones69/crazyauctions/api/Category.java @@ -1,11 +1,11 @@ -package com.badbones69.crazyauctions.api.enums; +package com.badbones69.crazyauctions.api; -import com.badbones69.crazyauctions.utils.func.ServerProtocol; import org.bukkit.Material; + import java.util.ArrayList; -public enum AuctionCategories { - +public enum Category { + NONE("None", new ArrayList<>()), OTHER("Other", getOthers()), ARMOR("Armor", getArmor()), @@ -14,194 +14,192 @@ public enum AuctionCategories { FOOD("Food", getFood()), POTIONS("Potions", getPotions()), BLOCKS("Blocks", getBlocks()); - + private final String name; private final ArrayList items; - + /** * @param name Name of the Shop Type. */ - AuctionCategories(String name, ArrayList items) { + private Category(String name, ArrayList items) { this.name = name; this.items = items; } - + /** * @param name Name of the Type you want. * @return Returns the Type as an Enum. */ - public static AuctionCategories getFromName(String name) { - for (AuctionCategories type : AuctionCategories.values()) { - if (type.getName().equalsIgnoreCase(name)) return type; + public static Category getFromName(String name) { + for (Category type : Category.values()) { + if (type.getName().equalsIgnoreCase(name)) { + return type; + } } - return null; } - + private static ArrayList getArmor() { ArrayList ma = new ArrayList<>(); - - ma.add(Material.LEATHER_HELMET); - ma.add(Material.LEATHER_CHESTPLATE); - ma.add(Material.LEATHER_LEGGINGS); - ma.add(Material.LEATHER_BOOTS); - - ma.add(Material.GOLDEN_HELMET); - ma.add(Material.GOLDEN_CHESTPLATE); - ma.add(Material.GOLDEN_LEGGINGS); - ma.add(Material.GOLDEN_BOOTS); - - ma.add(Material.CHAINMAIL_HELMET); - ma.add(Material.CHAINMAIL_CHESTPLATE); - ma.add(Material.CHAINMAIL_LEGGINGS); - ma.add(Material.CHAINMAIL_BOOTS); - - ma.add(Material.IRON_HELMET); - ma.add(Material.IRON_CHESTPLATE); - ma.add(Material.IRON_LEGGINGS); - ma.add(Material.IRON_BOOTS); - + if (Version.isNewer(Version.v1_12_R1)) { + ma.add(Material.matchMaterial("GOLDEN_HELMET")); + ma.add(Material.matchMaterial("GOLDEN_CHESTPLATE")); + ma.add(Material.matchMaterial("GOLDEN_LEGGINGS")); + ma.add(Material.matchMaterial("GOLDEN_BOOTS")); + } else { + ma.add(Material.matchMaterial("GOLD_HELMET")); + ma.add(Material.matchMaterial("GOLD_CHESTPLATE")); + ma.add(Material.matchMaterial("GOLD_LEGGINGS")); + ma.add(Material.matchMaterial("GOLD_BOOTS")); + } ma.add(Material.DIAMOND_HELMET); ma.add(Material.DIAMOND_CHESTPLATE); ma.add(Material.DIAMOND_LEGGINGS); ma.add(Material.DIAMOND_BOOTS); - - ma.add(Material.TURTLE_HELMET); - - if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) { + ma.add(Material.CHAINMAIL_HELMET); + ma.add(Material.CHAINMAIL_CHESTPLATE); + ma.add(Material.CHAINMAIL_LEGGINGS); + ma.add(Material.CHAINMAIL_BOOTS); + ma.add(Material.IRON_HELMET); + ma.add(Material.IRON_CHESTPLATE); + ma.add(Material.IRON_LEGGINGS); + ma.add(Material.IRON_BOOTS); + ma.add(Material.DIAMOND_HELMET); + ma.add(Material.DIAMOND_CHESTPLATE); + ma.add(Material.DIAMOND_LEGGINGS); + ma.add(Material.DIAMOND_BOOTS); + if (Version.isNewer(Version.v1_15_R1)) { ma.add(Material.NETHERITE_HELMET); ma.add(Material.NETHERITE_CHESTPLATE); ma.add(Material.NETHERITE_LEGGINGS); ma.add(Material.NETHERITE_BOOTS); } - return ma; } - + private static ArrayList getTools() { ArrayList ma = new ArrayList<>(); - - ma.add(Material.WOODEN_PICKAXE); - ma.add(Material.WOODEN_AXE); - ma.add(Material.WOODEN_SHOVEL); - ma.add(Material.WOODEN_HOE); - + if (Version.isNewer(Version.v1_12_R1)) { + ma.add(Material.matchMaterial("WOODEN_PICKAXE")); + ma.add(Material.matchMaterial("WOODEN_AXE")); + ma.add(Material.matchMaterial("WOODEN_SHOVEL")); + ma.add(Material.matchMaterial("WOODEN_HOE")); + ma.add(Material.matchMaterial("GOLDEN_PICKAXE")); + ma.add(Material.matchMaterial("GOLDEN_AXE")); + ma.add(Material.matchMaterial("GOLDEN_SHOVEL")); + ma.add(Material.matchMaterial("GOLDEN_HOE")); + ma.add(Material.matchMaterial("STONE_SHOVEL")); + ma.add(Material.matchMaterial("IRON_SHOVEL")); + ma.add(Material.matchMaterial("DIAMOND_SHOVEL")); + } else { + ma.add(Material.matchMaterial("WOOD_PICKAXE")); + ma.add(Material.matchMaterial("WOOD_AXE")); + ma.add(Material.matchMaterial("WOOD_SPADE")); + ma.add(Material.matchMaterial("WOOD_HOE")); + ma.add(Material.matchMaterial("GOLD_PICKAXE")); + ma.add(Material.matchMaterial("GOLD_AXE")); + ma.add(Material.matchMaterial("GOLD_SPADE")); + ma.add(Material.matchMaterial("GOLD_HOE")); + ma.add(Material.matchMaterial("STONE_SPADE")); + ma.add(Material.matchMaterial("IRON_SPADE")); + ma.add(Material.matchMaterial("DIAMOND_SPADE")); + } ma.add(Material.STONE_PICKAXE); - ma.add(Material.STONE_AXE); - ma.add(Material.STONE_SHOVEL); - ma.add(Material.STONE_HOE); - - ma.add(Material.GOLDEN_PICKAXE); - ma.add(Material.GOLDEN_AXE); - ma.add(Material.GOLDEN_SHOVEL); - ma.add(Material.GOLDEN_HOE); - ma.add(Material.IRON_PICKAXE); - ma.add(Material.IRON_AXE); - ma.add(Material.IRON_SHOVEL); - ma.add(Material.IRON_HOE); - ma.add(Material.DIAMOND_PICKAXE); + ma.add(Material.STONE_AXE); + ma.add(Material.IRON_AXE); ma.add(Material.DIAMOND_AXE); - ma.add(Material.DIAMOND_SHOVEL); + ma.add(Material.STONE_HOE); + ma.add(Material.IRON_HOE); ma.add(Material.DIAMOND_HOE); - - ma.add(Material.SHEARS); - ma.add(Material.FISHING_ROD); - ma.add(Material.FLINT_AND_STEEL); - ma.add(Material.SPYGLASS); - - if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) { + if (Version.isNewer(Version.v1_15_R1)) { ma.add(Material.NETHERITE_PICKAXE); ma.add(Material.NETHERITE_AXE); ma.add(Material.NETHERITE_HOE); ma.add(Material.NETHERITE_SHOVEL); } - return ma; } - + private static ArrayList getWeapons() { ArrayList ma = new ArrayList<>(); - - ma.add(Material.WOODEN_SWORD); - ma.add(Material.WOODEN_AXE); - + if (Version.isNewer(Version.v1_12_R1)) { + ma.add(Material.matchMaterial("WOODEN_SWORD")); + ma.add(Material.matchMaterial("WOODEN_AXE")); + ma.add(Material.matchMaterial("GOLDEN_SWORD")); + ma.add(Material.matchMaterial("GOLDEN_AXE")); + } else { + ma.add(Material.matchMaterial("WOOD_SWORD")); + ma.add(Material.matchMaterial("WOOD_AXE")); + ma.add(Material.matchMaterial("GOLD_SWORD")); + ma.add(Material.matchMaterial("GOLD_AXE")); + } ma.add(Material.STONE_SWORD); - ma.add(Material.STONE_AXE); - - ma.add(Material.GOLDEN_SWORD); - ma.add(Material.GOLDEN_AXE); - ma.add(Material.IRON_SWORD); - ma.add(Material.IRON_AXE); - ma.add(Material.DIAMOND_SWORD); + ma.add(Material.STONE_AXE); + ma.add(Material.IRON_AXE); ma.add(Material.DIAMOND_AXE); - ma.add(Material.BOW); - ma.add(Material.CROSSBOW); - ma.add(Material.TRIDENT); - - if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) { + if (Version.isNewer(Version.v1_15_R1)) { ma.add(Material.NETHERITE_SWORD); ma.add(Material.NETHERITE_AXE); } - return ma; } - + private static ArrayList getFood() { ArrayList ma = new ArrayList<>(); - for (Material m : Material.values()) { if (m.isEdible()) { if (m != Material.POTION) ma.add(m); } } - return ma; } - + private static ArrayList getPotions() { ArrayList ma = new ArrayList<>(); ma.add(Material.POTION); - - if (Material.matchMaterial("SPLASH_POTION") != null) ma.add(Material.matchMaterial("SPLASH_POTION")); - - if (Material.matchMaterial("LINGERING_POTION") != null) ma.add(Material.matchMaterial("LINGERING_POTION")); - + if (Material.matchMaterial("SPLASH_POTION") != null) { + ma.add(Material.matchMaterial("SPLASH_POTION")); + } + if (Material.matchMaterial("LINGERING_POTION") != null) { + ma.add(Material.matchMaterial("LINGERING_POTION")); + } return ma; } - + private static ArrayList getBlocks() { ArrayList ma = new ArrayList<>(); - for (Material m : Material.values()) { - if (m.isBlock()) ma.add(m); + if (m.isBlock()) { + ma.add(m); + } } - return ma; } - + private static ArrayList getOthers() { ArrayList ma = new ArrayList<>(); - for (Material m : Material.values()) { - if (!(getArmor().contains(m) || getTools().contains(m) || getWeapons().contains(m) || getFood().contains(m) || getPotions().contains(m) || getBlocks().contains(m))) ma.add(m); + if (!(getArmor().contains(m) || getTools().contains(m) || getWeapons().contains(m) || getFood().contains(m) || getPotions().contains(m) || getBlocks().contains(m))) { + ma.add(m); + } } - return ma; } - + /** * @return Returns the type name as a string. */ public String getName() { return name; } - + public ArrayList getItems() { return items; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/CrazyManager.java b/src/main/java/com/badbones69/crazyauctions/api/CrazyAuctions.java similarity index 69% rename from src/main/java/com/badbones69/crazyauctions/api/CrazyManager.java rename to src/main/java/com/badbones69/crazyauctions/api/CrazyAuctions.java index 230f201..4045c0e 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/CrazyManager.java +++ b/src/main/java/com/badbones69/crazyauctions/api/CrazyAuctions.java @@ -1,24 +1,29 @@ package com.badbones69.crazyauctions.api; import com.badbones69.crazyauctions.api.FileManager.Files; -import com.badbones69.crazyauctions.api.enums.ShopCategories; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; + import java.util.ArrayList; -public class CrazyManager { - +public class CrazyAuctions { + + private static CrazyAuctions instance = new CrazyAuctions(); + private FileManager fileManager = FileManager.getInstance(); private Boolean sellingEnabled; private Boolean biddingEnabled; - - public void load() { + + public static CrazyAuctions getInstance() { + return instance; + } + + public void loadCrazyAuctions() { if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Selling")) { this.sellingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Selling"); } else { this.sellingEnabled = true; } - if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Bidding")) { this.biddingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Bidding"); } else { @@ -37,32 +42,35 @@ public class CrazyManager { public ArrayList getItems(Player player) { FileConfiguration data = Files.DATA.getFile(); ArrayList items = new ArrayList<>(); - if (data.contains("Items")) { for (String i : data.getConfigurationSection("Items").getKeys(false)) { - if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) items.add(data.getItemStack("Items." + i + ".Item").clone()); + if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { + items.add(data.getItemStack("Items." + i + ".Item").clone()); + } } } - return items; } - public ArrayList getItems(Player player, ShopCategories type) { + public ArrayList getItems(Player player, ShopType type) { FileConfiguration data = Files.DATA.getFile(); ArrayList items = new ArrayList<>(); - if (data.contains("Items")) { for (String i : data.getConfigurationSection("Items").getKeys(false)) { if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { if (data.getBoolean("Items." + i + ".Biddable")) { - if (type == ShopCategories.BID) items.add(data.getItemStack("Items." + i + ".Item").clone()); + if (type == ShopType.BID) { + items.add(data.getItemStack("Items." + i + ".Item").clone()); + } } else { - if (type == ShopCategories.SELL) items.add(data.getItemStack("Items." + i + ".Item").clone()); + if (type == ShopType.SELL) { + items.add(data.getItemStack("Items." + i + ".Item").clone()); + } } } } } - return items; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/FileManager.java b/src/main/java/com/badbones69/crazyauctions/api/FileManager.java index 8e1691d..329f39a 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/FileManager.java +++ b/src/main/java/com/badbones69/crazyauctions/api/FileManager.java @@ -1,8 +1,11 @@ package com.badbones69.crazyauctions.api; -import com.badbones69.crazyauctions.CrazyAuctions; +import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -11,107 +14,110 @@ import java.util.ArrayList; import java.util.HashMap; /** + * * @author BadBones69 * @version v1.0 + * */ public class FileManager { - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); + private static FileManager instance = new FileManager(); + private Plugin plugin; + private String prefix = ""; + private Boolean log = false; + private HashMap files = new HashMap<>(); + private ArrayList homeFolders = new ArrayList<>(); + private ArrayList customFiles = new ArrayList<>(); + private HashMap autoGenerateFiles = new HashMap<>(); + private HashMap configurations = new HashMap<>(); - private boolean log = false; - - private final HashMap files = new HashMap<>(); - private final ArrayList homeFolders = new ArrayList<>(); - private final ArrayList customFiles = new ArrayList<>(); - private final HashMap jarHomeFolders = new HashMap<>(); - private final HashMap autoGenerateFiles = new HashMap<>(); - private final HashMap configurations = new HashMap<>(); + public static FileManager getInstance() { + return instance; + } /** - * Loads all necessary files. + * Sets up the plugin and loads all necessary files. + * @param plugin The plugin this is getting loading for. */ - public FileManager setup() { - if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs(); - + public FileManager setup(Plugin plugin) { + prefix = "[" + plugin.getName() + "] "; + this.plugin = plugin; + if (!plugin.getDataFolder().exists()) { + plugin.getDataFolder().mkdirs(); + } files.clear(); customFiles.clear(); - - // Loads all the normal static files. + //Loads all the normal static files. for (Files file : Files.values()) { File newFile = new File(plugin.getDataFolder(), file.getFileLocation()); - - if (isLogging()) plugin.getLogger().info("Loading the " + file.getFileName()); - + if (log) Bukkit.getLogger().info("Loading the " + file.getFileName()); if (!newFile.exists()) { try { + String fileLocation = file.getFileLocation(); + //Switch between 1.12.2- and 1.13+ config version. + if (file == Files.CONFIG) { + if (Version.isOlder(Version.v1_13_R2)) { + fileLocation = "config1.12.2-Down.yml"; + } else { + fileLocation = "config1.13-Up.yml"; + } + } File serverFile = new File(plugin.getDataFolder(), "/" + file.getFileLocation()); - InputStream jarFile = getClass().getResourceAsStream("/" + file.getFileJar()); + InputStream jarFile = getClass().getResourceAsStream("/" + fileLocation); copyFile(jarFile, serverFile); } catch (Exception e) { - if (isLogging()) plugin.getLogger().info("Failed to load " + file.getFileName()); - + if (log) Bukkit.getLogger().info("Failed to load " + file.getFileName()); e.printStackTrace(); continue; } } - files.put(file, newFile); configurations.put(file, YamlConfiguration.loadConfiguration(newFile)); - - if (isLogging()) plugin.getLogger().info("Successfully loaded " + file.getFileName()); + if (log) Bukkit.getLogger().info("Successfully loaded " + file.getFileName()); } - - // Starts to load all the custom files. + //Starts to load all the custom files. if (homeFolders.size() > 0) { - if (isLogging()) plugin.getLogger().info("Loading custom files."); - + if (log) Bukkit.getLogger().info("Loading custom files."); for (String homeFolder : homeFolders) { File homeFile = new File(plugin.getDataFolder(), "/" + homeFolder); - if (homeFile.exists()) { String[] list = homeFile.list(); - if (list != null) { for (String name : list) { if (name.endsWith(".yml")) { - CustomFile file = new CustomFile(name, homeFolder); - + CustomFile file = new CustomFile(name, homeFolder, plugin); if (file.exists()) { customFiles.add(file); - - if (isLogging()) plugin.getLogger().info("Loaded new custom file: " + homeFolder + "/" + name + "."); + if (log) Bukkit.getLogger().info("Loaded new custom file: " + homeFolder + "/" + name + "."); } } } } + } else { homeFile.mkdir(); - if (isLogging()) plugin.getLogger().info("The folder " + homeFolder + "/ was not found so it was created."); - + if (log) Bukkit.getLogger().info("The folder " + homeFolder + "/ was not found so it was created."); for (String fileName : autoGenerateFiles.keySet()) { if (autoGenerateFiles.get(fileName).equalsIgnoreCase(homeFolder)) { homeFolder = autoGenerateFiles.get(fileName); - try { File serverFile = new File(plugin.getDataFolder(), homeFolder + "/" + fileName); InputStream jarFile = getClass().getResourceAsStream(homeFolder + "/" + fileName); copyFile(jarFile, serverFile); - - if (fileName.toLowerCase().endsWith(".yml")) customFiles.add(new CustomFile(fileName, homeFolder)); - - if (isLogging()) plugin.getLogger().info("Created new default file: " + homeFolder + "/" + fileName + "."); + if (fileName.toLowerCase().endsWith(".yml")) { + customFiles.add(new CustomFile(fileName, homeFolder, plugin)); + } + if (log) Bukkit.getLogger().info("Created new default file: " + homeFolder + "/" + fileName + "."); } catch (Exception e) { - if (isLogging()) plugin.getLogger().info("Failed to create new default file: " + homeFolder + "/" + fileName + "!"); + if (log) Bukkit.getLogger().info("Failed to create new default file: " + homeFolder + "/" + fileName + "!"); e.printStackTrace(); } } } } } - - if (isLogging()) plugin.getLogger().info("Finished loading custom files."); + if (log) Bukkit.getLogger().info("Finished loading custom files."); } - return this; } @@ -119,7 +125,7 @@ public class FileManager { * Turn on the logger system for the FileManager. * @param log True to turn it on and false for it to be off. */ - public FileManager setLog(boolean log) { + public FileManager logInfo(Boolean log) { this.log = log; return this; } @@ -128,7 +134,7 @@ public class FileManager { * Check if the logger is logging in console. * @return True if it is and false if it isn't. */ - public boolean isLogging() { + public Boolean isLogging() { return log; } @@ -185,21 +191,42 @@ public class FileManager { */ public CustomFile getFile(String name) { for (CustomFile file : customFiles) { - if (file.getName().equalsIgnoreCase(name)) return file; + if (file.getName().equalsIgnoreCase(name)) { + return file; + } } - return null; } /** * Saves the file from the loaded state to the file system. */ - public void saveFile(Files file) { + public void saveFile(Files file, boolean sync) { try { - configurations.get(file).save(files.get(file)); - } catch (IOException e) { - plugin.getLogger().warning("Could not save " + file.getFileName() + "!"); - + File targetFile = files.get(file); + FileConfiguration configuration = configurations.get(file); + + YamlConfiguration copy = new YamlConfiguration(); + configuration.getValues(false).forEach(copy :: set); + + BukkitRunnable runnable = new BukkitRunnable() { + @Override + public void run() { + try { + copy.save(targetFile); + } catch (IOException e) { + Bukkit.getLogger().info("Could not save " + file.getFileName() + "!"); + e.printStackTrace(); + } + } + }; + if (sync) { + runnable.run(); + } else { + runnable.runTaskAsynchronously(plugin); + } + } catch (NullPointerException e) { + Bukkit.getLogger().info("File is null " + file.getFileName() + "!"); e.printStackTrace(); } } @@ -210,18 +237,16 @@ public class FileManager { */ public void saveFile(String name) { CustomFile file = getFile(name); - if (file != null) { try { file.getFile().save(new File(plugin.getDataFolder(), file.getHomeFolder() + "/" + file.getFileName())); - - if (isLogging()) plugin.getLogger().info("Successfully saved the " + file.getFileName() + "."); + if (log) Bukkit.getLogger().info("Successfuly saved the " + file.getFileName() + "."); } catch (Exception e) { - plugin.getLogger().warning("Could not save " + file.getFileName() + "!"); + Bukkit.getLogger().info("Could not save " + file.getFileName() + "!"); e.printStackTrace(); } } else { - if (isLogging()) plugin.getLogger().warning("The file " + name + ".yml could not be found!"); + if (log) Bukkit.getLogger().info("The file " + name + ".yml could not be found!"); } } @@ -230,7 +255,7 @@ public class FileManager { * @param file The custom file you are saving. * @return True if the file saved correct and false if there was an error. */ - public boolean saveFile(CustomFile file) { + public Boolean saveFile(CustomFile file) { return file.saveFile(); } @@ -246,18 +271,16 @@ public class FileManager { */ public void reloadFile(String name) { CustomFile file = getFile(name); - if (file != null) { try { file.file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + file.getHomeFolder() + "/" + file.getFileName())); - - if (isLogging()) plugin.getLogger().info("Successfully reloaded the " + file.getFileName() + "."); + if (log) Bukkit.getLogger().info("Successfuly reload the " + file.getFileName() + "."); } catch (Exception e) { - plugin.getLogger().warning("Could not reload the " + file.getFileName() + "!"); + Bukkit.getLogger().info("Could not reload the " + file.getFileName() + "!"); e.printStackTrace(); } } else { - if (isLogging()) plugin.getLogger().warning("The file " + name + ".yml could not be found!"); + if (log) Bukkit.getLogger().info("The file " + name + ".yml could not be found!"); } } @@ -265,70 +288,47 @@ public class FileManager { * Overrides the loaded state file and loads the filesystems file. * @return True if it reloaded correct and false if the file wasn't found. */ - public boolean reloadFile(CustomFile file) { + public Boolean reloadFile(CustomFile file) { return file.reloadFile(); } - + /** - * Was found here: ... + * Was found here: https://bukkit.org/threads/extracting-file-from-jar.16962 */ private void copyFile(InputStream in, File out) throws Exception { - try (InputStream fis = in; FileOutputStream fos = new FileOutputStream(out)) { + try (FileOutputStream fos = new FileOutputStream(out)) { byte[] buf = new byte[1024]; int i; - - while ((i = fis.read(buf)) != -1) { + while ((i = in.read(buf)) != -1) { fos.write(buf, 0, i); } - } - } - - public void reloadAllFiles() { - for (Files file : Files.values()) { - file.reloadFile(); - } - - for (CustomFile file : customFiles) { - file.reloadFile(); + } finally { + if (in != null) { + in.close(); + } + } } public enum Files { - - // ENUM_NAME("fileName.yml", "fileLocation.yml"), - // ENUM_NAME("fileName.yml", "newFileLocation.yml", "oldFileLocation.yml"), + + //ENUM_NAME("FileName.yml", "FilePath.yml"), CONFIG("config.yml", "config.yml"), - DATA("data.yml", "data.yml"), - MESSAGES("messages.yml", "messages.yml"), - TEST_FILE("test-file.yml", "test-file.yml"); - + DATA("Data.yml", "Data.yml"), + MESSAGES("Messages.yml", "Messages.yml"), + TEST_FILE("Test-File.yml", "Test-File.yml"); + private final String fileName; - private final String fileJar; private final String fileLocation; - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - private final FileManager fileManager = plugin.getStarter().getFileManager(); - + /** * The files that the server will try and load. * @param fileName The file name that will be in the plugin's folder. - * @param fileLocation The location the file in the plugin's folder. + * @param fileLocation The location the file is in while in the Jar. */ - Files(String fileName, String fileLocation) { - this(fileName, fileLocation, fileLocation); - } - - /** - * The files that the server will try and load. - * @param fileName The file name that will be in the plugin's folder. - * @param fileLocation The location of the file will be in the plugin's folder. - * @param fileJar The location of the file in the jar. - */ - Files(String fileName, String fileLocation, String fileJar) { + private Files(String fileName, String fileLocation) { this.fileName = fileName; this.fileLocation = fileLocation; - this.fileJar = fileJar; } /** @@ -346,57 +346,54 @@ public class FileManager { public String getFileLocation() { return fileLocation; } - - /** - * Get the location of the file in the jar. - * @return The location of the file in the jar. - */ - public String getFileJar() { - return fileJar; - } - + /** * Gets the file from the system. * @return The file from the system. */ public FileConfiguration getFile() { - return fileManager.getFile(this); + return getInstance().getFile(this); } /** * Saves the file from the loaded state to the file system. */ + public void saveFile(boolean sync) { + getInstance().saveFile(this, sync); + } + public void saveFile() { - fileManager.saveFile(this); + getInstance().saveFile(this, false); } /** * Overrides the loaded state file and loads the file systems file. */ - public void reloadFile() { - fileManager.reloadFile(this); + public void relaodFile() { + getInstance().reloadFile(this); } + } - + public class CustomFile { - - private final String name; - private final String fileName; - private final String homeFolder; + + private String name; + private Plugin plugin; + private String fileName; + private String homeFolder; private FileConfiguration file; - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - + /** * A custom file that is being made. * @param name Name of the file. * @param homeFolder The home folder of the file. + * @param plugin The plugin the files belong to. */ - public CustomFile(String name, String homeFolder) { + public CustomFile(String name, String homeFolder, Plugin plugin) { this.name = name.replace(".yml", ""); + this.plugin = plugin; this.fileName = name; this.homeFolder = homeFolder; - if (new File(plugin.getDataFolder(), "/" + homeFolder).exists()) { if (new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name).exists()) { file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name)); @@ -405,13 +402,11 @@ public class FileManager { } } else { new File(plugin.getDataFolder(), "/" + homeFolder).mkdir(); - - if (isLogging()) plugin.getLogger().info("The folder " + homeFolder + "/ was not found so it was created."); - + if (log) Bukkit.getLogger().info("The folder " + homeFolder + "/ was not found so it was created."); file = null; } } - + /** * Get the name of the file without the .yml part. * @return The name of the file without the .yml. @@ -419,7 +414,7 @@ public class FileManager { public String getName() { return name; } - + /** * Get the full name of the file. * @return Full name of the file. @@ -427,7 +422,7 @@ public class FileManager { public String getFileName() { return fileName; } - + /** * Get the name of the home folder of the file. * @return The name of the home folder the files are in. @@ -435,7 +430,15 @@ public class FileManager { public String getHomeFolder() { return homeFolder; } - + + /** + * Get the plugin the file belongs to. + * @return The plugin the file belongs to. + */ + public Plugin getPlugin() { + return plugin; + } + /** * Get the ConfigurationFile. * @return The ConfigurationFile of this file. @@ -443,7 +446,7 @@ public class FileManager { public FileConfiguration getFile() { return file; } - + /** * Check if the file actually exists in the file system. * @return True if it does and false if it doesn't. @@ -451,7 +454,7 @@ public class FileManager { public Boolean exists() { return file != null; } - + /** * Save the custom file. * @return True if it saved correct and false if something went wrong. @@ -460,43 +463,39 @@ public class FileManager { if (file != null) { try { file.save(new File(plugin.getDataFolder(), homeFolder + "/" + fileName)); - - if (isLogging()) plugin.getLogger().info("Successfully saved the " + fileName + "."); - + if (log) Bukkit.getLogger().info("Successfuly saved the " + fileName + "."); return true; } catch (Exception e) { - plugin.getLogger().warning("Could not save " + fileName + "!"); + Bukkit.getLogger().info("Could not save " + fileName + "!"); e.printStackTrace(); return false; } } else { - if (isLogging()) plugin.getLogger().warning("There was a null custom file that could not be found!"); + if (log) Bukkit.getLogger().info("There was a null custom file that could not be found!"); } - return false; } - + /** * Overrides the loaded state file and loads the filesystems file. - * @return True if it reloaded correct and false if the file wasn't found or error. + * @return True if it reloaded correct and false if the file wasn't found or errored. */ public Boolean reloadFile() { if (file != null) { try { file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + fileName)); - - if (isLogging()) plugin.getLogger().info("Successfully reloaded the " + fileName + "."); - + if (log) Bukkit.getLogger().info("Successfuly reload the " + fileName + "."); return true; } catch (Exception e) { - plugin.getLogger().warning("Could not reload the " + fileName + "!"); + Bukkit.getLogger().info("Could not reload the " + fileName + "!"); e.printStackTrace(); } } else { - if (isLogging()) plugin.getLogger().warning("There was a null custom file that was not found!"); + if (log) Bukkit.getLogger().info("There was a null custom file that was not found!"); } - return false; } + } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/enums/Messages.java b/src/main/java/com/badbones69/crazyauctions/api/Messages.java similarity index 77% rename from src/main/java/com/badbones69/crazyauctions/api/enums/Messages.java rename to src/main/java/com/badbones69/crazyauctions/api/Messages.java index 2bfe4ce..23be245 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/enums/Messages.java +++ b/src/main/java/com/badbones69/crazyauctions/api/Messages.java @@ -1,8 +1,6 @@ -package com.badbones69.crazyauctions.api.enums; +package com.badbones69.crazyauctions.api; -import com.badbones69.crazyauctions.CrazyAuctions; import com.badbones69.crazyauctions.Methods; -import com.badbones69.crazyauctions.api.FileManager; import com.badbones69.crazyauctions.api.FileManager.Files; import org.bukkit.configuration.file.FileConfiguration; @@ -56,54 +54,47 @@ public enum Messages { "&9/Ah Expired/Collect - &eView and manage your cancelled and expired items.", "&9/Ah Listed - &eView and manage the items you are selling.", "&9/Ah Help - &eView this help menu.")); + + private static final FileManager fileManager = FileManager.getInstance(); private final String path; private String defaultMessage; private List defaultListMessage; - - private static final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - private static final Methods methods = plugin.getStarter().getMethods(); - Messages(String path, String defaultMessage) { + private Messages(String path, String defaultMessage) { this.path = path; this.defaultMessage = defaultMessage; } - Messages(String path, List defaultListMessage) { + private Messages(String path, List defaultListMessage) { this.path = path; this.defaultListMessage = defaultListMessage; } public static String convertList(List list) { - StringBuilder message = new StringBuilder(); - + String message = ""; for (String m : list) { - message.append(methods.color(m)).append("\n"); + message += Methods.color(m) + "\n"; } - - return message.toString(); + return message; } public static String convertList(List list, HashMap placeholders) { - StringBuilder message = new StringBuilder(); + String message = ""; for (String m : list) { - message.append(methods.color(m)).append("\n"); + message += Methods.color(m) + "\n"; } - for (String ph : placeholders.keySet()) { - message = new StringBuilder(methods.color(message.toString().replace(ph, placeholders.get(ph))).replace(ph, placeholders.get(ph).toLowerCase())); + message = Methods.color(message.replace(ph, placeholders.get(ph))).replace(ph, placeholders.get(ph).toLowerCase()); } - return message.toString(); + return message; } public static void addMissingMessages() { FileConfiguration messages = Files.MESSAGES.getFile(); boolean saveFile = false; - for (Messages message : values()) { if (!messages.contains("Messages." + message.getPath())) { saveFile = true; - if (message.getDefaultMessage() != null) { messages.set("Messages." + message.getPath(), message.getDefaultMessage()); } else { @@ -111,22 +102,23 @@ public enum Messages { } } } - - if (saveFile) Files.MESSAGES.saveFile(); + if (saveFile) { + Files.MESSAGES.saveFile(); + } } public String getMessage() { if (isList()) { if (exists()) { - return methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); + return Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); } else { - return methods.color(convertList(getDefaultListMessage())); + return Methods.color(convertList(getDefaultListMessage())); } } else { if (exists()) { - return methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); + return Methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); } else { - return methods.getPrefix(getDefaultMessage()); + return Methods.getPrefix(getDefaultMessage()); } } } @@ -135,18 +127,20 @@ public enum Messages { String message; if (isList()) { if (exists()) { - message = methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); + message = Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); } else { - message = methods.color(convertList(getDefaultListMessage(), placeholders)); + message = Methods.color(convertList(getDefaultListMessage(), placeholders)); } } else { if (exists()) { - message = methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); + message = Methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); } else { - message = methods.getPrefix(getDefaultMessage()); + message = Methods.getPrefix(getDefaultMessage()); } for (String ph : placeholders.keySet()) { - if (message.contains(ph)) message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase()); + if (message.contains(ph)) { + message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase()); + } } } return message; @@ -155,15 +149,15 @@ public enum Messages { public String getMessageNoPrefix() { if (isList()) { if (exists()) { - return methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); + return Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); } else { - return methods.color(convertList(getDefaultListMessage())); + return Methods.color(convertList(getDefaultListMessage())); } } else { if (exists()) { - return methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); + return Methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); } else { - return methods.color(getDefaultMessage()); + return Methods.color(getDefaultMessage()); } } } @@ -172,18 +166,20 @@ public enum Messages { String message; if (isList()) { if (exists()) { - message = methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); + message = Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); } else { - message = methods.color(convertList(getDefaultListMessage(), placeholders)); + message = Methods.color(convertList(getDefaultListMessage(), placeholders)); } } else { if (exists()) { - message = methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); + message = Methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); } else { - message = methods.color(getDefaultMessage()); + message = Methods.color(getDefaultMessage()); } for (String ph : placeholders.keySet()) { - if (message.contains(ph)) message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase()); + if (message.contains(ph)) { + message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase()); + } } } return message; @@ -212,4 +208,5 @@ public enum Messages { private List getDefaultListMessage() { return defaultListMessage; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/ShopType.java b/src/main/java/com/badbones69/crazyauctions/api/ShopType.java new file mode 100644 index 0000000..3c3e4ce --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/api/ShopType.java @@ -0,0 +1,36 @@ +package com.badbones69.crazyauctions.api; + +public enum ShopType { + + SELL("Sell"), BID("Bid"); + + private final String name; + + /** + * @param name name of the Shop Type. + */ + private ShopType(String name) { + this.name = name; + } + + /** + * @param name name of the Type you want. + * @return Returns the Type as an Enum. + */ + public static ShopType getFromName(String name) { + for (ShopType type : ShopType.values()) { + if (type.getName().equalsIgnoreCase(name)) { + return type; + } + } + return null; + } + + /** + * @return Returns the type name as a string. + */ + public String getName() { + return name; + } + +} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/Version.java b/src/main/java/com/badbones69/crazyauctions/api/Version.java new file mode 100644 index 0000000..7b57a9d --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/api/Version.java @@ -0,0 +1,128 @@ +package com.badbones69.crazyauctions.api; + +import org.bukkit.Bukkit; + +public enum Version { + + TOO_OLD(-1), + v1_7_R1(171), v1_7_R2(172), v1_7_R3(173), v1_7_R4(174), + v1_8_R1(181), v1_8_R2(182), v1_8_R3(183), + v1_9_R1(191), v1_9_R2(192), + v1_10_R1(1101), + v1_11_R1(1111), + v1_12_R1(1121), + v1_13_R2(1132), + v1_14_R1(1141), + v1_15_R1(1151), + v1_16_R1(1161), v1_16_R2(1162), v1_16_R3(1163), + TOO_NEW(-2); + + private static Version currentVersion; + private static Version latest; + private final int versionInteger; + + private Version(int versionInteger) { + this.versionInteger = versionInteger; + } + + /** + * + * @return Get the server's Minecraft version. + */ + public static Version getCurrentVersion() { + if (currentVersion == null) { + String ver = Bukkit.getServer().getClass().getPackage().getName(); + int v = Integer.parseInt(ver.substring(ver.lastIndexOf('.') + 1).replace("_", "").replace("R", "").replace("v", "")); + for (Version version : values()) { + if (version.getVersionInteger() == v) { + currentVersion = version; + break; + } + } + if (v > Version.getLatestVersion().getVersionInteger()) { + currentVersion = Version.getLatestVersion(); + } + if (currentVersion == null) { + currentVersion = Version.TOO_NEW; + } + } + return currentVersion; + } + + /** + * Get the latest version allowed by the Version class. + * @return The latest version. + */ + public static Version getLatestVersion() { + if (latest == null) { + Version v = Version.TOO_OLD; + for (Version version : values()) { + if (version.comparedTo(v) == 1) { + v = version; + } + } + return v; + } else { + return latest; + + } + } + + /** + * + * @return The server's minecraft version as an integer. + */ + public int getVersionInteger() { + return this.versionInteger; + } + + /** + * This checks if the current version is older, newer, or is the checked version. + * @param version The version you are checking. + * @return -1 if older, 0 if the same, and 1 if newer. + */ + public int comparedTo(Version version) { + int result = -1; + int current = this.getVersionInteger(); + int check = version.getVersionInteger(); + if (current > check || check == -2) {// check is newer then current + result = 1; + } else if (current == check) {// check is the same as current + result = 0; + } else if (check == -1) {// check is older then current + result = -1; + } + return result; + } + + /** + * Checks to see if the current version is newer then the checked version. + * @param version The version you are checking. + * @return True if newer then the checked version and false if the same or older. + */ + public static boolean isNewer(Version version) { + if (currentVersion == null) getCurrentVersion(); + return currentVersion.versionInteger > version.versionInteger || currentVersion.versionInteger == -2; + } + + /** + * Checks to see if the current version is the same as the checked version. + * @param version The version you are checking. + * @return True if both the current and checked version is the same and false if otherwise. + */ + public static boolean isSame(Version version) { + if (currentVersion == null) getCurrentVersion(); + return currentVersion.versionInteger == version.versionInteger; + } + + /** + * Checks to see if the current version is older than the checked version. + * @param version The version you are checking. + * @return True if older than the checked version and false if the same or newer. + */ + public static boolean isOlder(Version version) { + if (currentVersion == null) getCurrentVersion(); + return currentVersion.versionInteger < version.versionInteger || currentVersion.versionInteger == -1; + } + +} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/economy/Currency.java b/src/main/java/com/badbones69/crazyauctions/api/economy/Currency.java deleted file mode 100644 index dadec63..0000000 --- a/src/main/java/com/badbones69/crazyauctions/api/economy/Currency.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.badbones69.crazyauctions.api.economy; - -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; - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/economy/CurrencyAPI.java b/src/main/java/com/badbones69/crazyauctions/api/economy/CurrencyAPI.java deleted file mode 100644 index cf760bc..0000000 --- a/src/main/java/com/badbones69/crazyauctions/api/economy/CurrencyAPI.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.badbones69.crazyauctions.api.economy; - -import com.badbones69.crazyauctions.CrazyAuctions; -import com.badbones69.crazyauctions.api.economy.vault.VaultSupport; -import com.badbones69.crazyauctions.api.enums.ShopCategories; -import org.bukkit.entity.Player; - -public class CurrencyAPI { - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - private final VaultSupport vaultSupport = plugin.getStarter().getVaultSupport(); - - /** - * Get the amount that a player has from a specific currency. - * @param player The player you wish to get the amount from. - * @param currency The currency you wish to get from. - * @return The amount that the player has of that currency. - */ - public int getCurrency(Player player, Currency currency) { - try { - switch (currency) { - case VAULT: - vaultSupport.getVault().getBalance(player); - break; - case XP_LEVEL: - player.getLevel(); - break; - case XP_TOTAL: - getTotalExperience(player); - break; - } - } catch (Exception | NoClassDefFoundError ignored) {} - return 0; - } - - /** - * Take an amount from a player's currency. - * @param player The player you wish to take from. - * @param option The ShopOption you wish to use. - */ - public void takeCurrency(Player player, ShopCategories option) { - // takeCurrency(player, option.getCurrency(), option.getCost()); - } - - /** - * Take an amount from a player's currency. - * @param player The player you wish to take from. - * @param currency The currency you wish to use. - * @param amount The amount you want to take. - */ - public void takeCurrency(Player player, Currency currency, int amount) { - try { - switch (currency) { - case VAULT: - vaultSupport.getVault().withdrawPlayer(player, amount); - break; - case XP_LEVEL: - player.setLevel(player.getLevel() - amount); - break; - case XP_TOTAL: - takeTotalExperience(player, amount); - break; - } - } catch (Exception | NoClassDefFoundError ignored) {} - } - - /** - * Give an amount to a player's currency. - * @param player The player you are giving to. - * @param currency The currency you want to use. - * @param amount The amount you are giving to the player. - */ - public void giveCurrency(Player player, Currency currency, int amount) { - try { - switch (currency) { - case VAULT: - vaultSupport.getVault().depositPlayer(player, amount); - break; - case XP_LEVEL: - player.setLevel(player.getLevel() + amount); - break; - case XP_TOTAL: - takeTotalExperience(player, -amount); - break; - } - } catch (Exception | NoClassDefFoundError ignored) {} - } - - /** - * Checks if the player has enough of a currency. - * @param player The player you are checking. - * @param option The ShopOption you wish to check. - * @return True if they have enough to buy it or false if they don't. - */ - public boolean canBuy(Player player, ShopCategories option) { - return canBuy(player, option.getCurrency(), option.getCost()); - } - - /** - * Checks if the player has enough of a currency. - * @param player The player you are checking. - * @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(Player player, Currency currency, int cost) { - return getCurrency(player, 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; - } - } - - /** - * Loads the vault currency if it is on the server. - */ - public void loadCurrency() { - vaultSupport.loadVault(); - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/economy/vault/VaultSupport.java b/src/main/java/com/badbones69/crazyauctions/api/economy/vault/VaultSupport.java deleted file mode 100644 index b5d80f1..0000000 --- a/src/main/java/com/badbones69/crazyauctions/api/economy/vault/VaultSupport.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.badbones69.crazyauctions.api.economy.vault; - -import com.badbones69.crazyauctions.CrazyAuctions; -import com.badbones69.crazyauctions.utils.func.PluginSupport; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.plugin.RegisteredServiceProvider; - -public class VaultSupport { - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - private Economy vault = null; - - public Economy getVault() { - return vault; - } - - public void loadVault() { - if (PluginSupport.VAULT.isPluginLoaded()) { - RegisteredServiceProvider rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class); - - if (rsp != null) vault = rsp.getProvider(); - } - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/enums/CancelledReason.java b/src/main/java/com/badbones69/crazyauctions/api/enums/CancelledReason.java index 12da0b2..206adf1 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/enums/CancelledReason.java +++ b/src/main/java/com/badbones69/crazyauctions/api/enums/CancelledReason.java @@ -10,4 +10,5 @@ public enum CancelledReason { * Cancelled by the player them self. */ PLAYER_FORCE_CANCEL() + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/enums/ShopCategories.java b/src/main/java/com/badbones69/crazyauctions/api/enums/ShopCategories.java deleted file mode 100644 index e2d84d3..0000000 --- a/src/main/java/com/badbones69/crazyauctions/api/enums/ShopCategories.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.badbones69.crazyauctions.api.enums; - -import com.badbones69.crazyauctions.api.economy.Currency; -import com.badbones69.crazyauctions.utils.ItemBuilder; - -import java.util.HashMap; - -public enum ShopCategories { - - SELL("Sell"), - BID("Bid"); - - private final String name; - - private final HashMap shopCategories = new HashMap<>(); - - /** - * @param name name of the Shop Type. - */ - ShopCategories(String name) { - this.name = name; - } - - /** - * @param name name of the Type you want. - * @return Returns the Type as an Enum. - */ - public static ShopCategories getFromName(String name) { - for (ShopCategories type : ShopCategories.values()) { - if (type.getName().equalsIgnoreCase(name)) return type; - } - - return null; - } - - public Currency getCurrency() { - return shopCategories.get(this).currency; - } - - public int getCost() { - return shopCategories.get(this).cost; - } - - /** - * @return Returns the type name as a string. - */ - public String getName() { - return name; - } - - private static class Options { - - private final ItemBuilder itemBuilder; - - private final int slot; - private final boolean inMenu; - private int cost; - private final Currency currency; - - public Options(ItemBuilder itemBuilder, int slot, boolean inMenu, int cost, Currency currency) { - this.itemBuilder = itemBuilder; - this.slot = slot; - this.inMenu = inMenu; - this.cost = cost; - this.currency = currency; - } - - public ItemBuilder getItemBuilder() { - return itemBuilder; - } - - public int getSlot() { - return slot; - } - - public int getCost() { - return cost; - } - - public Currency getCurrency() { - return currency; - } - - public boolean isInMenu() { - return inMenu; - } - - public void setCost(int cost) { - this.cost = cost; - } - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionBuyEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionBuyEvent.java index 4da1a46..ed32bfa 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionBuyEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionBuyEvent.java @@ -6,18 +6,21 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * @author BadBones69 * * This event is fired when a player buys something from the selling auction house. + * */ public class AuctionBuyEvent extends Event { - private final HandlerList handlers = new HandlerList(); - private final Player player; - private final long price; - private final ItemStack item; + private static final HandlerList handlers = new HandlerList(); + private Player player; + private long price; + private ItemStack item; /** + * * @param player The player who bought the item. * @param item The item that was bought. * @param price The price of the item. @@ -27,7 +30,11 @@ public class AuctionBuyEvent extends Event { this.item = item; this.price = price; } - + + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -43,4 +50,5 @@ public class AuctionBuyEvent extends Event { public long getPrice() { return price; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionCancelledEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionCancelledEvent.java index fe13b63..fb013e2 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionCancelledEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionCancelledEvent.java @@ -8,20 +8,23 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * @author BadBones69 * * This event is fired when a player's item is cancelled. + * */ public class AuctionCancelledEvent extends Event { - private final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); private OfflinePlayer offlinePlayer; private Player onlinePlayer; - private final boolean isOnline; - private final ItemStack item; - private final CancelledReason reason; + private boolean isOnline; + private ItemStack item; + private CancelledReason reason; /** + * * @param offlinePlayer The player whose item is cancelled. * @param item The item that is cancelled. */ @@ -33,6 +36,7 @@ public class AuctionCancelledEvent extends Event { } /** + * * @param onlinePlayer The player whose item is cancelled. * @param item The item that is cancelled. */ @@ -43,6 +47,10 @@ public class AuctionCancelledEvent extends Event { this.reason = reason; } + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -66,4 +74,5 @@ public class AuctionCancelledEvent extends Event { public CancelledReason getReason() { return reason; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionExpireEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionExpireEvent.java index 5102904..9a99ed5 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionExpireEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionExpireEvent.java @@ -7,19 +7,22 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * @author BadBones69 * * This event is fired when a player item expires. + * */ public class AuctionExpireEvent extends Event { - private final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); private OfflinePlayer offlinePlayer; private Player onlinePlayer; - private final boolean isOnline; - private final ItemStack item; + private boolean isOnline; + private ItemStack item; /** + * * @param offlinePlayer The player whose item is expiring. * @param item The item that is expiring. */ @@ -30,6 +33,7 @@ public class AuctionExpireEvent extends Event { } /** + * * @param onlinePlayer The player whose item is expiring. * @param item The item that is expiring. */ @@ -39,6 +43,10 @@ public class AuctionExpireEvent extends Event { this.isOnline = true; } + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -58,4 +66,5 @@ public class AuctionExpireEvent extends Event { public ItemStack getItem() { return item; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionListEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionListEvent.java index 2d7895f..743ea14 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionListEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionListEvent.java @@ -1,37 +1,44 @@ package com.badbones69.crazyauctions.api.events; -import com.badbones69.crazyauctions.api.enums.ShopCategories; +import com.badbones69.crazyauctions.api.ShopType; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * @author BadBones69 * * This event is fired when a new item is listed onto the auction house. + * */ public class AuctionListEvent extends Event { - private final HandlerList handlers = new HandlerList(); - private final Player player; - private final long price; - private final ShopCategories shop; - private final ItemStack item; + private static final HandlerList handlers = new HandlerList(); + private Player player; + private long price; + private ShopType shop; + private ItemStack item; /** + * * @param player The player who is listing the item. * @param shop The shop type the item is being listed to. * @param item The item being listed. * @param price The price the item is being listed for. */ - public AuctionListEvent(Player player, ShopCategories shop, ItemStack item, long price) { + public AuctionListEvent(Player player, ShopType shop, ItemStack item, long price) { this.player = player; this.shop = shop; this.item = item; this.price = price; } + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -40,7 +47,7 @@ public class AuctionListEvent extends Event { return player; } - public ShopCategories getShopType() { + public ShopType getShopType() { return shop; } @@ -51,4 +58,5 @@ public class AuctionListEvent extends Event { public long getPrice() { return price; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionNewBidEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionNewBidEvent.java index 5c5bb99..0b391f1 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionNewBidEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionNewBidEvent.java @@ -6,16 +6,18 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * This event is fired when a player places a new bid onto an item in the auction house. */ public class AuctionNewBidEvent extends Event { - private final HandlerList handlers = new HandlerList(); - private final Player player; - private final long bid; - private final ItemStack item; + private static final HandlerList handlers = new HandlerList(); + private Player player; + private long bid; + private ItemStack item; /** + * * @param player The player who placed the bid. * @param item The item that was bid on. * @param bid The amount of money that was bid. @@ -26,6 +28,10 @@ public class AuctionNewBidEvent extends Event { this.bid = bid; } + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -41,4 +47,5 @@ public class AuctionNewBidEvent extends Event { public long getBid() { return bid; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionWinBidEvent.java b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionWinBidEvent.java index 0f3da3e..b91419a 100644 --- a/src/main/java/com/badbones69/crazyauctions/api/events/AuctionWinBidEvent.java +++ b/src/main/java/com/badbones69/crazyauctions/api/events/AuctionWinBidEvent.java @@ -6,18 +6,21 @@ import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; /** + * * @author BadBones69 * * This event is fired when a bidding item's time has run out and so a player wins the item. + * */ public class AuctionWinBidEvent extends Event { - private final HandlerList handlers = new HandlerList(); - private final Player player; - private final long bid; - private final ItemStack item; + private static final HandlerList handlers = new HandlerList(); + private Player player; + private long bid; + private ItemStack item; /** + * * @param player The player who won the item. * @param item The item that was won. * @param bid The bid that was placed on the item. @@ -28,6 +31,10 @@ public class AuctionWinBidEvent extends Event { this.bid = bid; } + public static HandlerList getHandlerList() { + return handlers; + } + public HandlerList getHandlers() { return handlers; } @@ -43,4 +50,5 @@ public class AuctionWinBidEvent extends Event { public long getBid() { return bid; } + } \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/controllers/DupePatch.java b/src/main/java/com/badbones69/crazyauctions/controllers/DupePatch.java new file mode 100644 index 0000000..83deb9e --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/controllers/DupePatch.java @@ -0,0 +1,22 @@ +package com.badbones69.crazyauctions.controllers; + +import com.badbones69.crazyauctions.api.FileManager; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +public class DupePatch implements Listener { + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPreCommand(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + + boolean macro = FileManager.Files.CONFIG.getFile().getBoolean("Settings.Patches.Macro-Dupe", true); + + if (!macro) return; + + if (!player.isOnline() || player.isDead()) event.setCancelled(true); + } +} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/controllers/GUI.java b/src/main/java/com/badbones69/crazyauctions/controllers/GUI.java new file mode 100644 index 0000000..bfd2d9c --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/controllers/GUI.java @@ -0,0 +1,950 @@ +package com.badbones69.crazyauctions.controllers; + +import com.badbones69.crazyauctions.Methods; +import com.badbones69.crazyauctions.api.*; +import com.badbones69.crazyauctions.api.FileManager.Files; +import com.badbones69.crazyauctions.api.enums.CancelledReason; +import com.badbones69.crazyauctions.api.events.AuctionBuyEvent; +import com.badbones69.crazyauctions.api.events.AuctionCancelledEvent; +import com.badbones69.crazyauctions.api.events.AuctionNewBidEvent; +import com.badbones69.crazyauctions.currency.CurrencyManager; +import org.bukkit.Bukkit; +import org.bukkit.Sound; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; + +public class GUI implements Listener { + + private static HashMap bidding = new HashMap<>(); + private static HashMap biddingID = new HashMap<>(); + private static HashMap shopType = new HashMap<>(); // Shop Type + private static HashMap shopCategory = new HashMap<>(); // Category Type + private static HashMap> List = new HashMap<>(); + private static HashMap IDs = new HashMap<>(); + private static CrazyAuctions crazyAuctions = CrazyAuctions.getInstance(); + private static Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("CrazyAuctions"); + + public static void openShop(Player player, ShopType sell, Category cat, int page) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + List items = new ArrayList<>(); + List ID = new ArrayList<>(); + if (!data.contains("Items")) { + data.set("Items.Clear", null); + Files.DATA.saveFile(); + } + if (cat != null) { + shopCategory.put(player, cat); + } else { + shopCategory.put(player, Category.NONE); + } + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + List lore = new ArrayList<>(); + if (data.getItemStack("Items." + i + ".Item") != null && (cat.getItems().contains(data.getItemStack("Items." + i + ".Item").getType()) || cat == Category.NONE)) { + if (data.getBoolean("Items." + i + ".Biddable")) { + if (sell == ShopType.BID) { + String seller = data.getString("Items." + i + ".Seller"); + String topbidder = data.getString("Items." + i + ".TopBidder"); + for (String l : config.getStringList("Settings.GUISettings.Bidding")) { + lore.add(l.replace("%TopBid%", Methods.getPrice(i, false)).replace("%topbid%", Methods.getPrice(i, false)).replace("%Seller%", seller).replace("%seller%", seller).replace("%TopBidder%", topbidder).replace("%topbidder%", topbidder).replace("%Time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire")))); + } + items.add(Methods.addLore(data.getItemStack("Items." + i + ".Item").clone(), lore)); + ID.add(data.getInt("Items." + i + ".StoreID")); + } + } else { + if (sell == ShopType.SELL) { + for (String l : config.getStringList("Settings.GUISettings.SellingItemLore")) { + lore.add(l.replace("%Price%", String.format(Locale.ENGLISH, "%,d", Long.parseLong(Methods.getPrice(i, false)))).replace("%price%", String.format(Locale.ENGLISH, "%,d", Long.parseLong(Methods.getPrice(i, false)))).replace("%Seller%", data.getString("Items." + i + ".Seller")).replace("%seller%", data.getString("Items." + i + ".Seller")).replace("%Time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire")))); + } + items.add(Methods.addLore(data.getItemStack("Items." + i + ".Item").clone(), lore)); + ID.add(data.getInt("Items." + i + ".StoreID")); + } + } + } + } + } + int maxPage = Methods.getMaxPage(items); + for (; page > maxPage; page--) ; + Inventory inv = Bukkit.createInventory(null, 54, Methods.color(config.getString("Settings.GUIName") + " #" + page)); + List options = new ArrayList<>(); + options.add("SellingItems"); + options.add("Cancelled/ExpiredItems"); + options.add("PreviousPage"); + options.add("Refesh"); + options.add("NextPage"); + options.add("Category1"); + options.add("Category2"); + if (sell == ShopType.SELL) { + shopType.put(player, ShopType.SELL); + if (crazyAuctions.isBiddingEnabled()) { + options.add("Bidding/Selling.Selling"); + } + options.add("WhatIsThis.SellingShop"); + } + if (sell == ShopType.BID) { + shopType.put(player, ShopType.BID); + if (crazyAuctions.isSellingEnabled()) { + options.add("Bidding/Selling.Bidding"); + } + options.add("WhatIsThis.BiddingShop"); + } + for (String o : options) { + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + if (!config.getBoolean("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + continue; + } + } + String id = config.getString("Settings.GUISettings.OtherSettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings.OtherSettings." + o + ".Name"); + List lore = new ArrayList<>(); + int slot = config.getInt("Settings.GUISettings.OtherSettings." + o + ".Slot"); + String cName = Methods.color(config.getString("Settings.GUISettings.Category-Settings." + shopCategory.get(player).getName() + ".Name")); + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + for (String l : config.getStringList("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + lore.add(l.replace("%Category%", cName).replace("%category%", cName)); + } + inv.setItem(slot - 1, Methods.makeItem(id, 1, name, lore)); + } else { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name)); + } + } + for (ItemStack item : Methods.getPage(items, page)) { + int slot = inv.firstEmpty(); + inv.setItem(slot, item); + } + List Id = new ArrayList<>(Methods.getPageInts(ID, page)); + List.put(player, Id); + player.openInventory(inv); + } + + public static void openCategories(Player player, ShopType shop) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + Inventory inv = Bukkit.createInventory(null, 54, Methods.color(config.getString("Settings.Categories"))); + List options = new ArrayList<>(); + options.add("OtherSettings.Back"); + options.add("OtherSettings.WhatIsThis.Categories"); + options.add("Category-Settings.Armor"); + options.add("Category-Settings.Weapons"); + options.add("Category-Settings.Tools"); + options.add("Category-Settings.Food"); + options.add("Category-Settings.Potions"); + options.add("Category-Settings.Blocks"); + options.add("Category-Settings.Other"); + options.add("Category-Settings.None"); + for (String o : options) { + if (config.contains("Settings.GUISettings." + o + ".Toggle")) { + if (!config.getBoolean("Settings.GUISettings." + o + ".Toggle")) { + continue; + } + } + String id = config.getString("Settings.GUISettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings." + o + ".Name"); + int slot = config.getInt("Settings.GUISettings." + o + ".Slot"); + if (config.contains("Settings.GUISettings." + o + ".Lore")) { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name, config.getStringList("Settings.GUISettings." + o + ".Lore"))); + } else { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name)); + } + } + shopType.put(player, shop); + player.openInventory(inv); + } + + public static void openPlayersCurrentList(Player player, int page) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + List items = new ArrayList<>(); + List ID = new ArrayList<>(); + Inventory inv = Bukkit.createInventory(null, 54, Methods.color(config.getString("Settings.Players-Current-Items"))); + List options = new ArrayList<>(); + options.add("Back"); + options.add("WhatIsThis.CurrentItems"); + for (String o : options) { + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + if (!config.getBoolean("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + continue; + } + } + String id = config.getString("Settings.GUISettings.OtherSettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings.OtherSettings." + o + ".Name"); + int slot = config.getInt("Settings.GUISettings.OtherSettings." + o + ".Slot"); + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name, config.getStringList("Settings.GUISettings.OtherSettings." + o + ".Lore"))); + } else { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name)); + } + } + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { + List lore = new ArrayList<>(); + for (String l : config.getStringList("Settings.GUISettings.CurrentLore")) { + lore.add(l.replace("%Price%", Methods.getPrice(i, false)).replace("%price%", Methods.getPrice(i, false)).replace("%Time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire")))); + } + items.add(Methods.addLore(data.getItemStack("Items." + i + ".Item").clone(), lore)); + ID.add(data.getInt("Items." + i + ".StoreID")); + } + } + } + for (ItemStack item : Methods.getPage(items, page)) { + int slot = inv.firstEmpty(); + inv.setItem(slot, item); + } + List Id = new ArrayList<>(Methods.getPageInts(ID, page)); + List.put(player, Id); + player.openInventory(inv); + } + + public static void openPlayersExpiredList(Player player, int page) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + List items = new ArrayList<>(); + List ID = new ArrayList<>(); + if (data.contains("OutOfTime/Cancelled")) { + for (String i : data.getConfigurationSection("OutOfTime/Cancelled").getKeys(false)) { + if (data.getString("OutOfTime/Cancelled." + i + ".Seller") != null) { + if (data.getString("OutOfTime/Cancelled." + i + ".Seller").equalsIgnoreCase(player.getName())) { + List lore = new ArrayList<>(); + for (String l : config.getStringList("Settings.GUISettings.Cancelled/ExpiredLore")) { + lore.add(l.replace("%Price%", Methods.getPrice(i, true)).replace("%price%", Methods.getPrice(i, true)).replace("%Time%", Methods.convertToTime(data.getLong("OutOfTime/Cancelled." + i + ".Full-Time"))).replace("%time%", Methods.convertToTime(data.getLong("OutOfTime/Cancelled." + i + ".Full-Time")))); + } + items.add(Methods.addLore(data.getItemStack("OutOfTime/Cancelled." + i + ".Item").clone(), lore)); + ID.add(data.getInt("OutOfTime/Cancelled." + i + ".StoreID")); + } + } + } + } + int maxPage = Methods.getMaxPage(items); + for (; page > maxPage; page--) ; + Inventory inv = Bukkit.createInventory(null, 54, Methods.color(config.getString("Settings.Cancelled/Expired-Items") + " #" + page)); + List options = new ArrayList<>(); + options.add("Back"); + options.add("PreviousPage"); + options.add("Return"); + options.add("NextPage"); + options.add("WhatIsThis.Cancelled/ExpiredItems"); + for (String o : options) { + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + if (!config.getBoolean("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + continue; + } + } + String id = config.getString("Settings.GUISettings.OtherSettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings.OtherSettings." + o + ".Name"); + int slot = config.getInt("Settings.GUISettings.OtherSettings." + o + ".Slot"); + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name, config.getStringList("Settings.GUISettings.OtherSettings." + o + ".Lore"))); + } else { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name)); + } + } + for (ItemStack item : Methods.getPage(items, page)) { + int slot = inv.firstEmpty(); + inv.setItem(slot, item); + } + List Id = new ArrayList<>(Methods.getPageInts(ID, page)); + List.put(player, Id); + player.openInventory(inv); + } + + public static void openBuying(Player player, String ID) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + if (!data.contains("Items." + ID)) { + openShop(player, ShopType.SELL, shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + Inventory inv = Bukkit.createInventory(null, 9, Methods.color(config.getString("Settings.Buying-Item"))); + List options = new ArrayList<>(); + options.add("Confirm"); + options.add("Cancel"); + for (String o : options) { + String id = config.getString("Settings.GUISettings.OtherSettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings.OtherSettings." + o + ".Name"); + ItemStack item; + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + item = Methods.makeItem(id, 1, name, config.getStringList("Settings.GUISettings.OtherSettings." + o + ".Lore")); + } else { + item = Methods.makeItem(id, 1, name); + } + if (o.equals("Confirm")) { + inv.setItem(0, item); + inv.setItem(1, item); + inv.setItem(2, item); + inv.setItem(3, item); + } + if (o.equals("Cancel")) { + inv.setItem(5, item); + inv.setItem(6, item); + inv.setItem(7, item); + inv.setItem(8, item); + } + } + ItemStack item = data.getItemStack("Items." + ID + ".Item"); + List lore = new ArrayList<>(); + for (String l : config.getStringList("Settings.GUISettings.SellingItemLore")) { + lore.add(l.replace("%Price%", Methods.getPrice(ID, false)).replace("%price%", Methods.getPrice(ID, false)).replace("%Seller%", data.getString("Items." + ID + ".Seller")).replace("%seller%", data.getString("Items." + ID + ".Seller")).replace("%Time%", Methods.convertToTime(data.getLong("Items." + l + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + l + ".Time-Till-Expire")))); + } + inv.setItem(4, Methods.addLore(item.clone(), lore)); + IDs.put(player, ID); + player.openInventory(inv); + } + + public static void openBidding(Player player, String ID) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + if (!data.contains("Items." + ID)) { + openShop(player, ShopType.BID, shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + Inventory inv = Bukkit.createInventory(null, 27, Methods.color(config.getString("Settings.Bidding-On-Item"))); + if (!bidding.containsKey(player)) bidding.put(player, 0); + if (Version.isNewer(Version.v1_12_R1)) { + inv.setItem(9, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+1")); + inv.setItem(10, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+10")); + inv.setItem(11, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+100")); + inv.setItem(12, Methods.makeItem("LIME_STAINED_GLASS_PANE", 1, "&a+1000")); + inv.setItem(14, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-1000")); + inv.setItem(15, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-100")); + inv.setItem(16, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-10")); + inv.setItem(17, Methods.makeItem("RED_STAINED_GLASS_PANE", 1, "&c-1")); + } else { + inv.setItem(9, Methods.makeItem("160:5", 1, "&a+1")); + inv.setItem(10, Methods.makeItem("160:5", 1, "&a+10")); + inv.setItem(11, Methods.makeItem("160:5", 1, "&a+100")); + inv.setItem(12, Methods.makeItem("160:5", 1, "&a+1000")); + inv.setItem(14, Methods.makeItem("160:14", 1, "&c-1000")); + inv.setItem(15, Methods.makeItem("160:14", 1, "&c-100")); + inv.setItem(16, Methods.makeItem("160:14", 1, "&c-10")); + inv.setItem(17, Methods.makeItem("160:14", 1, "&c-1")); + } + inv.setItem(13, getBiddingGlass(player, ID)); + inv.setItem(22, Methods.makeItem(config.getString("Settings.GUISettings.OtherSettings.Bid.Item"), 1, config.getString("Settings.GUISettings.OtherSettings.Bid.Name"), config.getStringList("Settings.GUISettings.OtherSettings.Bid.Lore"))); + + inv.setItem(4, getBiddingItem(player, ID)); + player.openInventory(inv); + } + + public static void openViewer(Player player, String other, int page) { + Methods.updateAuction(); + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + List items = new ArrayList<>(); + List ID = new ArrayList<>(); + if (!data.contains("Items")) { + data.set("Items.Clear", null); + Files.DATA.saveFile(); + } + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(other)) { + List lore = new ArrayList<>(); + if (data.getBoolean("Items." + i + ".Biddable")) { + String seller = data.getString("Items." + i + ".Seller"); + String topbidder = data.getString("Items." + i + ".TopBidder"); + for (String l : config.getStringList("Settings.GUISettings.Bidding")) { + lore.add(l.replace("%TopBid%", Methods.getPrice(i, false)).replace("%topbid%", Methods.getPrice(i, false)).replace("%Seller%", seller).replace("%seller%", seller).replace("%TopBidder%", topbidder).replace("%topbidder%", topbidder).replace("%Time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire")))); + } + } else { + for (String l : config.getStringList("Settings.GUISettings.SellingItemLore")) { + lore.add(l.replace("%Price%", Methods.getPrice(i, false)).replace("%price%", Methods.getPrice(i, false)).replace("%Seller%", data.getString("Items." + i + ".Seller")).replace("%seller%", data.getString("Items." + i + ".Seller")).replace("%Time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + i + ".Time-Till-Expire")))); + } + } + items.add(Methods.addLore(data.getItemStack("Items." + i + ".Item").clone(), lore)); + ID.add(data.getInt("Items." + i + ".StoreID")); + } + } + } + int maxPage = Methods.getMaxPage(items); + for (; page > maxPage; page--) ; + Inventory inv = Bukkit.createInventory(null, 54, Methods.color(config.getString("Settings.GUIName") + " #" + page)); + List options = new ArrayList<>(); + options.add("WhatIsThis.Viewing"); + for (String o : options) { + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + if (!config.getBoolean("Settings.GUISettings.OtherSettings." + o + ".Toggle")) { + continue; + } + } + String id = config.getString("Settings.GUISettings.OtherSettings." + o + ".Item"); + String name = config.getString("Settings.GUISettings.OtherSettings." + o + ".Name"); + int slot = config.getInt("Settings.GUISettings.OtherSettings." + o + ".Slot"); + if (config.contains("Settings.GUISettings.OtherSettings." + o + ".Lore")) { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name, config.getStringList("Settings.GUISettings.OtherSettings." + o + ".Lore"))); + } else { + inv.setItem(slot - 1, Methods.makeItem(id, 1, name)); + } + } + for (ItemStack item : Methods.getPage(items, page)) { + int slot = inv.firstEmpty(); + inv.setItem(slot, item); + } + List.put(player, new ArrayList<>(Methods.getPageInts(ID, page))); + player.openInventory(inv); + } + + public static ItemStack getBiddingGlass(Player player, String ID) { + FileConfiguration config = Files.CONFIG.getFile(); + String id = config.getString("Settings.GUISettings.OtherSettings.Bidding.Item"); + String name = config.getString("Settings.GUISettings.OtherSettings.Bidding.Name"); + ItemStack item; + int bid = bidding.get(player); + if (config.contains("Settings.GUISettings.OtherSettings.Bidding.Lore")) { + List lore = new ArrayList<>(); + for (String l : config.getStringList("Settings.GUISettings.OtherSettings.Bidding.Lore")) { + lore.add(l.replace("%Bid%", bid + "").replace("%bid%", bid + "").replace("%TopBid%", Methods.getPrice(ID, false)).replace("%topbid%", Methods.getPrice(ID, false))); + } + item = Methods.makeItem(id, 1, name, lore); + } else { + item = Methods.makeItem(id, 1, name); + } + return item; + } + + public static ItemStack getBiddingItem(Player player, String ID) { + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + String seller = data.getString("Items." + ID + ".Seller"); + String topbidder = data.getString("Items." + ID + ".TopBidder"); + ItemStack item = data.getItemStack("Items." + ID + ".Item"); + List lore = new ArrayList<>(); + for (String l : config.getStringList("Settings.GUISettings.Bidding")) { + lore.add(l.replace("%TopBid%", Methods.getPrice(ID, false)).replace("%topbid%", Methods.getPrice(ID, false)).replace("%Seller%", seller).replace("%seller%", seller).replace("%TopBidder%", topbidder).replace("%topbidder%", topbidder).replace("%Time%", Methods.convertToTime(data.getLong("Items." + ID + ".Time-Till-Expire"))).replace("%time%", Methods.convertToTime(data.getLong("Items." + ID + ".Time-Till-Expire")))); + } + return Methods.addLore(item.clone(), lore); + } + + private static void playClick(Player player) { + if (Files.CONFIG.getFile().contains("Settings.Sounds.Toggle")) { + if (Files.CONFIG.getFile().getBoolean("Settings.Sounds.Toggle")) { + String sound = Files.CONFIG.getFile().getString("Settings.Sounds.Sound"); + try { + player.playSound(player.getLocation(), Sound.valueOf(sound), 1, 1); + } catch (Exception e) { + if (Methods.getVersion() >= 191) { + player.playSound(player.getLocation(), Sound.valueOf("UI_BUTTON_CLICK"), 1, 1); + } else { + player.playSound(player.getLocation(), Sound.valueOf("CLICK"), 1, 1); + } + Bukkit.getLogger().log(Level.WARNING, "[Crazy Auctions]>> You set the sound to " + sound + " and this is not a sound for your minecraft version. " + "Please go to the config and set a correct sound or turn the sound off in the toggle setting."); + } + } + } else { + if (Methods.getVersion() >= 191) { + player.playSound(player.getLocation(), Sound.valueOf("UI_BUTTON_CLICK"), 1, 1); + } else { + player.playSound(player.getLocation(), Sound.valueOf("CLICK"), 1, 1); + } + } + } + + @EventHandler + public void onInvClose(InventoryCloseEvent e) { + FileConfiguration config = Files.CONFIG.getFile(); + Inventory inv = e.getInventory(); + Player player = (Player) e.getPlayer(); + if (inv != null) { + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Bidding-On-Item")))) { + bidding.remove(player); + } + } + } + + @EventHandler + public void onInvClick(InventoryClickEvent e) { + FileConfiguration config = Files.CONFIG.getFile(); + FileConfiguration data = Files.DATA.getFile(); + Player player = (Player) e.getWhoClicked(); + final Inventory inv = e.getInventory(); + if (inv != null) { + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Categories")))) { + e.setCancelled(true); + int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + for (Category cat : Category.values()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.Category-Settings." + cat.getName() + ".Name")))) { + openShop(player, shopType.get(player), cat, 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Back.Name")))) { + openShop(player, shopType.get(player), shopCategory.get(player), 1); + playClick(player); + return; + } + } + } + } + } + } + } + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Bidding-On-Item")))) { + e.setCancelled(true); + int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Bid.Name")))) { + String ID = biddingID.get(player); + int bid = bidding.get(player); + String topBidder = data.getString("Items." + ID + ".TopBidder"); + if (CurrencyManager.getMoney(player) < bid) { + HashMap placeholders = new HashMap<>(); + placeholders.put("%Money_Needed%", (bid - CurrencyManager.getMoney(player)) + ""); + placeholders.put("%money_needed%", (bid - CurrencyManager.getMoney(player)) + ""); + player.sendMessage(Messages.NEED_MORE_MONEY.getMessage(placeholders)); + return; + } + if (data.getLong("Items." + ID + ".Price") > bid) { + player.sendMessage(Messages.BID_MORE_MONEY.getMessage()); + return; + } + if (data.getLong("Items." + ID + ".Price") >= bid && !topBidder.equalsIgnoreCase("None")) { + player.sendMessage(Messages.BID_MORE_MONEY.getMessage()); + return; + } + Bukkit.getPluginManager().callEvent(new AuctionNewBidEvent(player, data.getItemStack("Items." + ID + ".Item"), bid)); + data.set("Items." + ID + ".Price", bid); + data.set("Items." + ID + ".TopBidder", player.getName()); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Bid%", bid + ""); + player.sendMessage(Messages.BID_MESSAGE.getMessage(placeholders)); + Files.DATA.saveFile(); + bidding.put(player, 0); + player.closeInventory(); + playClick(player); + return; + } + HashMap priceEdits = new HashMap<>(); + priceEdits.put("&a+1", 1); + priceEdits.put("&a+10", 10); + priceEdits.put("&a+100", 100); + priceEdits.put("&a+1000", 1000); + priceEdits.put("&c-1", -1); + priceEdits.put("&c-10", -10); + priceEdits.put("&c-100", -100); + priceEdits.put("&c-1000", -1000); + for (String price : priceEdits.keySet()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(price))) { + try { + bidding.put(player, (bidding.get(player) + priceEdits.get(price))); + inv.setItem(4, getBiddingItem(player, biddingID.get(player))); + inv.setItem(13, getBiddingGlass(player, biddingID.get(player))); + playClick(player); + return; + } catch (Exception ex) { + player.closeInventory(); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + } + } + } + } + } + } + } + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.GUIName")))) { + e.setCancelled(true); + final int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + final ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.NextPage.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + openShop(player, shopType.get(player), shopCategory.get(player), page + 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.PreviousPage.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + if (page == 1) page++; + openShop(player, shopType.get(player), shopCategory.get(player), page - 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Refesh.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + openShop(player, shopType.get(player), shopCategory.get(player), page); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Bidding/Selling.Selling.Name")))) { + openShop(player, ShopType.BID, shopCategory.get(player), 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Bidding/Selling.Bidding.Name")))) { + openShop(player, ShopType.SELL, shopCategory.get(player), 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Cancelled/ExpiredItems.Name")))) { + openPlayersExpiredList(player, 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.SellingItems.Name")))) { + openPlayersCurrentList(player, 1); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Category1.Name")))) { + openCategories(player, shopType.get(player)); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Category2.Name")))) { + openCategories(player, shopType.get(player)); + playClick(player); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Your-Item.Name")))) { + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Cant-Afford.Name")))) { + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Top-Bidder.Name")))) { + return; + } + } + if (List.containsKey(player)) { + if (List.get(player).size() >= slot) { + int id = List.get(player).get(slot); + boolean T = false; + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + int ID = data.getInt("Items." + i + ".StoreID"); + if (id == ID) { + if (player.hasPermission("crazyAuctions.admin") || player.hasPermission("crazyauctions.force-end")) { + if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { + int num = 1; + for (; data.contains("OutOfTime/Cancelled." + num); num++) ; + String seller = data.getString("Items." + i + ".Seller"); + Player sellerPlayer = Methods.getPlayer(seller); + if (Methods.isOnline(seller) && sellerPlayer != null) { + sellerPlayer.sendMessage(Messages.ADMIN_FORCE_CANCELLED_TO_PLAYER.getMessage()); + } + AuctionCancelledEvent event = new AuctionCancelledEvent((sellerPlayer != null ? sellerPlayer : Bukkit.getOfflinePlayer(seller)), data.getItemStack("Items." + i + ".Item"), CancelledReason.ADMIN_FORCE_CANCEL); + Bukkit.getPluginManager().callEvent(event); + data.set("OutOfTime/Cancelled." + num + ".Seller", data.getString("Items." + i + ".Seller")); + data.set("OutOfTime/Cancelled." + num + ".Full-Time", data.getLong("Items." + i + ".Full-Time")); + data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID")); + data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item")); + data.set("Items." + i, null); + Files.DATA.saveFile(); + player.sendMessage(Messages.ADMIN_FORCE_CENCELLED.getMessage()); + playClick(player); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + openShop(player, shopType.get(player), shopCategory.get(player), page); + return; + } + } + final Runnable runnable = () -> inv.setItem(slot, item); + if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { + String it = config.getString("Settings.GUISettings.OtherSettings.Your-Item.Item"); + String name = config.getString("Settings.GUISettings.OtherSettings.Your-Item.Name"); + ItemStack I; + if (config.contains("Settings.GUISettings.OtherSettings.Your-Item.Lore")) { + I = Methods.makeItem(it, 1, name, config.getStringList("Settings.GUISettings.OtherSettings.Your-Item.Lore")); + } else { + I = Methods.makeItem(it, 1, name); + } + inv.setItem(slot, I); + playClick(player); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, runnable, 3 * 20); + return; + } + long cost = data.getLong("Items." + i + ".Price"); + if (CurrencyManager.getMoney(player) < cost) { + String it = config.getString("Settings.GUISettings.OtherSettings.Cant-Afford.Item"); + String name = config.getString("Settings.GUISettings.OtherSettings.Cant-Afford.Name"); + ItemStack I; + if (config.contains("Settings.GUISettings.OtherSettings.Cant-Afford.Lore")) { + I = Methods.makeItem(it, 1, name, config.getStringList("Settings.GUISettings.OtherSettings.Cant-Afford.Lore")); + } else { + I = Methods.makeItem(it, 1, name); + } + inv.setItem(slot, I); + playClick(player); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, runnable, 3 * 20); + return; + } + if (data.getBoolean("Items." + i + ".Biddable")) { + if (player.getName().equalsIgnoreCase(data.getString("Items." + i + ".TopBidder"))) { + String it = config.getString("Settings.GUISettings.OtherSettings.Top-Bidder.Item"); + String name = config.getString("Settings.GUISettings.OtherSettings.Top-Bidder.Name"); + ItemStack I; + if (config.contains("Settings.GUISettings.OtherSettings.Top-Bidder.Lore")) { + I = Methods.makeItem(it, 1, name, config.getStringList("Settings.GUISettings.OtherSettings.Top-Bidder.Lore")); + } else { + I = Methods.makeItem(it, 1, name); + } + inv.setItem(slot, I); + playClick(player); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, runnable, 3 * 20); + return; + } + playClick(player); + openBidding(player, i); + biddingID.put(player, i); + } else { + playClick(player); + openBuying(player, i); + } + return; + } + } + } + if (!T) { + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + } + } + } + } + } + } + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Buying-Item")))) { + e.setCancelled(true); + int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Confirm.Name")))) { + String ID = IDs.get(player); + long cost = data.getLong("Items." + ID + ".Price"); + String seller = data.getString("Items." + ID + ".Seller"); + if (!data.contains("Items." + ID)) { + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + if (Methods.isInvFull(player)) { + playClick(player); + player.closeInventory(); + player.sendMessage(Messages.INVENTORY_FULL.getMessage()); + return; + } + if (CurrencyManager.getMoney(player) < cost) { + playClick(player); + player.closeInventory(); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Money_Needed%", (cost - CurrencyManager.getMoney(player)) + ""); + placeholders.put("%money_needed%", (cost - CurrencyManager.getMoney(player)) + ""); + player.sendMessage(Messages.NEED_MORE_MONEY.getMessage(placeholders)); + return; + } + ItemStack i = data.getItemStack("Items." + ID + ".Item"); + Bukkit.getPluginManager().callEvent(new AuctionBuyEvent(player, i, cost)); + CurrencyManager.removeMoney(player, cost); + CurrencyManager.addMoney(Methods.getOfflinePlayer(seller), cost); + HashMap placeholders = new HashMap<>(); + placeholders.put("%Price%", Methods.getPrice(ID, false)); + placeholders.put("%price%", Methods.getPrice(ID, false)); + placeholders.put("%Player%", player.getName()); + placeholders.put("%player%", player.getName()); + player.sendMessage(Messages.BOUGHT_ITEM.getMessage(placeholders)); + if (Methods.isOnline(seller) && Methods.getPlayer(seller) != null) { + Player sell = Methods.getPlayer(seller); + sell.sendMessage(Messages.PLAYER_BOUGHT_ITEM.getMessage(placeholders)); + } + player.getInventory().addItem(i); + data.set("Items." + ID, null); + Files.DATA.saveFile(); + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Cancel.Name")))) { + openShop(player, shopType.get(player), shopCategory.get(player), 1); + playClick(player); + return; + } + } + } + } + } + } + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Players-Current-Items")))) { + e.setCancelled(true); + int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Back.Name")))) { + openShop(player, shopType.get(player), shopCategory.get(player), 1); + playClick(player); + return; + } + } + if (List.containsKey(player)) { + if (List.get(player).size() >= slot) { + int id = List.get(player).get(slot); + boolean T = false; + if (data.contains("Items")) { + for (String i : data.getConfigurationSection("Items").getKeys(false)) { + int ID = data.getInt("Items." + i + ".StoreID"); + if (id == ID) { + player.sendMessage(Messages.CANCELLED_ITEM.getMessage()); + AuctionCancelledEvent event = new AuctionCancelledEvent(player, data.getItemStack("Items." + i + ".Item"), CancelledReason.PLAYER_FORCE_CANCEL); + Bukkit.getPluginManager().callEvent(event); + int num = 1; + for (; data.contains("OutOfTime/Cancelled." + num); num++) ; + data.set("OutOfTime/Cancelled." + num + ".Seller", data.getString("Items." + i + ".Seller")); + data.set("OutOfTime/Cancelled." + num + ".Full-Time", data.getLong("Items." + i + ".Full-Time")); + data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID")); + data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item")); + data.set("Items." + i, null); + Files.DATA.saveFile(); + playClick(player); + openPlayersCurrentList(player, 1); + return; + } + } + } + if (!T) { + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + return; + } + } + } + } + } + } + } + if (e.getView().getTitle().contains(Methods.color(config.getString("Settings.Cancelled/Expired-Items")))) { + e.setCancelled(true); + final int slot = e.getRawSlot(); + if (slot <= inv.getSize()) { + if (e.getCurrentItem() != null) { + final ItemStack item = e.getCurrentItem(); + if (item.hasItemMeta()) { + if (item.getItemMeta().hasDisplayName()) { + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Back.Name")))) { + Methods.updateAuction(); + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.PreviousPage.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + if (page == 1) page++; + playClick(player); + openPlayersExpiredList(player, (page - 1)); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.Return.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + if (data.contains("OutOfTime/Cancelled")) { + for (String i : data.getConfigurationSection("OutOfTime/Cancelled").getKeys(false)) { + if (data.getString("OutOfTime/Cancelled." + i + ".Seller").equalsIgnoreCase(player.getName())) { + if (Methods.isInvFull(player)) { + player.sendMessage(Messages.INVENTORY_FULL.getMessage()); + break; + } else { + player.getInventory().addItem(data.getItemStack("OutOfTime/Cancelled." + i + ".Item")); + data.set("OutOfTime/Cancelled." + i, null); + } + } + } + } + player.sendMessage(Messages.GOT_ITEM_BACK.getMessage()); + Files.DATA.saveFile(); + playClick(player); + openPlayersExpiredList(player, page); + return; + } + if (item.getItemMeta().getDisplayName().equals(Methods.color(config.getString("Settings.GUISettings.OtherSettings.NextPage.Name")))) { + Methods.updateAuction(); + int page = Integer.parseInt(e.getView().getTitle().split("#")[1]); + playClick(player); + openPlayersExpiredList(player, (page + 1)); + return; + } + } + if (List.containsKey(player)) { + if (List.get(player).size() >= slot) { + int id = List.get(player).get(slot); + boolean T = false; + if (data.contains("OutOfTime/Cancelled")) { + for (String i : data.getConfigurationSection("OutOfTime/Cancelled").getKeys(false)) { + int ID = data.getInt("OutOfTime/Cancelled." + i + ".StoreID"); + if (id == ID) { + if (!Methods.isInvFull(player)) { + player.sendMessage(Messages.GOT_ITEM_BACK.getMessage()); + ItemStack IT = data.getItemStack("OutOfTime/Cancelled." + i + ".Item"); + player.getInventory().addItem(IT); + data.set("OutOfTime/Cancelled." + i, null); + Files.DATA.saveFile(); + playClick(player); + openPlayersExpiredList(player, 1); + } else { + player.sendMessage(Messages.INVENTORY_FULL.getMessage()); + } + return; + } + } + } + if (!T) { + playClick(player); + openShop(player, shopType.get(player), shopCategory.get(player), 1); + player.sendMessage(Messages.ITEM_DOESNT_EXIST.getMessage()); + } + } + } + } + } + } + } + } + } + +} diff --git a/src/main/java/com/badbones69/crazyauctions/currency/CurrencyManager.java b/src/main/java/com/badbones69/crazyauctions/currency/CurrencyManager.java new file mode 100644 index 0000000..1347974 --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/currency/CurrencyManager.java @@ -0,0 +1,119 @@ +package com.badbones69.crazyauctions.currency; + +import com.badbones69.crazyauctions.api.FileManager.Files; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +public enum CurrencyManager { // Currency Manager + + VAULT("Vault", "Money"); + + private final String pluginName; + private final String name; + + /** + * @param pluginname + * name of the Plugin. + * @param name + * name of the Currency. + */ + private CurrencyManager(String pluginname, String name) { + this.pluginName = pluginname; + this.name = name; + } + + /** + * @param name + * name of the Type you want. + * @return Returns the Currency as a Enum. + */ + public static CurrencyManager getFromName(String name) { + for (CurrencyManager type : CurrencyManager.values()) { + if (type.getPluginName().equalsIgnoreCase(name)) { + return type; + } + } + return null; + } + + /** + * + * @param player + * Player you want the currency from. + * @return Returns the amount they have of the currency + */ + public static Long getMoney(Player player) { + return Vault.getMoney(player); + } + + /** + * + * @param player + * Player you want the currency from. + * @param amount + * The amount you want to take. + */ + public static void removeMoney(Player player, Long amount) { + Vault.removeMoney(player, amount); + } + + /** + * + * @param player + * Player you want the currency from. + * @param amount + * The amount you want to take. + */ + public static void removeMoney(OfflinePlayer player, Long amount) { + Vault.removeMoney(player, amount); + } + + /** + * + * @param player + * Player you want the currency from. + * @param amount + * The amount you want to add. + */ + public static void addMoney(Player player, Long amount) { + Vault.addMoney(player, amount); + } + + /** + * + * @param player + * Player you want the currency from. + * @param amount + * The amount you want to add. + */ + public static void addMoney(OfflinePlayer player, Long amount) { + Vault.addMoney(player, amount); + } + + /** + * @return Returns the Currency name as a string. + */ + public String getName() { + return name; + } + + /** + * @return Returns the Currency name as a string. + */ + public String getPluginName() { + return pluginName; + } + + /** + * + * @return Returns true if the server has the plugin. + */ + public Boolean hasPlugin() { + if (Bukkit.getServer().getPluginManager().getPlugin(pluginName) != null) { + return Files.CONFIG.getFile().getBoolean("Settings.Currencies." + pluginName + ".Enabled"); + } + return false; + } + +} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/currency/Vault.java b/src/main/java/com/badbones69/crazyauctions/currency/Vault.java new file mode 100644 index 0000000..4444942 --- /dev/null +++ b/src/main/java/com/badbones69/crazyauctions/currency/Vault.java @@ -0,0 +1,57 @@ +package com.badbones69.crazyauctions.currency; + +import net.milkbowl.vault.economy.Economy; +import net.milkbowl.vault.economy.EconomyResponse; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class Vault { + + public static Economy econ = null; + public static EconomyResponse r; + + public static boolean hasVault() { + return Bukkit.getServer().getPluginManager().getPlugin("Vault") != null; + } + + public static boolean setupEconomy() { + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + return false; + } + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + return false; + } + econ = rsp.getProvider(); + return econ != null; + } + + public static Long getMoney(Player player) { + if (player != null) { + try { + return (long) econ.getBalance(player); + } catch (NullPointerException ignore) { + } + } + return 0L; + } + + public static void removeMoney(Player player, Long amount) { + econ.withdrawPlayer(player, amount); + } + + public static void removeMoney(OfflinePlayer player, Long amount) { + econ.withdrawPlayer(player, amount); + } + + public static void addMoney(Player player, Long amount) { + econ.depositPlayer(player, amount); + } + + public static void addMoney(OfflinePlayer player, Long amount) { + econ.depositPlayer(player, amount); + } + +} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/utils/ItemBuilder.java b/src/main/java/com/badbones69/crazyauctions/utils/ItemBuilder.java deleted file mode 100644 index 8b2a8fc..0000000 --- a/src/main/java/com/badbones69/crazyauctions/utils/ItemBuilder.java +++ /dev/null @@ -1,1261 +0,0 @@ -package com.badbones69.crazyauctions.utils; - -import com.badbones69.crazyauctions.CrazyAuctions; -import com.badbones69.crazyauctions.Methods; -import de.tr7zw.changeme.nbtapi.NBTItem; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; -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.EntityType; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.potion.PotionType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -public class ItemBuilder { - - private NBTItem nbtItem; - - // Item Data - private Material material; - private int damage; - private String itemName; - private final List itemLore; - private int itemAmount; - - // Player - private String player; - - // Skulls - private boolean isHash; - private boolean isURL; - private boolean isHead; - - // Enchantments/Flags - private boolean unbreakable; - private boolean hideItemFlags; - private boolean glowing; - - // Entities - private final boolean isMobEgg; - private EntityType entityType; - - // Potions - private PotionType potionType; - private Color potionColor; - private boolean isPotion; - - // Armor - private Color armorColor; - private boolean isLeatherArmor; - - // Enchantments - private HashMap enchantments; - - // Shields - private boolean isShield; - - // Banners - private boolean isBanner; - private List patterns; - - // Placeholders - private HashMap namePlaceholders; - private HashMap lorePlaceholders; - - // Misc - private ItemStack referenceItem; - private List itemFlags; - - // Custom Data - private int customModelData; - private boolean useCustomModelData; - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - private final Methods methods = plugin.getStarter().getMethods(); - - private final SkullCreator skullCreator = plugin.getStarter().getSkullCreator(); - - /** - * Create a blank item builder. - */ - public ItemBuilder() { - this.nbtItem = null; - this.material = Material.STONE; - this.damage = 0; - this.itemName = ""; - this.itemLore = new ArrayList<>(); - this.itemAmount = 1; - this.player = ""; - - this.isHash = false; - this.isURL = false; - this.isHead = false; - - this.unbreakable = false; - this.hideItemFlags = false; - this.glowing = false; - - this.isMobEgg = false; - this.entityType = EntityType.BAT; - - this.potionType = null; - this.potionColor = null; - this.isPotion = false; - - this.armorColor = null; - this.isLeatherArmor = false; - - this.enchantments = new HashMap<>(); - - this.isShield = false; - - this.isBanner = false; - this.patterns = new ArrayList<>(); - - this.namePlaceholders = new HashMap<>(); - this.lorePlaceholders = new HashMap<>(); - - this.itemFlags = new ArrayList<>(); - } - - /** - * Deduplicate an item builder. - * - * @param itemBuilder The item builder to deduplicate. - */ - public ItemBuilder(ItemBuilder itemBuilder) { - this.nbtItem = itemBuilder.nbtItem; - this.material = itemBuilder.material; - this.damage = itemBuilder.damage; - this.itemName = itemBuilder.itemName; - this.itemLore = new ArrayList<>(itemBuilder.itemLore); - this.itemAmount = itemBuilder.itemAmount; - this.player = itemBuilder.player; - - this.referenceItem = itemBuilder.referenceItem; - this.customModelData = itemBuilder.customModelData; - this.useCustomModelData = itemBuilder.useCustomModelData; - - this.enchantments = new HashMap<>(itemBuilder.enchantments); - - this.isHash = itemBuilder.isHash; - this.isURL = itemBuilder.isURL; - this.isHead = itemBuilder.isHead; - - this.unbreakable = itemBuilder.unbreakable; - this.hideItemFlags = itemBuilder.hideItemFlags; - this.glowing = itemBuilder.glowing; - - this.isMobEgg = itemBuilder.isMobEgg; - this.entityType = itemBuilder.entityType; - - this.potionType = itemBuilder.potionType; - this.potionColor = itemBuilder.potionColor; - this.isPotion = itemBuilder.isPotion; - - this.armorColor = itemBuilder.armorColor; - this.isLeatherArmor = itemBuilder.isLeatherArmor; - - this.isShield = itemBuilder.isShield; - - this.isBanner = itemBuilder.isBanner; - this.patterns = new ArrayList<>(itemBuilder.patterns); - - this.namePlaceholders = new HashMap<>(itemBuilder.namePlaceholders); - this.lorePlaceholders = new HashMap<>(itemBuilder.lorePlaceholders); - this.itemFlags = new ArrayList<>(itemBuilder.itemFlags); - } - - /** - * Gets the nbt item. - */ - public NBTItem getNBTItem() { - nbtItem = new NBTItem(build()); - return nbtItem; - } - - /** - * Gets the material. - */ - public Material getMaterial() { - return material; - } - - /** - * Checks if the item is a banner. - */ - public boolean isBanner() { - return isBanner; - } - - /** - * Checks if an item is a shield. - */ - public boolean isShield() { - return isShield; - } - - /** - * Checks if the item is a spawn mob egg. - */ - public boolean isMobEgg() { - return isMobEgg; - } - - /** - * Returns the player name. - */ - public String getPlayerName() { - return player; - } - - /** - * Get the entity type of the spawn mob egg. - */ - public EntityType getEntityType() { - return entityType; - } - - /** - * Get the name of the item. - */ - public String getName() { - return itemName; - } - - /** - * Get the lore on the item. - */ - public List getLore() { - return itemLore; - } - - /** - * Returns the enchantments on the Item. - */ - public HashMap getEnchantments() { - return enchantments; - } - - /** - * Return a list of Item Flags. - */ - public List getItemFlags() { - return itemFlags; - } - - /** - * Checks if flags are hidden. - */ - public boolean isItemFlagsHidden() { - return hideItemFlags; - } - - /** - * Check if item is Leather Armor - */ - public boolean isLeatherArmor() { - return isLeatherArmor; - } - - /** - * Checks if item is glowing. - */ - public boolean isGlowing() { - return glowing; - } - - /** - * Checks if the item is unbreakable. - */ - public boolean isUnbreakable() { - return unbreakable; - } - - /** - * Returns the amount of the item stack. - */ - public Integer getAmount() { - return itemAmount; - } - - /** - * Get the patterns on the banners. - */ - public List getPatterns() { - return patterns; - } - - /** - * Get the item's name with all the placeholders added to it. - * - * @return The name with all the placeholders in it. - */ - public String getUpdatedName() { - String newName = itemName; - - for (String placeholder : namePlaceholders.keySet()) { - newName = newName.replace(placeholder, namePlaceholders.get(placeholder)).replace(placeholder.toLowerCase(), namePlaceholders.get(placeholder)); - } - - return newName; - } - - /** - * Builder the item from all the information that was given to the builder. - * - * @return The result of all the info that was given to the builder as an ItemStack. - */ - public ItemStack build() { - - if (nbtItem != null) referenceItem = nbtItem.getItem(); - - ItemStack item = referenceItem != null ? referenceItem : new ItemStack(material); - - if (item.getType() != Material.AIR) { - if (isHead) { // Has to go 1st due to it removing all data when finished. - if (isHash) { // Sauce: https://github.com/deanveloper/SkullCreator - if (isURL) { - skullCreator.itemWithUrl(item, player); - } else { - skullCreator.itemWithBase64(item, player); - } - } - } - - item.setAmount(itemAmount); - ItemMeta itemMeta = item.getItemMeta(); - assert itemMeta != null; - itemMeta.setDisplayName(getUpdatedName()); - itemMeta.setLore(getUpdatedLore()); - - if (itemMeta instanceof org.bukkit.inventory.meta.Damageable) ((org.bukkit.inventory.meta.Damageable) itemMeta).setDamage(damage); - - if (isPotion && (potionType != null || potionColor != null)) { - PotionMeta potionMeta = (PotionMeta) itemMeta; - - if (potionType != null) potionMeta.setBasePotionData(new PotionData(potionType)); - - if (potionColor != null) potionMeta.setColor(potionColor); - } - - if (material == Material.TIPPED_ARROW && potionType != null) { - PotionMeta potionMeta = (PotionMeta) itemMeta; - potionMeta.setBasePotionData(new PotionData(potionType)); - } - - if (isLeatherArmor && armorColor != null) { - LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemMeta; - leatherMeta.setColor(armorColor); - } - - if (isBanner && !patterns.isEmpty()) { - BannerMeta bannerMeta = (BannerMeta) itemMeta; - bannerMeta.setPatterns(patterns); - } - - if (isShield && !patterns.isEmpty()) { - BlockStateMeta shieldMeta = (BlockStateMeta) itemMeta; - Banner banner = (Banner) shieldMeta.getBlockState(); - banner.setPatterns(patterns); - banner.update(); - shieldMeta.setBlockState(banner); - } - - if (useCustomModelData) itemMeta.setCustomModelData(customModelData); - - itemFlags.forEach(itemMeta :: addItemFlags); - item.setItemMeta(itemMeta); - hideItemFlags(item); - item.addUnsafeEnchantments(enchantments); - addGlow(item); - NBTItem nbt = new NBTItem(item); - - if (isHead && !isHash) nbt.setString("SkullOwner", player); - - if (isMobEgg) { - if (entityType != null) nbt.addCompound("EntityTag").setString("id", "minecraft:" + entityType.name()); - } - - return nbt.getItem(); - } else { - return item; - } - } - - /* - Class based extensions. - */ - - /** - * Set the type of item the builder is set to. - * - * @param material The material you wish to set. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder setMaterial(Material material) { - this.material = material; - this.isHead = material == Material.PLAYER_HEAD; - return this; - } - - /** - * Set the type of item and its metadata in the builder. - * - * @param material The string must be in this form: %Material% or %Material%:%MetaData% - * @return The ItemBuilder with updated info. - */ - public ItemBuilder setMaterial(String material) { - String metaData; - - if (material.contains(":")) { // Sets the durability or another value option. - String[] b = material.split(":"); - material = b[0]; - metaData = b[1]; - - if (metaData.contains("#")) { // :# - String modelData = metaData.split("#")[1]; - - if (isInt(modelData)) { // Value is a number. - this.useCustomModelData = true; - this.customModelData = Integer.parseInt(modelData); - } - } - - metaData = metaData.replace("#" + customModelData, ""); - - if (isInt(metaData)) { // Value is durability. - this.damage = Integer.parseInt(metaData); - } else { // Value is something else. - this.potionType = getPotionType(PotionEffectType.getByName(metaData)); - this.potionColor = getColor(metaData); - this.armorColor = getColor(metaData); - } - - } else if (material.contains("#")) { - String[] b = material.split("#"); - material = b[0]; - - if (isInt(b[1])) { // Value is a number. - this.useCustomModelData = true; - this.customModelData = Integer.parseInt(b[1]); - } - } - - Material matchedMaterial = Material.matchMaterial(material); - - if (matchedMaterial != null) this.material = matchedMaterial; - - switch (this.material.name()) { - case "PLAYER_HEAD": - case "SKULL_ITEM": - this.isHead = true; - break; - case "POTION": - case "SPLASH_POTION": - this.isPotion = true; - break; - case "LEATHER_HELMET": - case "LEATHER_CHESTPLATE": - case "LEATHER_LEGGINGS": - case "LEATHER_BOOTS": - case "LEATHER_HORSE_ARMOR": - this.isLeatherArmor = true; - break; - case "BANNER": - this.isBanner = true; - break; - case "SHIELD": - this.isShield = true; - break; - } - - if (this.material.name().contains("BANNER")) this.isBanner = true; - - return this; - } - - /** - * @param damage The damage value of the item. - * @return The ItemBuilder with an updated damage value. - */ - public ItemBuilder setDamage(int damage) { - this.damage = damage; - return this; - } - - /** - * @param itemName The name of the item. - * @return The ItemBuilder with an updated name. - */ - public ItemBuilder setName(String itemName) { - if (itemName != null) this.itemName = methods.color(itemName); - - return this; - } - - /** - * @param placeholders The placeholders that will be used. - * @return The ItemBuilder with updated placeholders. - */ - public ItemBuilder setNamePlaceholders(HashMap placeholders) { - this.namePlaceholders = placeholders; - return this; - } - - /** - * Add a placeholder to the name of the item. - * - * @param placeholder The placeholder that will be replaced. - * @param argument The argument you wish to replace the placeholder with. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder addNamePlaceholder(String placeholder, String argument) { - this.namePlaceholders.put(placeholder, argument); - return this; - } - - /** - * Remove a placeholder from the list. - * - * @param placeholder The placeholder you wish to remove. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder removeNamePlaceholder(String placeholder) { - this.namePlaceholders.remove(placeholder); - return this; - } - - /** - * Set the lore of the item in the builder. This will auto force color in all the lores that contains color code. (&a, &c, &7, etc...) - * - * @param lore The lore of the item in the builder. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder setLore(List lore) { - if (lore != null) { - this.itemLore.clear(); - - for (String line : lore) { - this.itemLore.add(methods.color(line)); - } - } - - return this; - } - - /** - * Add a line to the current lore of the item. This will auto force color in the lore that contains color code. (&a, &c, &7, etc...) - * - * @param lore The new line you wish to add. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder addLore(String lore) { - if (lore != null) this.itemLore.add(methods.color(lore)); - - return this; - } - - /** - * Set the placeholders that are in the lore of the item. - * - * @param placeholders The placeholders that you wish to use. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder setLorePlaceholders(HashMap placeholders) { - this.lorePlaceholders = placeholders; - return this; - } - - /** - * Add a placeholder to the lore of the item. - * - * @param placeholder The placeholder you wish to replace. - * @param argument The argument that will replace the placeholder. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder addLorePlaceholder(String placeholder, String argument) { - this.lorePlaceholders.put(placeholder, argument); - return this; - } - - /** - * Get the lore with all the placeholders added to it. - * - * @return The lore with all placeholders in it. - */ - public List getUpdatedLore() { - List newLore = new ArrayList<>(); - - for (String item : itemLore) { - for (String placeholder : lorePlaceholders.keySet()) { - item = item.replace(placeholder, lorePlaceholders.get(placeholder)).replace(placeholder.toLowerCase(), lorePlaceholders.get(placeholder)); - } - - newLore.add(item); - } - - return newLore; - } - - /** - * Remove a placeholder from the lore. - * - * @param placeholder The placeholder you wish to remove. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder removeLorePlaceholder(String placeholder) { - this.lorePlaceholders.remove(placeholder); - return this; - } - - /** - * @param entityType The entity type the mob spawn egg will be. - * @return The ItemBuilder with an updated mob spawn egg. - */ - public ItemBuilder setEntityType(EntityType entityType) { - this.entityType = entityType; - return this; - } - - /** - * Add patterns to the item. - * - * @param stringPattern The pattern you wish to add. - */ - 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) addPattern(new Pattern(color, pattern)); - - break; - } - } - } catch (Exception ignored) {} - } - - /** - * @param patterns The list of Patterns to add. - * @return The ItemBuilder with updated patterns. - */ - public ItemBuilder addPatterns(List patterns) { - patterns.forEach(this :: addPatterns); - return this; - } - - /** - * @param pattern A pattern to add. - * @return The ItemBuilder with an updated pattern. - */ - public ItemBuilder addPattern(Pattern pattern) { - patterns.add(pattern); - return this; - } - - /** - * @param patterns Set a list of Patterns. - * @return The ItemBuilder with an updated list of patterns. - */ - public ItemBuilder setPattern(List patterns) { - this.patterns = patterns; - return this; - } - - /** - * @param amount The amount of the item stack. - * @return The ItemBuilder with an updated item count. - */ - public ItemBuilder setAmount(Integer amount) { - this.itemAmount = amount; - return this; - } - - /** - * Set the player that will be displayed on the head. - * - * @param playerName The player being displayed on the head. - * @return The ItemBuilder with an updated Player Name. - */ - public ItemBuilder setPlayerName(String playerName) { - this.player = playerName; - - if (player != null && player.length() > 16) { - this.isHash = true; - this.isURL = player.startsWith("http"); - } - - return this; - } - - /** - * It will override any enchantments used in ItemBuilder.addEnchantment() below. - * - * @param enchantment A list of enchantments to add to the item. - * @return The ItemBuilder with a list of updated enchantments. - */ - public ItemBuilder setEnchantments(HashMap enchantment) { - if (enchantment != null) this.enchantments = enchantment; - - return this; - } - - /** - * Adds an enchantment to the item. - * - * @param enchantment The enchantment you wish to add. - * @param level The level of the enchantment ( Unsafe levels included ) - * @return The ItemBuilder with updated enchantments. - */ - public ItemBuilder addEnchantments(Enchantment enchantment, int level) { - this.enchantments.put(enchantment, level); - return this; - } - - /** - * Remove an enchantment from the item. - * - * @param enchantment The enchantment you wish to remove. - * @return The ItemBuilder with updated enchantments. - */ - public ItemBuilder removeEnchantments(Enchantment enchantment) { - this.enchantments.remove(enchantment); - return this; - } - - /** - * Set the flags that will be on the item in the builder. - * - * @param flagStrings The flag names as string you wish to add to the item in the builder. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder setFlagsFromStrings(List flagStrings) { - itemFlags.clear(); - - for (String flagString : flagStrings) { - ItemFlag flag = getFlag(flagString); - - if (flag != null) itemFlags.add(flag); - } - - return this; - } - - // Used for multiple Item Flags - public ItemBuilder addItemFlags(List flagStrings) { - for (String flagString : flagStrings) { - try { - ItemFlag itemFlag = ItemFlag.valueOf(flagString.toUpperCase()); - - if (itemFlag != null) addItemFlag(itemFlag); - } catch (Exception ignored) {} - } - - return this; - } - - /** - * Add a flag to the item in the builder. - * - * @param flagString The name of the flag you wish to add. - * @return The ItemBuilder with updated info. - */ - public ItemBuilder addFlags(String flagString) { - ItemFlag flag = getFlag(flagString); - - if (flag != null) itemFlags.add(flag); - return this; - } - - /** - * Adds an ItemFlag to a map which is added to an item. - * - * @param itemFlag The flag to add. - * @return The ItemBuilder with an updated ItemFlag. - */ - public ItemBuilder addItemFlag(ItemFlag itemFlag) { - if (itemFlag != null) itemFlags.add(itemFlag); - - return this; - } - - /** - * Adds multiple ItemFlags in a list to a map which get added to an item. - * - * @param itemFlags The list of flags to add. - * @return The ItemBuilder with a list of ItemFlags. - */ - public ItemBuilder setItemFlags(List itemFlags) { - this.itemFlags = itemFlags; - return this; - } - - /** - * @param hideItemFlags Hide item flags based on a boolean. - * @return The ItemBuilder with an updated Boolean. - */ - public ItemBuilder hideItemFlags(boolean hideItemFlags) { - this.hideItemFlags = hideItemFlags; - return this; - } - - /** - * @param item The item to hide flags on. - * @return The ItemBuilder with an updated Item. - */ - public ItemStack hideItemFlags(ItemStack item) { - if (hideItemFlags) { - if (item != null && item.hasItemMeta() && item.getItemMeta() != null) { - ItemMeta itemMeta = item.getItemMeta(); - itemMeta.addItemFlags(ItemFlag.values()); - item.setItemMeta(itemMeta); - return item; - } - } - - return item; - } - - /** - * Sets the converted item as a reference to try and save NBT tags and stuff. - * - * @param referenceItem The item that is being referenced. - * @return The ItemBuilder with updated info. - */ - private ItemBuilder setReferenceItem(ItemStack referenceItem) { - this.referenceItem = referenceItem; - return this; - } - - /** - * @param unbreakable Sets the item to be unbreakable. - * @return The ItemBuilder with an updated Boolean. - */ - public ItemBuilder setUnbreakable(boolean unbreakable) { - this.unbreakable = unbreakable; - return this; - } - - /** - * @param glow Sets whether to make an item to glow or not. - * @return The ItemBuilder with an updated Boolean. - */ - public ItemBuilder setGlow(boolean glow) { - this.glowing = glow; - return this; - } - - /** - * The text that will be displayed on the item. - * - * @param texture The skull texture. - * @param profileUUID The uuid of the profile. - * @return The ItemBuilder. - */ - public ItemBuilder texture(String texture, UUID profileUUID) { - return this; - } - - /** - * @param texture The skull texture. - * @return The ItemBuilder. - */ - public ItemBuilder texture(String texture) { - return this; - } - - /** - * @param texture The owner of the skull. - * @return The ItemBuilder. - */ - public ItemBuilder owner(String texture) { - return this; - } - - // Other misc shit - - /** - * Convert an ItemStack to an ItemBuilder to allow easier editing of the ItemStack. - * - * @param item The ItemStack you wish to convert into an ItemBuilder. - * @return The ItemStack as an ItemBuilder with all the info from the item. - */ - public static ItemBuilder convertItemStack(ItemStack item) { - ItemBuilder itemBuilder = new ItemBuilder().setReferenceItem(item).setAmount(item.getAmount()).setMaterial(item.getType()).setEnchantments(new HashMap<>(item.getEnchantments())); - - if (item.hasItemMeta() && item.getItemMeta() != null) { - ItemMeta itemMeta = item.getItemMeta(); - itemBuilder.setName(itemMeta.getDisplayName()).setLore(itemMeta.getLore()); - NBTItem nbt = new NBTItem(item); - - if (nbt.hasKey("Unbreakable")) itemBuilder.setUnbreakable(nbt.getBoolean("Unbreakable")); - - if (itemMeta instanceof org.bukkit.inventory.meta.Damageable) itemBuilder.setDamage(((org.bukkit.inventory.meta.Damageable) itemMeta).getDamage()); - } - - return itemBuilder; - } - - /** - * Converts a String to an ItemBuilder. - * - * @param itemString The String you wish to convert. - * @return The String as an ItemBuilder. - */ - public static ItemBuilder convertString(String itemString) { - return convertString(itemString, null); - } - - /** - * Converts a string to an ItemBuilder with a placeholder for errors. - * - * @param itemString The String you wish to convert. - * @param placeHolder The placeholder to use if there is an error. - * @return The String as an ItemBuilder. - */ - public static ItemBuilder convertString(String itemString, String placeHolder) { - ItemBuilder itemBuilder = new ItemBuilder(); - - try { - for (String optionString : itemString.split(", ")) { - String option = optionString.split(":")[0]; - String value = optionString.replace(option + ":", "").replace(option, ""); - - switch (option.toLowerCase()) { - case "item": - itemBuilder.setMaterial(value); - break; - case "name": - itemBuilder.setName(value); - break; - case "amount": - try { - itemBuilder.setAmount(Integer.parseInt(value)); - } catch (NumberFormatException e) { - itemBuilder.setAmount(1); - } - break; - case "lore": - itemBuilder.setLore(Arrays.asList(value.split(","))); - break; - case "player": - itemBuilder.setPlayerName(value); - break; - case "unbreakable-item": - if (value.isEmpty() || value.equalsIgnoreCase("true")) itemBuilder.setUnbreakable(true); - break; - default: - Enchantment enchantment = getEnchantment(option); - - if (enchantment != null && enchantment.getName() != null) { - try { - itemBuilder.addEnchantments(enchantment, Integer.parseInt(value)); - } catch (NumberFormatException e) { - itemBuilder.addEnchantments(enchantment, 1); - } - - break; - } - - for (ItemFlag itemFlag : ItemFlag.values()) { - if (itemFlag.name().equalsIgnoreCase(option)) { - itemBuilder.addItemFlag(itemFlag); - break; - } - } - - try { - for (PatternType pattern : PatternType.values()) { - if (option.equalsIgnoreCase(pattern.name()) || value.equalsIgnoreCase(pattern.getIdentifier())) { - DyeColor color = getDyeColor(value); - if (color != null) itemBuilder.addPattern(new Pattern(color, pattern)); - break; - } - } - } catch (Exception ignored) {} - break; - } - } - } catch (Exception e) { - itemBuilder.setMaterial(Material.RED_TERRACOTTA).setName("&c&lERROR").setLore(Arrays.asList("&cThere is an error", "&cFor : &c" + (placeHolder != null ? placeHolder : ""))); - e.printStackTrace(); - } - - return itemBuilder; - } - - /** - * Converts a list of Strings to a list of ItemBuilders. - * - * @param itemStrings The list of Strings. - * @return The list of ItemBuilders. - */ - public static List convertStringList(List itemStrings) { - return convertStringList(itemStrings, null); - } - - /** - * Converts a list of Strings to a list of ItemBuilders with a placeholder for errors. - * - * @param itemStrings The list of Strings. - * @param placeholder The placeholder for errors. - * @return The list of ItemBuilders. - */ - public static List convertStringList(List itemStrings, String placeholder) { - return itemStrings.stream().map(itemString -> convertString(itemString, placeholder)).collect(Collectors.toList()); - } - - /** - * Add glow to an item. - * - * @param item The item to add glow to. - */ - private void addGlow(ItemStack item) { - if (glowing) { - try { - if (item != null && item.getItemMeta() != null) { - if (item.hasItemMeta()) { - if (item.getItemMeta().hasEnchants()) return; - } - - item.addUnsafeEnchantment(Enchantment.LUCK, 1); - ItemMeta meta = item.getItemMeta(); - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - item.setItemMeta(meta); - } - } catch (NoClassDefFoundError ignored) {} - } - } - - /** - * Get the PotionEffect from a PotionEffectType. - * - * @param type The type of the potion effect. - * @return The potion type. - */ - private PotionType getPotionType(PotionEffectType type) { - if (type != null) { - if (type.equals(PotionEffectType.FIRE_RESISTANCE)) { - return PotionType.FIRE_RESISTANCE; - } else if (type.equals(PotionEffectType.HARM)) { - return PotionType.INSTANT_DAMAGE; - } else if (type.equals(PotionEffectType.HEAL)) { - return PotionType.INSTANT_HEAL; - } else if (type.equals(PotionEffectType.INVISIBILITY)) { - return PotionType.INVISIBILITY; - } else if (type.equals(PotionEffectType.JUMP)) { - return PotionType.JUMP; - } else if (type.equals(PotionEffectType.getByName("LUCK"))) { - return PotionType.valueOf("LUCK"); - } else if (type.equals(PotionEffectType.NIGHT_VISION)) { - return PotionType.NIGHT_VISION; - } else if (type.equals(PotionEffectType.POISON)) { - return PotionType.POISON; - } else if (type.equals(PotionEffectType.REGENERATION)) { - return PotionType.REGEN; - } else if (type.equals(PotionEffectType.SLOW)) { - return PotionType.SLOWNESS; - } else if (type.equals(PotionEffectType.SPEED)) { - return PotionType.SPEED; - } else if (type.equals(PotionEffectType.INCREASE_DAMAGE)) { - return PotionType.STRENGTH; - } else if (type.equals(PotionEffectType.WATER_BREATHING)) { - return PotionType.WATER_BREATHING; - } else if (type.equals(PotionEffectType.WEAKNESS)) { - return PotionType.WEAKNESS; - } - } - - return null; - } - - /** - * Get the Color from a string. - * - * @param color The string of the color. - * @return The color from the string. - */ - private static 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; - } - - /** - * Get the dye color from a string. - * - * @param color The string of the color. - * @return The dye color from the string. - */ - public static DyeColor getDyeColor(String color) { - if (color != null) { - try { - return DyeColor.valueOf(color.toUpperCase()); - } catch (Exception e) { - 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; - } - - /** - * Get the enchantment from a string. - * - * @param enchantmentName The string of the enchantment. - * @return The enchantment from the string. - */ - private static Enchantment getEnchantment(String enchantmentName) { - enchantmentName = stripEnchantmentName(enchantmentName); - for (Enchantment enchantment : Enchantment.values()) { - try { - if (stripEnchantmentName(enchantment.getKey().getKey()).equalsIgnoreCase(enchantmentName)) return enchantment; - - HashMap enchantments = getEnchantmentList(); - - if (stripEnchantmentName(enchantment.getName()).equalsIgnoreCase(enchantmentName) || (enchantments.get(enchantment.getName()) != null && - stripEnchantmentName(enchantments.get(enchantment.getName())).equalsIgnoreCase(enchantmentName))) return enchantment; - } catch (Exception ignore) {} - } - - return null; - } - - /** - * Strip extra characters from an enchantment name. - * - * @param enchantmentName The enchantment name. - * @return The stripped enchantment name. - */ - private static String stripEnchantmentName(String enchantmentName) { - return enchantmentName != null ? enchantmentName.replace("-", "").replace("_", "").replace(" ", "") : null; - } - - /** - * Get the list of enchantments and their in-Game names. - * - * @return The list of enchantments and their in-Game names. - */ - private static HashMap getEnchantmentList() { - HashMap enchantments = new HashMap<>(); - - enchantments.put("ARROW_DAMAGE", "Power"); - enchantments.put("ARROW_FIRE", "Flame"); - enchantments.put("ARROW_INFINITE", "Infinity"); - enchantments.put("ARROW_KNOCKBACK", "Punch"); - enchantments.put("DAMAGE_ALL", "Sharpness"); - enchantments.put("DAMAGE_ARTHROPODS", "Bane_Of_Arthropods"); - enchantments.put("DAMAGE_UNDEAD", "Smite"); - enchantments.put("DEPTH_STRIDER", "Depth_Strider"); - enchantments.put("DIG_SPEED", "Efficiency"); - enchantments.put("DURABILITY", "Unbreaking"); - enchantments.put("FIRE_ASPECT", "Fire_Aspect"); - enchantments.put("KNOCKBACK", "KnockBack"); - enchantments.put("LOOT_BONUS_BLOCKS", "Fortune"); - enchantments.put("LOOT_BONUS_MOBS", "Looting"); - enchantments.put("LUCK", "Luck_Of_The_Sea"); - enchantments.put("LURE", "Lure"); - enchantments.put("OXYGEN", "Respiration"); - enchantments.put("PROTECTION_ENVIRONMENTAL", "Protection"); - enchantments.put("PROTECTION_EXPLOSIONS", "Blast_Protection"); - enchantments.put("PROTECTION_FALL", "Feather_Falling"); - enchantments.put("PROTECTION_FIRE", "Fire_Protection"); - enchantments.put("PROTECTION_PROJECTILE", "Projectile_Protection"); - enchantments.put("SILK_TOUCH", "Silk_Touch"); - enchantments.put("THORNS", "Thorns"); - enchantments.put("WATER_WORKER", "Aqua_Affinity"); - enchantments.put("BINDING_CURSE", "Curse_Of_Binding"); - enchantments.put("MENDING", "Mending"); - enchantments.put("FROST_WALKER", "Frost_Walker"); - enchantments.put("VANISHING_CURSE", "Curse_Of_Vanishing"); - enchantments.put("SWEEPING_EDGE", "Sweeping_Edge"); - enchantments.put("RIPTIDE", "Riptide"); - enchantments.put("CHANNELING", "Channeling"); - enchantments.put("IMPALING", "Impaling"); - enchantments.put("LOYALTY", "Loyalty"); - - return enchantments; - } - - private boolean isInt(String s) { - try { - Integer.parseInt(s); - } catch (NumberFormatException nfe) { - return false; - } - - return true; - } - - private ItemFlag getFlag(String flagString) { - for (ItemFlag flag : ItemFlag.values()) { - if (flag.name().equalsIgnoreCase(flagString)) return flag; - } - - return null; - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/utils/SkullCreator.java b/src/main/java/com/badbones69/crazyauctions/utils/SkullCreator.java deleted file mode 100644 index 736e772..0000000 --- a/src/main/java/com/badbones69/crazyauctions/utils/SkullCreator.java +++ /dev/null @@ -1,275 +0,0 @@ -package com.badbones69.crazyauctions.utils; - -import com.badbones69.crazyauctions.CrazyAuctions; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Skull; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Base64; -import java.util.UUID; - -/** - * A library for the Bukkit API to create player skulls - * from names, base64 strings, and texture URLs. - * Does not use any NMS code, and should work across all versions. - * - * @author Dean B on 12/28/2016. - */ -public class SkullCreator { - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - /** - * Creates a player skull based on a player's name. - * - * @param name The Player's name - * @return The head of the Player - * - * @deprecated names don't make for good identifiers - */ - @Deprecated - public ItemStack itemFromName(String name) { - ItemStack item = getPlayerSkullItem(); - - return itemWithName(item, name); - } - - /** - * Creates a player skull based on a player's name. - * - * @param item The item to apply the name to - * @param name The Player's name - * @return The head of the Player - * - * @deprecated names don't make for good identifiers - */ - @Deprecated - public ItemStack itemWithName(ItemStack item, String name) { - notNull(item, "item"); - notNull(name, "name"); - - return plugin.getServer().getUnsafe().modifyItemStack(item, "{SkullOwner:\"" + name + "\"}"); - } - - /** - * Creates a player skull with a UUID. 1.13 only. - * - * @param id The Player's UUID - * @return The head of the Player - */ - public ItemStack itemFromUuid(UUID id) { - ItemStack item = getPlayerSkullItem(); - - return itemWithUuid(item, id); - } - - /** - * Creates a player skull based on a UUID. 1.13 only. - * - * @param item The item to apply the name to - * @param id The Player's UUID - * @return The head of the Player - */ - public ItemStack itemWithUuid(ItemStack item, UUID id) { - notNull(item, "item"); - notNull(id, "id"); - - SkullMeta meta = (SkullMeta) item.getItemMeta(); - meta.setOwningPlayer(plugin.getServer().getOfflinePlayer(id)); - item.setItemMeta(meta); - - return item; - } - - /** - * Creates a player skull based on a Mojang server URL. - * - * @param url The URL of the Mojang skin - * @return The head associated with the URL - */ - public ItemStack itemFromUrl(String url) { - ItemStack item = getPlayerSkullItem(); - - return itemWithUrl(item, url); - } - - /** - * Creates a player skull based on a Mojang server URL. - * - * @param item The item to apply the skin to - * @param url The URL of the Mojang skin - * @return The head associated with the URL - */ - public ItemStack itemWithUrl(ItemStack item, String url) { - notNull(item, "item"); - notNull(url, "url"); - - return itemWithBase64(item, urlToBase64(url)); - } - - /** - * Creates a player skull based on a base64 string containing the link to the skin. - * - * @param base64 The base64 string containing the texture - * @return The head with a custom texture - */ - public ItemStack itemFromBase64(String base64) { - ItemStack item = getPlayerSkullItem(); - - return itemWithBase64(item, base64); - } - - /** - * Applies the base64 string to the ItemStack. - * - * @param item The ItemStack to put the base64 onto - * @param base64 The base64 string containing the texture - * @return The head with a custom texture - */ - public ItemStack itemWithBase64(ItemStack item, String base64) { - notNull(item, "item"); - notNull(base64, "base64"); - - UUID hashAsId = new UUID(base64.hashCode(), base64.hashCode()); - return plugin.getServer().getUnsafe().modifyItemStack(item, - "{SkullOwner:{Id:\"" + hashAsId + "\",Properties:{textures:[{Value:\"" + base64 + "\"}]}}}" - ); - } - - /** - * Sets the block to a skull with the given name. - * - * @param block The block to set - * @param name The player to set it to - * - * @deprecated names don't make for good identifiers - */ - @Deprecated - public void blockWithName(Block block, String name) { - notNull(block, "block"); - notNull(name, "name"); - - setBlockType(block); - ((Skull) block.getState()).setOwningPlayer(Bukkit.getOfflinePlayer(name)); - } - - /** - * Sets the block to a skull with the given UUID. - * - * @param block The block to set - * @param id The player to set it to - */ - public void blockWithUuid(Block block, UUID id) { - notNull(block, "block"); - notNull(id, "id"); - - setBlockType(block); - ((Skull) block.getState()).setOwningPlayer(Bukkit.getOfflinePlayer(id)); - } - - /** - * Sets the block to a skull with the given UUID. - * - * @param block The block to set - * @param url The mojang URL to set it to use - */ - public void blockWithUrl(Block block, String url) { - notNull(block, "block"); - notNull(url, "url"); - - blockWithBase64(block, urlToBase64(url)); - } - - /** - * Sets the block to a skull with the given UUID. - * - * @param block The block to set - * @param base64 The base64 to set it to use - */ - public void blockWithBase64(Block block, String base64) { - notNull(block, "block"); - notNull(base64, "base64"); - - UUID hashAsId = new UUID(base64.hashCode(), base64.hashCode()); - - String args = String.format( - "%d %d %d %s", - block.getX(), - block.getY(), - block.getZ(), - "{Owner:{Id:\"" + hashAsId + "\",Properties:{textures:[{Value:\"" + base64 + "\"}]}}}" - ); - - if (newerApi()) { - plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "data merge block " + args); - } else { - plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "blockdata " + args); - } - } - - private boolean newerApi() { - try { - Material.valueOf("PLAYER_HEAD"); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } - - private ItemStack getPlayerSkullItem() { - if (newerApi()) { - return new ItemStack(Material.valueOf("PLAYER_HEAD")); - } else { - return new ItemStack(Material.valueOf("SKULL_ITEM"), 1, (byte) 3); - } - } - - private void setBlockType(Block block) { - try { - block.setType(Material.valueOf("PLAYER_HEAD"), false); - } catch (IllegalArgumentException e) { - block.setType(Material.valueOf("SKULL"), false); - } - } - - private void notNull(Object o, String name) { - if (o == null) { - throw new NullPointerException(name + " should not be null!"); - } - } - - private String urlToBase64(String url) { - - URI actualUrl; - - try { - actualUrl = new URI(url); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - - String toEncode = "{\"textures\":{\"SKIN\":{\"url\":\"" + actualUrl + "\"}}}"; - return Base64.getEncoder().encodeToString(toEncode.getBytes()); - } -} - -/* Format for skull -{ - display:{ - Name:"Cheese" - }, - SkullOwner:{ - Id:"9c919b83-f3fe-456f-a824-7d1d08cc8bd2", - Properties:{ - textures:[ - { - Value:"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTU1ZDYxMWE4NzhlODIxMjMxNzQ5YjI5NjU3MDhjYWQ5NDI2NTA2NzJkYjA5ZTI2ODQ3YTg4ZTJmYWMyOTQ2In19fQ==" - } - ] - } - } -}*/ \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/utils/func/PluginSupport.java b/src/main/java/com/badbones69/crazyauctions/utils/func/PluginSupport.java deleted file mode 100644 index ad345dd..0000000 --- a/src/main/java/com/badbones69/crazyauctions/utils/func/PluginSupport.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.badbones69.crazyauctions.utils.func; - -import com.badbones69.crazyauctions.CrazyAuctions; - -public enum PluginSupport { - - PLACEHOLDERAPI("PlaceholderAPI"), - HOLOGRAPHIC_DISPLAYS("HolographicDisplays"), - DECENT_HOLOGRAMS("DecentHolograms"), - VAULT("Vault"); - - private final String name; - - private final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - PluginSupport(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public boolean isPluginLoaded() { - return plugin.getServer().getPluginManager().getPlugin(name) != null; - } -} \ No newline at end of file diff --git a/src/main/java/com/badbones69/crazyauctions/utils/func/ServerProtocol.java b/src/main/java/com/badbones69/crazyauctions/utils/func/ServerProtocol.java deleted file mode 100644 index c0277a0..0000000 --- a/src/main/java/com/badbones69/crazyauctions/utils/func/ServerProtocol.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.badbones69.crazyauctions.utils.func; - -import com.badbones69.crazyauctions.CrazyAuctions; - -/** - * @author Badbones69 - */ -public enum ServerProtocol { - - TOO_OLD(-1), - v1_7_R1(171), v1_7_R2(172), v1_7_R3(173), v1_7_R4(174), - v1_8_R1(181), v1_8_R2(182), v1_8_R3(183), - v1_9_R1(191), v1_9_R2(192), - v1_10_R1(1101), - v1_11_R1(1111), - v1_12_R1(1121), - v1_13_R2(1132), - v1_14_R1(1141), - v1_15_R1(1151), - v1_16_R1(1161), v1_16_R2(1162), v1_16_R3(1163), - v1_17_R1(1171), - v1_18_R1(1181), - v1_18_R2(1182), - v1_19(1191), - TOO_NEW(-2); - - private static ServerProtocol currentProtocol; - private static ServerProtocol latest; - - private final int versionProtocol; - - private static final CrazyAuctions plugin = CrazyAuctions.getPlugin(); - - ServerProtocol(int versionProtocol) { - this.versionProtocol = versionProtocol; - } - - public static ServerProtocol getCurrentProtocol() { - - String serVer = plugin.getServer().getClass().getPackage().getName(); - - int serProt = Integer.parseInt( - serVer.substring( - serVer.lastIndexOf('.') + 1 - ).replace("_", "").replace("R", "").replace("v", "") - ); - - for (ServerProtocol protocol : values()) { - if (protocol.versionProtocol == serProt) { - currentProtocol = protocol; - break; - } - } - - if (currentProtocol == null) currentProtocol = ServerProtocol.TOO_NEW; - - return currentProtocol; - } - - public static boolean isLegacy() { - return isOlder(ServerProtocol.v1_18_R1); - } - - public static ServerProtocol getLatestProtocol() { - - if (latest != null) return latest; - - ServerProtocol old = ServerProtocol.TOO_OLD; - - for (ServerProtocol protocol : values()) { - if (protocol.compare(old) == 1) { - old = protocol; - } - } - - return old; - } - - public static boolean isAtLeast(ServerProtocol protocol) { - if (currentProtocol == null) getCurrentProtocol(); - - int proto = currentProtocol.versionProtocol; - - return proto >= protocol.versionProtocol || proto == -2; - } - - public static boolean isNewer(ServerProtocol protocol) { - if (currentProtocol == null) getCurrentProtocol(); - - return currentProtocol.versionProtocol > protocol.versionProtocol || currentProtocol.versionProtocol == -2; - } - - public static boolean isSame(ServerProtocol protocol) { - if (currentProtocol == null) getCurrentProtocol(); - - return currentProtocol.versionProtocol == protocol.versionProtocol; - } - - public static boolean isOlder(ServerProtocol protocol) { - if (currentProtocol == null) getCurrentProtocol(); - - int proto = currentProtocol.versionProtocol; - - return proto < protocol.versionProtocol || proto == -1; - } - - public int compare(ServerProtocol protocol) { - int result = -1; - int current = versionProtocol; - int check = protocol.versionProtocol; - - if (current > check || check == -2) { - result = 1; - } else if (current == check) { - result = 0; - } - - return result; - } -} \ No newline at end of file diff --git a/src/main/resources/config1.12.2-Down.yml b/src/main/resources/config1.12.2-Down.yml new file mode 100644 index 0000000..c181ef7 --- /dev/null +++ b/src/main/resources/config1.12.2-Down.yml @@ -0,0 +1,306 @@ +Settings: + Prefix: '&7[&4Crazy &bAuctions&7]: ' #Prefix of when you get Crazy Auctions Messages. + GUIName: '&4Crazy &bAuctions&8' #Name of the Main GUI. + Players-Current-Items: '&8Your Current Listings' #The Name of the Player Current Items GUI. + Cancelled/Expired-Items: '&8Cancelled/Expired Listings' #Name of the Canceled/Expired GUI. + Buying-Item: '&8Purchase Item: Are You Sure?' #Name of the Buying GUI. + Bidding-On-Item: '&8You Are Bidding On This Item.' #Name of the Bidding GUI. + Categories: '&8Categories' #Name of the Category GUI. + Sell-Time: 2d #The time that each item will sell for. + Bid-Time: 2m 30s #Time for each item that is biddable. + Full-Expire-Time: 10d #The full time the item is in the crazy auctions. + Bid-Winner-Time: 20d #The time the winner of a bid has to claim their prize. + Minimum-Sell-Price: 10 #Minimum amount you can sell an item for. + Max-Beginning-Sell-Price: 1000000 #Max amount you can sell an item for. + Minimum-Bid-Price: 100 #Minimum starting bid. + Max-Beginning-Bid-Price: 1000000 #Maximum starting bid. + Allow-Damaged-Items: False #Allow items that have been damaged. + Category-Page-Opens-First: False #If set to true the categories' page will open when they do /CA. + Feature-Toggle: #Toggle if a feature is on or off. + Selling: true #Able to use the selling part of the auction house. + Bidding: true #Able to use the bidding part of the auction house. + Patches: + Macro-Dupe: true #Turn to false if you have an issue, but it should patch the bug. + Sounds: + Toggle: False #Disable the clicking sound. + Sound: 'CLICK' #Make sure if you use 1.8 or lower you use the 1.8 sound and 1.9 and up use 1.9 sounds. The default sound is 1.8. + #1.8 sounds are found here: http://badbones69.com/javadocs/1.8.8/org/bukkit/Sound.html + #1.9 sounds are found here: https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Sound.html + GUISettings: #Settings for things in the gui. + SellingItemLore: #The lore on items that are being sold. + - '&7-------------------------' + - '&aClick here to purchase.' + - '' + - '&9Price: &e$%price%' + - '&9Seller: &e%seller%' + - '&7-------------------------' + CurrentLore: #Lore on items that are in your current items GUI. + - '&7-------------------------' + - '&aClick here to cancel.' + - '' + - '&9Price: &e$%price%' + - '&9Expire: &e%time%' + - '&7-------------------------' + Cancelled/ExpiredLore: #Lore on items that are in your canceled/expired GUI. + - '&7-------------------------' + - '&aClick here to return to you.' + - '' + - '&9Full Expire: &e%time%' + - '&7-------------------------' + Bidding: #Lore on Bidding Items. + - '&7-------------------------' + - '&aClick here to bid.' + - '' + - '&9Seller: &e%seller%' + - '&9Current Bid: &e$%topbid%' + - '&9Top Bidder: &e%topbidder%' + - '&9Time Left: &e%time%' + - '&7-------------------------' + Category-Settings: + Armor: + Item: '315' + Toggle: true + Slot: 11 + Name: '&6&lArmor' + Lore: + - '&7This category contains all' + - '&7armor that is currently being sold.' + Weapons: + Item: '283' + Toggle: true + Slot: 12 + Name: '&6&lWeapons' + Lore: + - '&7This category contains all' + - '&7weapons that are currently being sold.' + Tools: + Item: '285' + Toggle: true + Slot: 13 + Name: '&6&lTools' + Lore: + - '&7This category contains all' + - '&7tools that are currently being sold.' + Food: + Item: '322' + Toggle: true + Slot: 14 + Name: '&6&lFood' + Lore: + - '&7This category contains all' + - '&7food that is currently being sold.' + Potions: + Item: '373:8227' + Toggle: true + Slot: 15 + Name: '&6&lPotions' + Lore: + - '&7This category contains all' + - '&7potions that are currently being sold.' + Blocks: + Item: '2' + Toggle: true + Slot: 16 + Name: '&6&lBlocks' + Lore: + - '&7This category contains all' + - '&7blocks that are currently being sold.' + Other: + Item: '371' + Toggle: true + Slot: 17 + Name: '&6&lOthers' + Lore: + - '&7This category contains all the' + - '&7other items currently being sold.' + None: + Item: '166' + Toggle: true + Slot: 23 + Name: '&6&lNone' + Lore: + - '&7This category contains all' + - '&7items currently being sold.' + OtherSettings: #Other Settings for the GUIs. + SellingItems: #The button for your current items. + Item: '264' #The item that this button is. + Toggle: true #If the item is in the gui or not. + Slot: 46 #The slot it is in. I recommend not changing these. If you do make sure they are still in the bottom row. + Name: '&6Items You are Selling' #Name of the item. + Lore: #Lore of the item. + - '&aClick here to view all the items you' + - '&aare currently selling on the auction.' + Cancelled/ExpiredItems: #The button for Canceled/Expired Items. + Item: '394' + Toggle: true + Slot: 47 + Name: '&6Collect Expired / Canceled Items' + Lore: + - '&aClick here to view and collect all of the' + - '&aitems you have canceled or has expired.' + PreviousPage: #The button for Previous Page. + Item: '339' + Toggle: true + Slot: 49 + Name: '&6Previous Page' + Lore: { } + Refesh: #The button for Refresh Page. + Item: '175' + Toggle: true + Slot: 50 + Name: '&6Refresh Page' + Lore: { } + NextPage: #The button for Next Page. + Item: '339' + Toggle: true + Slot: 51 + Name: '&6Next Page' + Lore: { } + Category1: #The button for Next Page. + Item: '54' + Toggle: true + Slot: 52 + Name: '&6Categories' + Lore: + - '&bCurrent Category: &6%category%' + - '&aWant to see items in specific categories?' + - '&aClick here to see all categories of items.' + Category2: #The button for Next Page. + Item: '54' + Toggle: true + Slot: 48 + Name: '&6Categories' + Lore: + - '&bCurrent Category: &6%category%' + - '&aWant to see items in specific categories?' + - '&aClick here to see all categories of items.' + Bidding/Selling: #Switch between Bidding and Selling. + Selling: + Item: '341' + Toggle: true + Slot: 53 + Name: '&6Currently looking at items being sold.' + Lore: + - '&7&l(&6&l!&7&l) &7Click here to see items' + - '&7that you can bid on.' + Bidding: + Item: '378' + Toggle: true + Slot: 53 + Name: '&6Currently looking at items that can be bid on.' + Lore: + - '&7&l(&6&l!&7&l) &7Click here to see items' + - '&7that you can buy at a price.' + WhatIsThis: #The info on all the Books buttons. + SellingShop: #The Book in the main shop. + Item: '340' + Toggle: true + Slot: 54 + Name: '&6What Is This Page?' + Lore: + - '&aThis is the crazy auctions, here you can' + - '&aput items for sale, and buy items' + - '&athat others have put for sale.' + - '' + - '&aThe auction is also a great place to make' + - '&amoney by selling items that others' + - '&amay be interested in buying.' + BiddingShop: #The Book in the main shop. + Item: '340' + Toggle: true + Slot: 54 + Name: '&6What Is This Page?' + Lore: + - '&aThis is the crazy auctions, here you can' + - '&aput items for sale, and bid on items' + - '&athat others have put for sale.' + - '' + - '&aThe bidding auction is also a great place to' + - '&amake money by bidding off items that others' + - '&amay be interested in bidding on.' + CurrentItems: #The Book in the Current items GUI. + Item: '340' + Toggle: true + Slot: 54 + Name: '&6What Is This Page?' + Lore: + - '&aThese are your current listings, all of' + - '&athe items you currenty have listed on' + - '&acrazy auctions are displayed here.' + - '' + - '&aYou can cancel and view your listings' + - '&aexpire time here.' + Cancelled/ExpiredItems: #The Book in the Canceled/Expired Items GUI. + Item: '340' + Toggle: true + Slot: 54 + Name: '&6What Is This Page?' + Lore: + - '&aThis page houses all of your cancelled and' + - '&aexpired items, when a listings is cancelled' + - '&aor expires you will be able to return that' + - '&aitem back to you from this menu.' + - '' + - '&aJust click on the item and if you have enough' + - '&ainventory space you will receive that item.' + Viewing: #The Book in the Viewing Items GUI. + Item: '340' + Toggle: true + Slot: 50 + Name: '&6What Is This Page?' + Lore: + - '&aThis page shows all the items that' + - '&aa player has currently on the bidding' + - '&aand selling market. You can quickly see' + - '&awhat a specific player is selling.' + Categories: #The Book in the Viewing Items GUI. + Item: '340' + Toggle: true + Slot: 54 + Name: '&6What Is This Page?' + Lore: + - '&aThis page shows all the categories' + - '&athat you can choose from. When you click' + - '&aa category it will open the gui with only' + - '&aitems that belong to that category.' + Back: #The Back Buttons. + Item: '339' + Slot: 46 + Name: '&6Back' + Return: #The Return Buttons. + Item: '390' + Slot: 50 + Name: '&6Return All' + Lore: + - '&aClick here to return all cancelled' + - '&aand expired items to your inventory.' + Confirm: #The Confirm Buttons. + Item: '160:5' + Name: '&aConfirm' + Cancel: #The Cancel Buttons. + Item: '160:14' + Name: '&cCancel' + Your-Item: #The item that shows when you try to buy/bid on your item. + Item: '166' + Name: '&cYou Can''t Purchase Your Own Item.' + Cant-Afford: #The item that shows when you can't afford this item. + Item: '166' + Name: '&cYou Can''t Afford This Item.' + Top-Bidder: #The item for when a player is already the top bidder. + Item: '166' + Name: '&cYou are already the top bidder.' + Bidding: #The item in the middle when bidding on an item. + Item: '160:15' + Name: '&7Bidding' + Lore: + - '&7<--&aAdd &cRemove&7-->' + - '&9Your Current Bid: &e$%bid%' + - '&9Current Top Bid: &e$%topbid%' + Bid: #The button for when you want to confirm your bid. + Item: '160:3' + Name: '&bBid Now' + Lore: + - '&7Click here to Bid Now.' + BlackList: + - '7' + - '120' \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config1.13-Up.yml similarity index 99% rename from src/main/resources/config.yml rename to src/main/resources/config1.13-Up.yml index ebaf756..eb10ebd 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config1.13-Up.yml @@ -19,6 +19,8 @@ Settings: Feature-Toggle: #Toggle if a feature is on or off. Selling: true #Able to use the selling part of the auction house. Bidding: true #Able to use the bidding part of the auction house. + Patches: + Macro-Dupe: true #Turn to false if you have an issue, but it should patch the bug. Sounds: Toggle: false #Disable the clicking sound. Sound: 'CLICK' #Make sure if you use 1.8 or lower you use the 1.8 sound and 1.9 and up use 1.9 sounds. The default sound is 1.8. diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 3150de6..5de4b8b 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,16 +1,12 @@ -name: "CrazyAuctions" -main: "${group}.CrazyAuctions" - -authors: [BadBones69, RyderBelserion] - -version: ${version} -api-version: "1.13" -description: ${description} - -softdepend: [Vault] - -website: https://modrinth.com/plugin/crazyauctions - +name: CrazyAuctions +author: BadBones69 +main: com.badbones69.crazyauctions.Main +website: https://www.spigotmc.org/resources/authors/badbones69.9719/ +version: ${version}${build.number} +depend: [Vault] +api-version: 1.13 +description: A plugin to auction off items globally. commands: - crazyauctions: - description: Opens the main menu for CrazyAuctions. \ No newline at end of file + ca: + description: Opens the Crazy Auctions GUI. + aliases: [crazyauction, crazyauctions, ah, hdv] \ No newline at end of file