This commit is contained in:
Jsinco 2024-02-25 20:59:50 +00:00 committed by GitHub
commit 2465c48e2d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
108 changed files with 2988 additions and 1916 deletions

2
.gitignore vendored
View File

@ -8,7 +8,7 @@
/build.xml
# vim
.*.sw[a-p]
.*.sw[a-breweryPlugin]
# IntelliJ
/.idea

View File

@ -1,3 +1,13 @@
# BreweryX
### This is a fork of the original Brewery plugin to add features and give support to Brewery
Need help, have a feature request, or found a bug? Join the discord [here](https://discord.gg/aV5Am7uxWr)!
# Old ReadME:
### Brewery is a Minecraft-Plugin for an alternate brewing process, including alcoholic Potions.
[![Build Status](https://github.com/DieReicheErethons/Brewery/actions/workflows/maven.yml/badge.svg)](https://github.com/DieReicheErethons/Brewery/actions/workflows/maven.yml)
@ -15,7 +25,7 @@
### JavaDocs
[JavaDocs on Jitpack](https://javadoc.jitpack.io/com/github/DieReicheErethons/Brewery/3.1.1/javadoc/index.html)
[JavaDocs on Jitpack](https://javadoc.jitpack.io/com/github/DieReicheErethons/Brewery/3.1.1/javadoc/index.html) (Old, new ones coming soon + wiki)
### Maven

27
pom.xml
View File

@ -4,7 +4,7 @@
<groupId>com.dre</groupId>
<artifactId>Brewery</artifactId>
<version>3.1.1</version>
<version>3.1.7</version>
<name>Brewery</name>
<properties>
@ -58,6 +58,7 @@
<artifactSet>
<includes>
<include>org.bstats:*</include>
<include>com.github.Anon8281:*</include>
</includes>
</artifactSet>
<relocations>
@ -65,6 +66,10 @@
<pattern>org.bstats</pattern>
<shadedPattern>com.dre.brewery.integration.bstats</shadedPattern>
</relocation>
<relocation>
<pattern>com.github.Anon8281.universalScheduler</pattern>
<shadedPattern>com.dre.brewery.integration.universalScheduler</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
@ -96,6 +101,11 @@
</plugins>
</build>
<repositories>
<repository>
<!-- GriefPrevention, SlimeFun, Towny, Brewery -->
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<repository>
<id>md_5-public</id>
<url>https://repo.md-5.net/content/groups/public/</url>
@ -113,11 +123,6 @@
<id>enginehub-maven</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<!-- GriefPrevention, SlimeFun, Towny, Brewery -->
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<repository>
<!-- LWC Extended -->
<id>ender-repo</id>
@ -248,7 +253,7 @@
<!-- https://www.spigotmc.org/resources/griefprevention.1884/history -->
<groupId>com.github.TechFortress</groupId>
<artifactId>GriefPrevention</artifactId>
<version>16.18.1</version>
<version>16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -296,7 +301,7 @@
<!-- https://www.spigotmc.org/resources/towny-advanced.72694/history -->
<groupId>com.github.TownyAdvanced</groupId>
<artifactId>Towny</artifactId>
<version>0.100.0.0</version>
<version>0.100.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -320,5 +325,11 @@
<version>16.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.Anon8281</groupId>
<artifactId>UniversalScheduler</artifactId>
<version>0.1.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -7,6 +7,9 @@
# Sprachedatei die genutzt werden sollte (befindet sich in plugins/Brewery/languages)
language: de
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Ob der Spieler beim nächsten Einloggen nach starker Trunkenheit am nächsten morgen Zuhause "aufwacht" (Ein home Plugin muss installiert sein!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# Item das beim Erbrechen mehrfach unaufsammelbar fallen gelassen wird [SOUL_SAND]
pukeItem: SOUL_SAND
pukeItem: [SOUL_SAND]
# Zeit in Sekunden bis die pukeitems despawnen, (mc standard wäre 300 = 5 min) [60]
# Wurde die item Despawnzeit in der spigot.yml verändert, verändert sich auch die pukeDespawnzeit in Abhängigkeit.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Ob in den Iteminformationen immer der Alkoholgehalt angezeigt weden soll, oder nur im Braustand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# Ob das reifen in -Minecraft- Fässern aktiviert ist und wie viele Brewery Getränke in die diese getan werden können [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -7,6 +7,9 @@
# Languagefile to be used (found in plugins/Brewery/languages)
language: en
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# If the player wakes up at /home when logging in after excessive drinking (/home plugin must be installed!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# Item that is dropped multiple times uncollectable when puking [SOUL_SAND]
pukeItem: SOUL_SAND
pukeItem: [SOUL_SAND]
# Time in seconds until the pukeitems despawn, (mc default is 300 = 5 min) [60]
# If the item despawn time was changed in the spigot.yml, the pukeDespawntime changes as well.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# If aging in -Minecraft- Barrels in enabled [true] and how many Brewery drinks can be put into them [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6
@ -126,6 +132,7 @@ customItems:
name: '&cRaspberry'
# -- Ingredients in the Cauldron --
# Which Ingredients are accepted by the Cauldron and the base potion resulting from them
# You only need to add something here if you want to specify a custom name or color for the base potion

View File

@ -8,6 +8,9 @@
# Fichier de langage utilisé (trouvable dans plugins/Brewery/languages)
language: fr
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Si le joueur se réveille à son /home lors de sa connexion après un excès alcool (Un plugin de /home est nécessaire!) [true]
enableHome: true
@ -33,7 +36,7 @@ enableKickOnOverdrink: false
enablePuke: true
# L'objet utilisé pour représenter le vomit [SOUL_SAND]
pukeItem: SOUL_SAND
pukeItem: [SOUL_SAND]
# Time in seconds until the pukeitems despawn, (mc default is 300 = 5 min) [60]
# If the item despawn time was changed in the spigot.yml, the pukeDespawntime changes as well.
@ -66,6 +69,9 @@ alwaysShowQuality: true
# Toujours indiquer la teneur en alcool sur les objets. S'il est false, il n'apparaîtra que dans le stand de brassage. [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# Combien de boissons de brasserie peuvent être mises dans les barils -Minecraft- [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -7,6 +7,9 @@
# Lingua da usare (fra quelle in plugins/Brewery/languages)
language: it
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Se il giocatore si sveglia nella sua /home dopo aver bevuto troppo(il plugin di /home deve essere installato!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# L'oggetto droppato in massa quando si vomita che dovrebbe rappresentare il vomito [SOUL_SAND]
pukeItem: SOUL_SAND
pukeItem: [SOUL_SAND]
# Tempo in secondi perché il vomito sparisca (il valore di minecraft di default è 300 = 5 min) [60]
# Se il tempo di scomparsa viene cambiato in spigot.yml anche pukeDespawntime cambia.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# If aging in -Minecraft- Barrels in enabled [true] and how many Brewery drinks can be put into them [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -7,6 +7,9 @@
# Sprachedatei die genutzt werden sollte (befindet sich in plugins/Brewery/languages)
language: de
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Ob der Spieler beim nächsten Einloggen nach starker Trunkenheit am nächsten morgen Zuhause "aufwacht" (Ein home Plugin muss installiert sein!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# Item das beim Erbrechen mehrfach unaufsammelbar fallen gelassen wird [Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# Zeit in Sekunden bis die pukeitems despawnen, (mc standard wäre 300 = 5 min) [60]
# Wurde die item Despawnzeit in der spigot.yml verändert, verändert sich auch die pukeDespawnzeit in Abhängigkeit.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Ob in den Iteminformationen immer der Alkoholgehalt angezeigt weden soll, oder nur im Braustand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# Ob das reifen in -Minecraft- Fässern aktiviert ist und wie viele Brewery Getränke in die diese getan werden können [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -7,6 +7,9 @@
# Languagefile to be used (found in plugins/Brewery/languages)
language: en
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# If the player wakes up at /home when logging in after excessive drinking (/home plugin must be installed!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# Item that is dropped multiple times uncollectable when puking [Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# Time in seconds until the pukeitems despawn, (mc default is 300 = 5 min) [60]
# If the item despawn time was changed in the spigot.yml, the pukeDespawntime changes as well.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# If aging in -Minecraft- Barrels in enabled [true] and how many Brewery drinks can be put into them [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6
@ -100,7 +106,7 @@ version: '3.1'
# material: Which type the item has to be
# name: Which name the item has to be (Formatting codes possible: such as &6)
# lore: What has to be in the lore of the item
# modeldata: Custom Model Data Int. Whatever Model data number the item has to have (NEEDS TO HAVE QUOTATIONS, SEE EXAMPLE)
customItems:
# Three Example Items
ex-item:
@ -126,6 +132,11 @@ customItems:
rasp:
name: '&cRaspberry'
modelitem:
material: paper
# modeldata must always be in quotations
modeldata: '12345'
blue-flowers:
matchAny: true
material:

View File

@ -7,6 +7,9 @@
# Languagefile to be used (found in plugins/Brewery/languages)
language: es
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# If the player wakes up at /home when logging in after excessive drinking (/home plugin must be installed!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# Item that is dropped multiple times uncollectable when puking [Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# Time in seconds until the pukeitems despawn, (mc default is 300 = 5 min) [60]
# If the item despawn time was changed in the spigot.yml, the pukeDespawntime changes as well.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# If aging in -Minecraft- Barrels in enabled [true] and how many Brewery drinks can be put into them [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -8,6 +8,9 @@
# Fichier de langage utilisé (trouvable dans plugins/Brewery/languages)
language: fr
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Si le joueur se réveille à son /home lors de sa connexion après un excès alcool (Un plugin de /home est nécessaire!) [true]
enableHome: true
@ -33,7 +36,7 @@ enableKickOnOverdrink: false
enablePuke: true
# L'objet utilisé pour représenter le vomit [Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# Time in seconds until the pukeitems despawn, (mc default is 300 = 5 min) [60]
# If the item despawn time was changed in the spigot.yml, the pukeDespawntime changes as well.
@ -66,6 +69,9 @@ alwaysShowQuality: true
# Toujours indiquer la teneur en alcool sur les objets. S'il est false, il n'apparaîtra que dans le stand de brassage. [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# Combien de boissons de brasserie peuvent être mises dans les barils -Minecraft- [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -7,6 +7,9 @@
# Lingua da usare (fra quelle in plugins/Brewery/languages)
language: it
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# Se il giocatore si sveglia nella sua /home dopo aver bevuto troppo(il plugin di /home deve essere installato!) [true]
enableHome: true
@ -32,7 +35,7 @@ enableKickOnOverdrink: false
enablePuke: true
# L'oggetto droppato in massa quando si vomita che dovrebbe rappresentare il vomito [Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# Tempo in secondi perché il vomito sparisca (il valore di minecraft di default è 300 = 5 min) [60]
# Se il tempo di scomparsa viene cambiato in spigot.yml anche pukeDespawntime cambia.
@ -65,6 +68,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# If aging in -Minecraft- Barrels in enabled [true] and how many Brewery drinks can be put into them [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -9,6 +9,9 @@
# 语言文件(可在plugins/Brewery/languages下找到)
language: zh
# Prefix used on messages
pluginPrefix: '&2[Brewery]&f '
# 喝高了的下线玩家会在家里醒来(需要/home等功能支持)[true]
enableHome: true
@ -34,7 +37,7 @@ enableKickOnOverdrink: false
enablePuke: true
# 呕吐物[Soul_Sand]
pukeItem: Soul_Sand
pukeItem: [Soul_Sand]
# 呕吐物消失的时间, 单位为秒(MC默认为300 = 5分钟)[60]
# 如果spigot.yml中的物品消失时间被变更, 此处也会变更.
@ -67,6 +70,9 @@ alwaysShowQuality: true
# Always show the alcohol content on the item. If false, it will only show in the brewing stand [false]
alwaysShowAlc: false
# If we should show who brewed the drink [false]
showBrewer: false
# MC自带的桶内可以存放多少饮品 [6]
ageInMCBarrels: true
maxBrewsInMCBarrels: 6

View File

@ -16,6 +16,7 @@ Brew_Years: Jahre
Brew_fermented: gegärt
Brew_minute: minute
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &cTränke haben nicht mehr in das Inventar gepasst'
@ -54,6 +55,7 @@ Etc_Page: Seite
Etc_Usage: 'Benutzung:'
Etc_Barrel: Fass
Etc_SealingTable: Trankversiegler
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew Copy [Anzahl]&9 Kopiert den Trank in deiner Hand'

View File

@ -16,6 +16,7 @@ Brew_Years: Years
Brew_fermented: fermented
Brew_minute: minute
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &cPotions did not fit into your inventory'
@ -54,6 +55,7 @@ Etc_Barrel: Barrel
Etc_Page: Page
Etc_Usage: 'Usage:'
Etc_SealingTable: Brew Sealing Table
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew copy [Quantity]&9 Copies the potion in your hand'

View File

@ -17,6 +17,7 @@ Brew_Years: Años
Brew_fermented: fermentado
Brew_minute: minuto
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &cLas pociones no cabían en tu inventario'
@ -55,6 +56,7 @@ Etc_Barrel: Barril
Etc_Page: Página
Etc_Usage: 'Usa:'
Etc_SealingTable: Mesa de sellado
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew copy [Cantidad]&9 Copia la poción en tu mano'

View File

@ -16,6 +16,7 @@ Brew_Years: Années
Brew_fermented: fermenté
Brew_minute: minute
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &cCes potions ne rentrent pas dans votre inventaire.'
@ -54,6 +55,7 @@ Etc_Barrel: Baril
Etc_Page: Page
Etc_Usage: 'Utilise:'
Etc_SealingTable: 'Table de scellage des boissons'
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Aide
Help_Copy: '&6/brew copy [Quantity]&9 Copie la potion qui est dans votre main'

View File

@ -16,6 +16,7 @@ Brew_Years: Anni
Brew_fermented: fermentata
Brew_minute: minuto
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# Comandi
CMD_Copy_Error: '&6&v1 &cLe copie di questa pozione non stavano nell''inventario.'
@ -54,6 +55,7 @@ Etc_Barrel: Barile
Etc_Page: Pagina
Etc_Usage: 'Utilizzo:'
Etc_SealingTable: Brew Sealing Table
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Aiuto
Help_Copy: '&6/brew copy [Quantità]&9 Copia la pozione che tieni in mano'

View File

@ -16,6 +16,7 @@ Brew_Years: года
Brew_fermented: ферментировано
Brew_minute: минут
Brew_Alc: Алк &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &cЗелья не поместились в инвентарь'
@ -54,6 +55,7 @@ Etc_Barrel: 'Бочка'
Etc_Page: 'Страница'
Etc_Usage: 'Использование:'
Etc_SealingTable: 'Стол закупорки бражки.'
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew copy [Quantity]&9 Копирует зелье в твоей руке'

View File

@ -16,6 +16,7 @@ Brew_Years: 年
Brew_fermented: 發酵
Brew_minute: 分鐘
Brew_Alc: Alc &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1 &c藥水不適合你的庫存'
@ -54,6 +55,7 @@ Etc_Barrel: 釀造桶
Etc_Page: 頁數
Etc_Usage: '用法:'
Etc_SealingTable: Brew Sealing Table
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew copy [數量]&9 複製手中的藥水'

View File

@ -16,6 +16,7 @@ Brew_Years: 年
Brew_fermented: 炖煮发酵
Brew_minute: 分钟
Brew_Alc: 酒精度 &v1ml
Brew_Brewer: 'Brewer: &v1'
# CMD
CMD_Copy_Error: '&6&v1&r, &c你的背包塞不下了.'
@ -54,6 +55,7 @@ Etc_Barrel: 木桶
Etc_Page:
Etc_Usage: '用途:'
Etc_SealingTable: Brew Sealing Table
Etc_UpdateAvailable: 'Update available: &a&v1 &f-> &a&v2 &bhttps://www.spigotmc.org/resources/breweryx.114777/'
# Help
Help_Copy: '&6/brew copy [数量] &9复制当前手中的饮品.'

View File

@ -1,9 +1,13 @@
name: Brewery
version: 3.1.1
main: com.dre.brewery.P
version: '${project.version}'
website: 'https://www.spigotmc.org/resources/breweryx.114777/'
main: com.dre.brewery.BreweryPlugin
softdepend: [LWC, LogBlock, WorldGuard, GriefPrevention, Vault, ChestShop, Shopkeepers, Towny, BlockLocker, Slimefun]
authors: [Milan Albrecht, Frank Baumann, ProgrammerDan, Daniel Saukel]
authors: [Milan Albrecht, Frank Baumann, ProgrammerDan, Daniel Saukel, Jsinco]
folia-supported: true
api-version: 1.13
libraries:
- 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.10'
commands:
brewery:
description: Mostly admin commands to create/modify Brews and drunkeness
@ -21,6 +25,7 @@ permissions:
brewery.cauldron.time: true
brewery.cauldron.insert: true
brewery.cauldron.fill: true
brewery.cmd.version: true
# Mod
brewery.mod:
description: Allow to maintain Wakeup Points and to login even if overdrunken
@ -33,6 +38,7 @@ permissions:
description: Gives access to Every Command and most bypasses
default: op
children:
brewery.update: true
brewery.user: true
brewery.mod: true
brewery.cmd.info: true
@ -48,7 +54,9 @@ permissions:
brewery.cmd.delete: true
brewery.cmd.static: true
brewery.cmd.reload: true
# *
brewery.cmd.itemname: true
brewery.cmd.reloadaddons: true
# *
brewery.*:
description: Gives Access to every Permission, including bypasses and overrides
children:
@ -89,6 +97,12 @@ permissions:
description: Make Brews Static
brewery.cmd.reload:
description: Reload config
brewery.cmd.itemname:
description: View the material name of an item
brewery.cmd.reloadaddons:
description: Reload all Addons
brewery.cmd.version:
description: See misc info about BreweryX
# -- Barrel --
brewery.createbarrel:
@ -137,3 +151,7 @@ permissions:
brewery.recovery.2:
description: How quickly the player will naturally reduce his drunkeness per minute
# -- Misc --
brewery.update:
description: Get notified about new versions

View File

@ -21,13 +21,14 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class BCauldron {
public static final byte EMPTY = 0, SOME = 1, FULL = 2;
public static final int PARTICLEPAUSE = 15;
public static Random particleRandom = new Random();
private static Set<UUID> plInteracted = new HashSet<>(); // Interact Event helper
public static Map<Block, BCauldron> bcauldrons = new HashMap<>(); // All active cauldrons. Mapped to their block for fast retrieve
public static Map<Block, BCauldron> bcauldrons = new ConcurrentHashMap<>(); // All active cauldrons. Mapped to their block for fast retrieve
private BIngredients ingredients = new BIngredients();
private final Block block;
@ -35,7 +36,7 @@ public class BCauldron {
private boolean changed = false; // Not really needed anymore
private Optional<BCauldronRecipe> particleRecipe; // null if we haven't checked, empty if there is none
private Color particleColor;
private Location particleLocation;
private final Location particleLocation;
public BCauldron(Block block) {
this.block = block;
@ -149,7 +150,7 @@ public class BCauldron {
}
IngedientAddEvent event = new IngedientAddEvent(player, block, bcauldron, ingredient.clone(), rItem);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
bcauldron.add(event.getIngredient(), event.getRecipeItem());
//P.p.debugLog("Cauldron add: t2 " + ((t2 - t1) / 1000) + " t3: " + ((t3 - t2) / 1000) + " t4: " + ((t4 - t3) / 1000) + " t5: " + ((t5 - t4) / 1000) + "µs");
@ -164,13 +165,13 @@ public class BCauldron {
// fills players bottle with cooked brew
public boolean fill(Player player, Block block) {
if (!player.hasPermission("brewery.cauldron.fill")) {
P.p.msg(player, P.p.languageReader.get("Perms_NoCauldronFill"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Perms_NoCauldronFill"));
return true;
}
ItemStack potion = ingredients.cook(state);
ItemStack potion = ingredients.cook(state, player.getName());
if (potion == null) return false;
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
BlockData data = block.getBlockData();
if (!(data instanceof Levelled)) {
bcauldrons.remove(block);
@ -220,7 +221,7 @@ public class BCauldron {
changed = true;
}
}
if (P.use1_9) {
if (BreweryPlugin.use1_9) {
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 1f, 1f);
}
// Bukkit Bug, inventory not updating while in event so this
@ -235,15 +236,15 @@ public class BCauldron {
// prints the current cooking time to the player
public static void printTime(Player player, Block block) {
if (!player.hasPermission("brewery.cauldron.time")) {
P.p.msg(player, P.p.languageReader.get("Error_NoPermissions"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Error_NoPermissions"));
return;
}
BCauldron bcauldron = get(block);
if (bcauldron != null) {
if (bcauldron.state > 1) {
P.p.msg(player, P.p.languageReader.get("Player_CauldronInfo1", "" + bcauldron.state));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Player_CauldronInfo1", "" + bcauldron.state));
} else {
P.p.msg(player, P.p.languageReader.get("Player_CauldronInfo2"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Player_CauldronInfo2"));
}
}
}
@ -274,7 +275,7 @@ public class BCauldron {
block.getWorld().spawnParticle(Particle.WATER_SPLASH, particleLocation, 1, 0.2, 0, 0.2);
}
if (P.use1_13 && particleRandom.nextFloat() > 0.4) {
if (BreweryPlugin.use1_13 && particleRandom.nextFloat() > 0.4) {
// Two hovering pixely dust clouds, a bit offset and with DustOptions to give some color and size
block.getWorld().spawnParticle(Particle.REDSTONE, particleLocation, 2, 0.15, 0.2, 0.15, new Particle.DustOptions(color, 1.5f));
}
@ -372,7 +373,7 @@ public class BCauldron {
for (BCauldron cauldron : bcauldrons.values()) {
if (particleRandom.nextFloat() < chance) {
cauldron.cookEffect();
BreweryPlugin.getScheduler().runTask(cauldron.block.getLocation(), cauldron::cookEffect);
}
}
}
@ -384,7 +385,7 @@ public class BCauldron {
Block clickedBlock = event.getClickedBlock();
assert clickedBlock != null;
if (materialInHand == null || materialInHand == Material.AIR || materialInHand == Material.BUCKET) {
if (materialInHand == Material.AIR || materialInHand == Material.BUCKET) {
return;
} else if (materialInHand == LegacyUtil.CLOCK) {
@ -415,7 +416,7 @@ public class BCauldron {
// Ignore Water Buckets
} else if (materialInHand == Material.WATER_BUCKET) {
if (!P.use1_9) {
if (!BreweryPlugin.use1_9) {
// reset < 1.9 cauldron when refilling to prevent unlimited source of potions
// We catch >=1.9 cases in the Cauldron Listener
if (LegacyUtil.getFillLevel(clickedBlock) == 1) {
@ -437,11 +438,11 @@ public class BCauldron {
// Certain Items in Hand cause one of them to be cancelled or not called at all sometimes.
// We mark if a player had the event for the main hand
// If not, we handle the main hand in the event for the off hand
if (P.use1_9) {
if (BreweryPlugin.use1_9) {
if (event.getHand() == EquipmentSlot.HAND) {
final UUID id = player.getUniqueId();
plInteracted.add(id);
P.p.getServer().getScheduler().runTask(P.p, () -> plInteracted.remove(id));
BreweryPlugin.getScheduler().runTask(() -> plInteracted.remove(id));
} else if (event.getHand() == EquipmentSlot.OFF_HAND) {
if (!plInteracted.remove(player.getUniqueId())) {
item = player.getInventory().getItemInMainHand();
@ -457,7 +458,7 @@ public class BCauldron {
if (item == null) return;
if (!player.hasPermission("brewery.cauldron.insert")) {
P.p.msg(player, P.p.languageReader.get("Perms_NoCauldronInsert"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Perms_NoCauldronInsert"));
return;
}
if (ingredientAdd(clickedBlock, item, player)) {
@ -523,7 +524,7 @@ public class BCauldron {
* Unload all Cauldrons that have are in a unloaded World
*/
public static void unloadWorlds() {
List<World> worlds = P.p.getServer().getWorlds();
List<World> worlds = BreweryPlugin.getInstance().getServer().getWorlds();
bcauldrons.keySet().removeIf(block -> !worlds.contains(block.getWorld()));
}
@ -563,7 +564,7 @@ public class BCauldron {
// bukkit bug not updating the inventory while executing event, have to
// schedule the give
public static void giveItem(final Player player, final ItemStack item) {
P.p.getServer().getScheduler().runTaskLater(P.p, () -> player.getInventory().addItem(item), 1L);
BreweryPlugin.getScheduler().runTaskLater(() -> player.getInventory().addItem(item), 1L);
}
}

View File

@ -1,7 +1,8 @@
package com.dre.brewery;
import com.dre.brewery.lore.BrewLore;
import org.bukkit.Bukkit;
import com.github.Anon8281.universalScheduler.UniversalRunnable;
import com.github.Anon8281.universalScheduler.scheduling.tasks.MyScheduledTask;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
@ -10,10 +11,9 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.BrewerInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Updated for 1.9 to replicate the "Brewing" process for distilling.
@ -27,13 +27,13 @@ import java.util.Map;
public class BDistiller {
private static final int DISTILLTIME = 400;
private static Map<Block, BDistiller> trackedDistillers = new HashMap<>();
private static Map<Block, BDistiller> trackedDistillers = new ConcurrentHashMap<>();
private int taskId;
private MyScheduledTask task;
private int runTime = -1;
private int brewTime = -1;
private Block standBlock;
private int fuel;
private final Block standBlock;
private final int fuel;
public BDistiller(Block standBlock, int fuel) {
this.standBlock = standBlock;
@ -41,11 +41,11 @@ public class BDistiller {
}
public void cancelDistill() {
Bukkit.getScheduler().cancelTask(taskId); // cancel prior
task.cancel(); // cancel prior
}
public void start() {
taskId = new DistillRunnable().runTaskTimer(P.p, 2L, 1L).getTaskId();
task = new DistillRunnable().runTaskTimer(BreweryPlugin.getInstance(), 2L, 1L);
}
public static void distillerClick(InventoryClickEvent event) {
@ -167,45 +167,48 @@ public class BDistiller {
}
}
public class DistillRunnable extends BukkitRunnable {
public class DistillRunnable extends UniversalRunnable {
private Brew[] contents = null;
@Override
public void run() {
BlockState now = standBlock.getState();
if (now instanceof BrewingStand) {
BrewingStand stand = (BrewingStand) now;
if (brewTime == -1) { // check at the beginning for distillables
if (!prepareForDistillables(stand)) {
return;
BreweryPlugin.getScheduler().runTask(standBlock.getLocation(), () -> {
BlockState now = standBlock.getState();
if (now instanceof BrewingStand) {
BrewingStand stand = (BrewingStand) now;
if (brewTime == -1) { // check at the beginning for distillables
if (!prepareForDistillables(stand)) {
return;
}
}
}
brewTime--; // count down.
stand.setBrewingTime((int) ((float) brewTime / ((float) runTime / (float) DISTILLTIME)) + 1);
brewTime--; // count down.
stand.setBrewingTime((int) ((float) brewTime / ((float) runTime / (float) DISTILLTIME)) + 1);
if (brewTime <= 1) { // Done!
contents = getDistillContents(stand.getInventory()); // Get the contents again at the end just in case
stand.setBrewingTime(0);
stand.update();
if (!runDistill(stand.getInventory(), contents)) {
this.cancel();
trackedDistillers.remove(standBlock);
P.p.debugLog("All done distilling");
if (brewTime <= 1) { // Done!
contents = getDistillContents(stand.getInventory()); // Get the contents again at the end just in case
stand.setBrewingTime(0);
stand.update();
if (!runDistill(stand.getInventory(), contents)) {
this.cancel();
trackedDistillers.remove(standBlock);
BreweryPlugin.getInstance().debugLog("All done distilling");
} else {
brewTime = -1; // go again.
BreweryPlugin.getInstance().debugLog("Can distill more! Continuing.");
}
} else {
brewTime = -1; // go again.
P.p.debugLog("Can distill more! Continuing.");
stand.update();
}
} else {
stand.update();
this.cancel();
trackedDistillers.remove(standBlock);
BreweryPlugin.getInstance().debugLog("The block was replaced; not a brewing stand.");
}
} else {
this.cancel();
trackedDistillers.remove(standBlock);
P.p.debugLog("The block was replaced; not a brewing stand.");
}
});
}
private boolean prepareForDistillables(BrewingStand stand) {
BrewerInventory inventory = stand.getInventory();
if (contents == null) {
@ -217,7 +220,7 @@ public class BDistiller {
case 1:
// Custom potion but not for distilling. Stop any brewing and cancel this task
if (stand.getBrewingTime() > 0) {
if (P.use1_11) {
if (BreweryPlugin.use1_11) {
// The trick below doesnt work in 1.11, but we dont need it anymore
// This should only happen with older Brews that have been made with the old Potion Color System
// This causes standard potions to not brew in the brewing stand if put together with Brews, but the bubble animation will play
@ -236,12 +239,12 @@ public class BDistiller {
this.cancel();
trackedDistillers.remove(standBlock);
showAlc(inventory, contents);
P.p.debugLog("nothing to distill");
BreweryPlugin.getInstance().debugLog("nothing to distill");
return false;
default:
runTime = getLongestDistillTime(contents);
brewTime = runTime;
P.p.debugLog("using brewtime: " + runTime);
BreweryPlugin.getInstance().debugLog("using brewtime: " + runTime);
}
return true;

View File

@ -101,7 +101,7 @@ public class BIngredients {
/**
* returns an Potion item with cooked ingredients
*/
public ItemStack cook(int state) {
public ItemStack cook(int state, String brewer) {
ItemStack potion = new ItemStack(Material.POTION);
PotionMeta potionMeta = (PotionMeta) potion.getItemMeta();
@ -119,12 +119,13 @@ public class BIngredients {
// Potion is best with cooking only
int quality = (int) Math.round((getIngredientQuality(cookRecipe) + getCookingQuality(cookRecipe, false)) / 2.0);
int alc = (int) Math.round(cookRecipe.getAlcohol() * ((float) quality / 10.0f));
P.p.debugLog("cooked potion has Quality: " + quality + ", Alc: " + alc);
BreweryPlugin.getInstance().debugLog("cooked potion has Quality: " + quality + ", Alc: " + alc);
brew = new Brew(quality, alc, cookRecipe, this);
BrewLore lore = new BrewLore(brew, potionMeta);
lore.updateQualityStars(false);
lore.updateCustomLore();
lore.updateAlc(false);
lore.updateBrewer(brewer);
lore.addOrReplaceEffects(brew.getEffects(), brew.getQuality());
lore.write();
@ -137,12 +138,12 @@ public class BIngredients {
brew = new Brew(this);
if (state <= 0) {
cookedName = P.p.languageReader.get("Brew_ThickBrew");
cookedName = BreweryPlugin.getInstance().languageReader.get("Brew_ThickBrew");
PotionColor.BLUE.colorBrew(potionMeta, potion, false);
} else {
BCauldronRecipe cauldronRecipe = getCauldronRecipe();
if (cauldronRecipe != null) {
P.p.debugLog("Found Cauldron Recipe: " + cauldronRecipe.getName());
BreweryPlugin.getInstance().debugLog("Found Cauldron Recipe: " + cauldronRecipe.getName());
cookedName = cauldronRecipe.getName();
if (cauldronRecipe.getLore() != null) {
BrewLore lore = new BrewLore(brew, potionMeta);
@ -150,7 +151,7 @@ public class BIngredients {
lore.write();
}
cauldronRecipe.getColor().colorBrew(potionMeta, potion, true);
if (P.use1_14 && cauldronRecipe.getCmData() != 0) {
if (BreweryPlugin.use1_14 && cauldronRecipe.getCmData() != 0) {
potionMeta.setCustomModelData(cauldronRecipe.getCmData());
}
}
@ -158,11 +159,11 @@ public class BIngredients {
}
if (cookedName == null) {
// if no name could be found
cookedName = P.p.languageReader.get("Brew_Undefined");
cookedName = BreweryPlugin.getInstance().languageReader.get("Brew_Undefined");
PotionColor.CYAN.colorBrew(potionMeta, potion, true);
}
potionMeta.setDisplayName(P.p.color("&f" + cookedName));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + cookedName));
//if (!P.use1_14) {
// Before 1.14 the effects duration would strangely be only a quarter of what we tell it to be
// This is due to the Duration Modifier, that is removed in 1.14
@ -173,13 +174,13 @@ public class BIngredients {
brew.touch();
BrewModifyEvent modifyEvent = new BrewModifyEvent(brew, potionMeta, BrewModifyEvent.Type.FILL);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
return null;
}
brew.save(potionMeta);
potion.setItemMeta(potionMeta);
P.p.stats.metricsForCreate(false);
BreweryPlugin.getInstance().stats.metricsForCreate(false);
return potion;
}
@ -222,7 +223,7 @@ public class BIngredients {
// needs riping in barrel
ageQuality = getAgeQuality(recipe, time);
woodQuality = getWoodQuality(recipe, wood);
P.p.debugLog("Ingredient Quality: " + ingredientQuality + " Cooking Quality: " + cookingQuality +
BreweryPlugin.getInstance().debugLog("Ingredient Quality: " + ingredientQuality + " Cooking Quality: " + cookingQuality +
" Wood Quality: " + woodQuality + " age Quality: " + ageQuality + " for " + recipe.getName(5));
// is this recipe better than the previous best?
@ -231,7 +232,7 @@ public class BIngredients {
bestRecipe = recipe;
}
} else {
P.p.debugLog("Ingredient Quality: " + ingredientQuality + " Cooking Quality: " + cookingQuality + " for " + recipe.getName(5));
BreweryPlugin.getInstance().debugLog("Ingredient Quality: " + ingredientQuality + " Cooking Quality: " + cookingQuality + " for " + recipe.getName(5));
// calculate quality without age and barrel
if ((((float) ingredientQuality + cookingQuality) / 2) > quality) {
quality = ((float) ingredientQuality + cookingQuality) / 2;
@ -241,7 +242,7 @@ public class BIngredients {
}
}
if (bestRecipe != null) {
P.p.debugLog("best recipe: " + bestRecipe.getName(5) + " has Quality= " + quality);
BreweryPlugin.getInstance().debugLog("best recipe: " + bestRecipe.getName(5) + " has Quality= " + quality);
}
return bestRecipe;
}
@ -471,11 +472,11 @@ public class BIngredients {
List<Ingredient> ing = new ArrayList<>(size);
for (; size > 0; size--) {
ItemLoader itemLoader = new ItemLoader(dataVersion, in, in.readUTF());
if (!P.p.ingredientLoaders.containsKey(itemLoader.getSaveID())) {
P.p.errorLog("Ingredient Loader not found: " + itemLoader.getSaveID());
if (!BreweryPlugin.getInstance().ingredientLoaders.containsKey(itemLoader.getSaveID())) {
BreweryPlugin.getInstance().errorLog("Ingredient Loader not found: " + itemLoader.getSaveID());
break;
}
Ingredient loaded = P.p.ingredientLoaders.get(itemLoader.getSaveID()).apply(itemLoader);
Ingredient loaded = BreweryPlugin.getInstance().ingredientLoaders.get(itemLoader.getSaveID()).apply(itemLoader);
int amount = in.readShort();
if (loaded != null) {
loaded.setAmount(amount);

View File

@ -9,8 +9,10 @@ import com.dre.brewery.lore.BrewLore;
import com.dre.brewery.recipe.BEffect;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.PermissionUtil;
import com.github.Anon8281.universalScheduler.scheduling.tasks.MyScheduledTask;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@ -28,11 +30,12 @@ import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class BPlayer {
private static Map<String, BPlayer> players = new HashMap<>();// Players uuid and BPlayer
private static Map<Player, Integer> pTasks = new HashMap<>();// Player and count
private static int taskId;
private static ConcurrentHashMap<String, BPlayer> players = new ConcurrentHashMap<>();// Players uuid and BPlayer
private static ConcurrentHashMap<Player, Integer> pTasks = new ConcurrentHashMap<>();// Player and count
private static MyScheduledTask task;
private static Random pukeRand;
private final String uuid;
@ -67,9 +70,9 @@ public class BPlayer {
// This method may be slow and should not be used if not needed
@Nullable
public static BPlayer getByName(String playerName) {
if (P.useUUID) {
if (BreweryPlugin.useUUID) {
for (Map.Entry<String, BPlayer> entry : players.entrySet()) {
OfflinePlayer p = P.p.getServer().getOfflinePlayer(UUID.fromString(entry.getKey()));
OfflinePlayer p = BreweryPlugin.getInstance().getServer().getOfflinePlayer(UUID.fromString(entry.getKey()));
if (p != null) {
String name = p.getName();
if (name != null) {
@ -86,9 +89,9 @@ public class BPlayer {
// This method may be slow and should not be used if not needed
public static boolean hasPlayerbyName(String playerName) {
if (P.useUUID) {
if (BreweryPlugin.useUUID) {
for (Map.Entry<String, BPlayer> entry : players.entrySet()) {
OfflinePlayer p = P.p.getServer().getOfflinePlayer(UUID.fromString(entry.getKey()));
OfflinePlayer p = BreweryPlugin.getInstance().getServer().getOfflinePlayer(UUID.fromString(entry.getKey()));
if (p != null) {
String name = p.getName();
if (name != null) {
@ -159,7 +162,7 @@ public class BPlayer {
// In this event the added alcohol amount is calculated, based on the sensitivity permission
BrewDrinkEvent drinkEvent = new BrewDrinkEvent(brew, meta, player, bPlayer);
if (meta != null) {
P.p.getServer().getPluginManager().callEvent(drinkEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(drinkEvent);
if (drinkEvent.isCancelled()) {
if (bPlayer.drunkeness <= 0) {
bPlayer.remove();
@ -171,7 +174,7 @@ public class BPlayer {
if (brew.hasRecipe()) {
brew.getCurrentRecipe().applyDrinkFeatures(player, brew.getQuality());
}
P.p.stats.forDrink(brew);
BreweryPlugin.getInstance().stats.forDrink(brew);
int brewAlc = drinkEvent.getAddedAlcohol();
int quality = drinkEvent.getQuality();
@ -218,8 +221,8 @@ public class BPlayer {
try {
// It this returns false, then the Action Bar is not supported. Do not repeat the message as it was sent into chat
if (sendDrunkenessMessage(player)) {
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> sendDrunkenessMessage(player), 40);
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> sendDrunkenessMessage(player), 80);
BreweryPlugin.getScheduler().runTaskLater(() -> sendDrunkenessMessage(player), 40);
BreweryPlugin.getScheduler().runTaskLater(() -> sendDrunkenessMessage(player), 80);
}
} catch (Exception e) {
e.printStackTrace();
@ -242,7 +245,7 @@ public class BPlayer {
hangover = true;
}
b.append(P.p.languageReader.get(hangover ? "Player_Hangover" : "Player_Drunkeness"));
b.append(BreweryPlugin.getInstance().languageReader.get(hangover ? "Player_Hangover" : "Player_Drunkeness"));
// Drunkeness or Hangover Strength Bars
b.append(": §7[");
@ -302,8 +305,8 @@ public class BPlayer {
}
b.append("§7]");
final String text = b.toString();
if (hangover && P.use1_11) {
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> player.sendTitle("", text, 30, 100, 90), 160);
if (hangover && BreweryPlugin.use1_11) {
BreweryPlugin.getScheduler().runTaskLater(() -> player.sendTitle("", text, 30, 100, 90), 160);
return false;
}
try {
@ -321,10 +324,10 @@ public class BPlayer {
drunkeness = 100;
syncToSQL(false);
if (BConfig.overdrinkKick && !player.hasPermission("brewery.bypass.overdrink")) {
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> passOut(player), 1);
BreweryPlugin.getScheduler().runTaskLater(() -> passOut(player), 1);
} else {
addPuke(player, 60 + (int) (Math.random() * 60.0));
P.p.msg(player, P.p.languageReader.get("Player_CantDrink"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Player_CantDrink"));
}
}
@ -393,7 +396,7 @@ public class BPlayer {
if (time == 0) {
// push him only to the side? or any direction
// like now
if (P.use1_9) { // Pushing is way stronger in 1.9
if (BreweryPlugin.use1_9) { // Pushing is way stronger in 1.9
push.setX((Math.random() - 0.5) / 2.0);
push.setZ((Math.random() - 0.5) / 2.0);
} else {
@ -402,7 +405,7 @@ public class BPlayer {
}
push.multiply(BConfig.stumbleModifier);
PlayerPushEvent pushEvent = new PlayerPushEvent(player, push, this);
P.p.getServer().getPluginManager().callEvent(pushEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(pushEvent);
push = pushEvent.getPush();
if (pushEvent.isCancelled() || push.lengthSquared() <= 0) {
time = -10;
@ -424,7 +427,7 @@ public class BPlayer {
}
public void passOut(Player player) {
player.kickPlayer(P.p.languageReader.get("Player_DrunkPassOut"));
player.kickPlayer(BreweryPlugin.getInstance().languageReader.get("Player_DrunkPassOut"));
offlineDrunk = drunkeness;
syncToSQL(false);
}
@ -432,6 +435,10 @@ public class BPlayer {
// #### Login ####
public boolean canJoinSimpleStatus() {
return canJoin() == 0;
}
// can the player login or is he too drunk
public int canJoin() {
if (drunkeness <= 70) {
@ -467,7 +474,7 @@ public class BPlayer {
return;
}
// delayed login event as the player is not fully accessible pre login
P.p.getServer().getScheduler().runTaskLater(P.p, () -> login(player), 1L);
BreweryPlugin.getScheduler().runTaskLater(() -> login(player), 1L);
}
// he may be having a hangover
@ -491,7 +498,7 @@ public class BPlayer {
Location randomLoc = Wakeup.getRandom(player.getLocation());
if (randomLoc != null) {
player.teleport(randomLoc);
P.p.msg(player, P.p.languageReader.get("Player_Wake"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Player_Wake"));
}
}
offlineDrunk = 0;
@ -516,7 +523,7 @@ public class BPlayer {
} else if (homeType.startsWith("cmd:")) {
player.performCommand(homeType.substring(4));
} else {
P.p.errorLog("Config.yml 'homeType: " + homeType + "' unknown!");
BreweryPlugin.getInstance().errorLog("Config.yml 'homeType: " + homeType + "' unknown!");
}
if (home != null) {
player.teleport(home);
@ -566,14 +573,14 @@ public class BPlayer {
}
PlayerPukeEvent event = new PlayerPukeEvent(player, count);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
if (event.isCancelled() || event.getCount() < 1) {
return;
}
BUtil.reapplyPotionEffect(player, PotionEffectType.HUNGER.createEffect(80, 4), true);
if (pTasks.isEmpty()) {
taskId = P.p.getServer().getScheduler().scheduleSyncRepeatingTask(P.p, BPlayer::pukeTask, 1L, 1L);
task = BreweryPlugin.getScheduler().runTaskTimer(player, BPlayer::pukeTask, 1L, 1L);
}
pTasks.put(player, event.getCount());
}
@ -594,7 +601,7 @@ public class BPlayer {
}
}
if (pTasks.isEmpty()) {
P.p.getServer().getScheduler().cancelTask(taskId);
task.cancel();
}
}
@ -602,8 +609,8 @@ public class BPlayer {
if (pukeRand == null) {
pukeRand = new Random();
}
if (BConfig.pukeItem == null || BConfig.pukeItem == Material.AIR) {
BConfig.pukeItem = Material.SOUL_SAND;
if (BConfig.pukeItem == null || BConfig.pukeItem.isEmpty()) {
BConfig.pukeItem = List.of(Material.SOUL_SAND);
}
Location loc = player.getLocation();
loc.setY(loc.getY() + 1.1);
@ -612,11 +619,12 @@ public class BPlayer {
Vector direction = loc.getDirection();
direction.multiply(0.5);
loc.add(direction);
Item item = player.getWorld().dropItem(loc, new ItemStack(BConfig.pukeItem));
Item item = player.getWorld().dropItem(loc, new ItemStack(BConfig.pukeItem.get(new Random().nextInt(BConfig.pukeItem.size()))));
item.setVelocity(direction);
item.setPickupDelay(32767); // Item can never be picked up when pickup delay is 32767
item.setMetadata("brewery_puke", new FixedMetadataValue(P.p, true));
if (P.use1_14) item.setPersistent(false); // No need to save Puke items
item.setMetadata("brewery_puke", new FixedMetadataValue(BreweryPlugin.getInstance(), true));
if (BreweryPlugin.use1_14) item.setPersistent(false); // No need to save Puke items
int pukeDespawntime = BConfig.pukeDespawntime;
if (pukeDespawntime >= 5800) {
@ -641,7 +649,7 @@ public class BPlayer {
public static void applyEffects(List<PotionEffect> effects, Player player, PlayerEffectEvent.EffectType effectType) {
PlayerEffectEvent event = new PlayerEffectEvent(player, effectType, effects);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
effects = event.getEffects();
if (event.isCancelled() || effects == null) {
return;
@ -660,20 +668,20 @@ public class BPlayer {
} else if (duration < 115) {
duration = 115;
}
if (!P.use1_14) {
if (!BreweryPlugin.use1_14) {
duration *= 4;
}
List<PotionEffect> l = new ArrayList<>(1);
l.add(PotionEffectType.CONFUSION.createEffect(duration, 0));
PlayerEffectEvent event = new PlayerEffectEvent(player, PlayerEffectEvent.EffectType.ALCOHOL, l);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
l = event.getEffects();
if (event.isCancelled() || l == null) {
return;
}
for (PotionEffect effect : l) {
effect.apply(player);
BreweryPlugin.getScheduler().runTask(player, () -> effect.apply(player)); // Fix can't add effect to entities Async
}
}
@ -690,7 +698,7 @@ public class BPlayer {
duration = 0;
}
}
if (!P.use1_14) {
if (!BreweryPlugin.use1_14) {
duration *= 4;
}
if (duration > 0) {
@ -705,7 +713,7 @@ public class BPlayer {
} else {
duration = 30;
}
if (!P.use1_14) {
if (!BreweryPlugin.use1_14) {
duration *= 4;
}
out.add(PotionEffectType.BLINDNESS.createEffect(duration, 0));
@ -716,7 +724,7 @@ public class BPlayer {
public static void addQualityEffects(int quality, int brewAlc, Player player) {
List<PotionEffect> list = getQualityEffects(quality, brewAlc);
PlayerEffectEvent event = new PlayerEffectEvent(player, PlayerEffectEvent.EffectType.QUALITY, list);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
list = event.getEffects();
if (event.isCancelled() || list == null) {
return;
@ -750,7 +758,7 @@ public class BPlayer {
public void hangoverEffects(final Player player) {
int duration = offlineDrunk * 25 * getHangoverQuality();
if (!P.use1_14) {
if (!BreweryPlugin.use1_14) {
duration *= 2;
}
int amplifier = getHangoverQuality() / 3;
@ -760,7 +768,7 @@ public class BPlayer {
list.add(PotionEffectType.HUNGER.createEffect(duration, amplifier));
PlayerEffectEvent event = new PlayerEffectEvent(player, PlayerEffectEvent.EffectType.HANGOVER, list);
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
list = event.getEffects();
if (event.isCancelled() || list == null) {
return;
@ -867,7 +875,7 @@ public class BPlayer {
public int getQuality() {
if (drunkeness == 0) {
P.p.errorLog("drunkeness should not be 0!");
BreweryPlugin.getInstance().errorLog("drunkeness should not be 0!");
return quality;
}
if (drunkeness < 0) {
@ -902,4 +910,17 @@ public class BPlayer {
public void setAlcRecovery(int alcRecovery) {
this.alcRecovery = alcRecovery;
}
public String getName() {
Player player = BUtil.getPlayerfromString(uuid);
OfflinePlayer offlinePlayer;
if (player != null) {
return player.getName();
} else {
offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(uuid));
}
return offlinePlayer.getName();
}
}

View File

@ -1,5 +1,6 @@
package com.dre.brewery;
import com.github.Anon8281.universalScheduler.scheduling.tasks.MyScheduledTask;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Sound;
@ -12,7 +13,6 @@ import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
@ -22,20 +22,20 @@ import java.util.Iterator;
* <p>Class doesn't load in mc 1.12 and lower (Can't find RecipeChoice, BlockData and NamespacedKey)
*/
public class BSealer implements InventoryHolder {
public static final NamespacedKey TAG_KEY = new NamespacedKey(P.p, "SealingTable");
public static final NamespacedKey TAG_KEY = new NamespacedKey(BreweryPlugin.getInstance(), "SealingTable");
public static boolean recipeRegistered = false;
public static boolean inventoryHolderWorking = true;
private final Inventory inventory;
private final Player player;
private short[] slotTime = new short[9];
private final short[] slotTime = new short[9];
private ItemStack[] contents = null;
private BukkitTask task;
private MyScheduledTask task;
public BSealer(Player player) {
this.player = player;
if (inventoryHolderWorking) {
Inventory inv = P.p.getServer().createInventory(this, InventoryType.DISPENSER, P.p.languageReader.get("Etc_SealingTable"));
Inventory inv = BreweryPlugin.getInstance().getServer().createInventory(this, InventoryType.DISPENSER, BreweryPlugin.getInstance().languageReader.get("Etc_SealingTable"));
// Inventory Holder (for DISPENSER, ...) is only passed in Paper, not in Spigot. Doing inventory.getHolder() will return null in spigot :/
if (inv.getHolder() == this) {
inventory = inv;
@ -44,7 +44,7 @@ public class BSealer implements InventoryHolder {
inventoryHolderWorking = false;
}
}
inventory = P.p.getServer().createInventory(this, 9, P.p.languageReader.get("Etc_SealingTable"));
inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 9, BreweryPlugin.getInstance().languageReader.get("Etc_SealingTable"));
}
@Override
@ -56,7 +56,7 @@ public class BSealer implements InventoryHolder {
public void clickInv() {
contents = null;
if (task == null) {
task = P.p.getServer().getScheduler().runTaskTimer(P.p, this::itemChecking, 1, 1);
task = BreweryPlugin.getScheduler().runTaskTimer(BreweryPlugin.getInstance(), this::itemChecking, 1, 1);
}
}
@ -93,7 +93,7 @@ public class BSealer implements InventoryHolder {
Brew brew = Brew.get(contents[i]);
if (brew != null && !brew.isStripped()) {
brew.seal(contents[i]);
if (playerValid && P.use1_9) {
if (playerValid && BreweryPlugin.use1_9) {
player.playSound(player.getLocation(), Sound.ITEM_BOTTLE_FILL_DRAGONBREATH, 1, 1.5f + (float) (Math.random() * 0.2));
}
}
@ -104,10 +104,10 @@ public class BSealer implements InventoryHolder {
}
public static boolean isBSealer(Block block) {
if (P.use1_14 && block.getType() == Material.SMOKER) {
if (BreweryPlugin.use1_14 && block.getType() == Material.SMOKER) {
Container smoker = (Container) block.getState();
if (smoker.getCustomName() != null) {
if (smoker.getCustomName().equals("§e" + P.p.languageReader.get("Etc_SealingTable"))) {
if (smoker.getCustomName().equals("§e" + BreweryPlugin.getInstance().languageReader.get("Etc_SealingTable"))) {
return true;
} else {
return smoker.getPersistentDataContainer().has(TAG_KEY, PersistentDataType.BYTE);
@ -121,7 +121,7 @@ public class BSealer implements InventoryHolder {
if (item.getType() == Material.SMOKER && item.hasItemMeta()) {
ItemMeta itemMeta = item.getItemMeta();
assert itemMeta != null;
if ((itemMeta.hasDisplayName() && itemMeta.getDisplayName().equals("§e" + P.p.languageReader.get("Etc_SealingTable"))) ||
if ((itemMeta.hasDisplayName() && itemMeta.getDisplayName().equals("§e" + BreweryPlugin.getInstance().languageReader.get("Etc_SealingTable"))) ||
itemMeta.getPersistentDataContainer().has(BSealer.TAG_KEY, PersistentDataType.BYTE)) {
Container smoker = (Container) block.getState();
// Rotate the Block 180° so it doesn't look like a Smoker
@ -137,26 +137,26 @@ public class BSealer implements InventoryHolder {
public static void registerRecipe() {
recipeRegistered = true;
ItemStack sealingTableItem = new ItemStack(Material.SMOKER);
ItemMeta meta = P.p.getServer().getItemFactory().getItemMeta(Material.SMOKER);
ItemMeta meta = BreweryPlugin.getInstance().getServer().getItemFactory().getItemMeta(Material.SMOKER);
if (meta == null) return;
meta.setDisplayName("§e" + P.p.languageReader.get("Etc_SealingTable"));
meta.setDisplayName("§e" + BreweryPlugin.getInstance().languageReader.get("Etc_SealingTable"));
meta.getPersistentDataContainer().set(TAG_KEY, PersistentDataType.BYTE, (byte)1);
sealingTableItem.setItemMeta(meta);
ShapedRecipe recipe = new ShapedRecipe(new NamespacedKey(P.p, "SealingTable"), sealingTableItem);
ShapedRecipe recipe = new ShapedRecipe(new NamespacedKey(BreweryPlugin.getInstance(), "SealingTable"), sealingTableItem);
recipe.shape("bb ",
"ww ",
"ww ");
recipe.setIngredient('b', Material.GLASS_BOTTLE);
recipe.setIngredient('w', new RecipeChoice.MaterialChoice(Tag.PLANKS));
P.p.getServer().addRecipe(recipe);
BreweryPlugin.getInstance().getServer().addRecipe(recipe);
}
public static void unregisterRecipe() {
recipeRegistered = false;
//P.p.getServer().removeRecipe(new NamespacedKey(P.p, "SealingTable")); 1.15 Method
Iterator<Recipe> recipeIterator = P.p.getServer().recipeIterator();
Iterator<Recipe> recipeIterator = BreweryPlugin.getInstance().getServer().recipeIterator();
while (recipeIterator.hasNext()) {
Recipe next = recipeIterator.next();
if (next instanceof ShapedRecipe && ((ShapedRecipe) next).getKey().equals(TAG_KEY)) {

View File

@ -10,11 +10,8 @@ import com.dre.brewery.lore.BrewLore;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.BoundingBox;
import com.dre.brewery.utility.LegacyUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.SoundCategory;
import org.bukkit.World;
import com.github.Anon8281.universalScheduler.UniversalRunnable;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity;
@ -24,7 +21,6 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -37,7 +33,7 @@ import java.util.Map;
*/
public class Barrel implements InventoryHolder {
public static List<Barrel> barrels = new ArrayList<>();
public static volatile List<Barrel> barrels = new ArrayList<>();
private static int check = 0; // Which Barrel was last checked
private final Block spigot;
@ -49,9 +45,9 @@ public class Barrel implements InventoryHolder {
public Barrel(Block spigot, byte signoffset) {
this.spigot = spigot;
if (isLarge()) {
inventory = P.p.getServer().createInventory(this, 27, P.p.languageReader.get("Etc_Barrel"));
inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 27, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
} else {
inventory = P.p.getServer().createInventory(this, 9, P.p.languageReader.get("Etc_Barrel"));
inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 9, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
}
body = new BarrelBody(this, signoffset);
}
@ -70,14 +66,14 @@ public class Barrel implements InventoryHolder {
public Barrel(Block spigot, byte sign, BoundingBox bounds, Map<String, Object> items, float time, boolean async) {
this.spigot = spigot;
if (isLarge()) {
this.inventory = P.p.getServer().createInventory(this, 27, P.p.languageReader.get("Etc_Barrel"));
this.inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 27, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
} else {
this.inventory = P.p.getServer().createInventory(this, 9, P.p.languageReader.get("Etc_Barrel"));
this.inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 9, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
}
if (items != null) {
for (String slot : items.keySet()) {
if (items.get(slot) instanceof ItemStack) {
this.inventory.setItem(P.p.parseInt(slot), (ItemStack) items.get(slot));
this.inventory.setItem(BreweryPlugin.getInstance().parseInt(slot), (ItemStack) items.get(slot));
}
}
}
@ -89,7 +85,9 @@ public class Barrel implements InventoryHolder {
public static void onUpdate() {
for (Barrel barrel : barrels) {
// Minecraft day is 20 min, so add 1/20 to the time every minute
barrel.time += (1.0 / 20.0);
if (barrel != null) {
barrel.time += (1.0 / 20.0);
}
}
int numBarrels = barrels.size();
if (check == 0 && numBarrels > 0) {
@ -106,19 +104,19 @@ public class Barrel implements InventoryHolder {
randomInTheBack.checked = false;
}
}
new BarrelCheck().runTaskTimer(P.p, 1, 1);
new BarrelCheck().runTaskTimer(BreweryPlugin.getInstance(), 1, 1);
}
}
public boolean hasPermsOpen(Player player, PlayerInteractEvent event) {
if (isLarge()) {
if (!player.hasPermission("brewery.openbarrel.big")) {
P.p.msg(player, P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
return false;
}
} else {
if (!player.hasPermission("brewery.openbarrel.small")) {
P.p.msg(player, P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
return false;
}
}
@ -126,7 +124,7 @@ public class Barrel implements InventoryHolder {
// Call event
BarrelAccessEvent accessEvent = new BarrelAccessEvent(this, player, event.getClickedBlock(), event.getBlockFace());
// Listened to by IntegrationListener
P.p.getServer().getPluginManager().callEvent(accessEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(accessEvent);
return !accessEvent.isCancelled();
}
@ -136,7 +134,7 @@ public class Barrel implements InventoryHolder {
public boolean hasPermsDestroy(Player player, Block block, BarrelDestroyEvent.Reason reason) {
// Listened to by LWCBarrel (IntegrationListener)
BarrelDestroyEvent destroyEvent = new BarrelDestroyEvent(this, block, reason, player);
P.p.getServer().getPluginManager().callEvent(destroyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(destroyEvent);
return !destroyEvent.isCancelled();
}
@ -146,9 +144,9 @@ public class Barrel implements InventoryHolder {
public void open(Player player) {
if (inventory == null) {
if (isLarge()) {
inventory = P.p.getServer().createInventory(this, 27, P.p.languageReader.get("Etc_Barrel"));
inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 27, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
} else {
inventory = P.p.getServer().createInventory(this, 9, P.p.languageReader.get("Etc_Barrel"));
inventory = BreweryPlugin.getInstance().getServer().createInventory(this, 9, BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"));
}
} else {
if (time > 0) {
@ -168,7 +166,7 @@ public class Barrel implements InventoryHolder {
}
loadTime = System.nanoTime() - loadTime;
float ftime = (float) (loadTime / 1000000.0);
P.p.debugLog("opening Barrel with potions (" + ftime + "ms)");
BreweryPlugin.getInstance().debugLog("opening Barrel with potions (" + ftime + "ms)");
}
}
}
@ -180,8 +178,8 @@ public class Barrel implements InventoryHolder {
try {
LogBlockBarrel.openBarrel(player, inventory, spigot.getLocation());
} catch (Throwable e) {
P.p.errorLog("Failed to Log Barrel to LogBlock!");
P.p.errorLog("Brewery was tested with version 1.94 of LogBlock!");
BreweryPlugin.getInstance().errorLog("Failed to Log Barrel to LogBlock!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 1.94 of LogBlock!");
e.printStackTrace();
}
}
@ -287,7 +285,7 @@ public class Barrel implements InventoryHolder {
int i = 0;
for (Barrel barrel : barrels) {
if (barrel.body.isSignOfBarrel(signoffset)) {
if (barrel != null && barrel.body.isSignOfBarrel(signoffset)) {
if (barrel.spigot.equals(spigot)) {
if (barrel.body.getSignoffset() == 0 && signoffset != 0) {
// Barrel has no signOffset even though we clicked a sign, may be old
@ -346,17 +344,17 @@ public class Barrel implements InventoryHolder {
if (barrel.body.getBrokenBlock(true) == null) {
if (LegacyUtil.isSign(spigot.getType())) {
if (!player.hasPermission("brewery.createbarrel.small")) {
P.p.msg(player, P.p.languageReader.get("Perms_NoSmallBarrelCreate"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Perms_NoSmallBarrelCreate"));
return false;
}
} else {
if (!player.hasPermission("brewery.createbarrel.big")) {
P.p.msg(player, P.p.languageReader.get("Perms_NoBigBarrelCreate"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Perms_NoBigBarrelCreate"));
return false;
}
}
BarrelCreateEvent createEvent = new BarrelCreateEvent(barrel, player);
P.p.getServer().getPluginManager().callEvent(createEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(createEvent);
if (!createEvent.isCancelled()) {
barrels.add(0, barrel);
return true;
@ -381,7 +379,7 @@ public class Barrel implements InventoryHolder {
public void remove(@Nullable Block broken, @Nullable Player breaker, boolean dropItems) {
BarrelRemoveEvent event = new BarrelRemoveEvent(this, dropItems);
// Listened to by LWCBarrel (IntegrationListener)
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
if (inventory != null) {
List<HumanEntity> viewers = new ArrayList<>(inventory.getViewers());
@ -395,8 +393,8 @@ public class Barrel implements InventoryHolder {
try {
LogBlockBarrel.breakBarrel(breaker, items, spigot.getLocation());
} catch (Throwable e) {
P.p.errorLog("Failed to Log Barrel-break to LogBlock!");
P.p.errorLog("Brewery was tested with version 1.94 of LogBlock!");
BreweryPlugin.getInstance().errorLog("Failed to Log Barrel-break to LogBlock!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 1.94 of LogBlock!");
e.printStackTrace();
}
}
@ -486,7 +484,7 @@ public class Barrel implements InventoryHolder {
* Unload all Barrels that have a Block in a unloaded World
*/
public static void unloadWorlds() {
List<World> worlds = P.p.getServer().getWorlds();
List<World> worlds = BreweryPlugin.getInstance().getServer().getWorlds();
barrels.removeIf(barrel -> !worlds.contains(barrel.spigot.getWorld()));
}
@ -550,7 +548,7 @@ public class Barrel implements InventoryHolder {
}
}
public static class BarrelCheck extends BukkitRunnable {
public static class BarrelCheck extends UniversalRunnable {
@Override
public void run() {
boolean repeat = true;
@ -558,19 +556,21 @@ public class Barrel implements InventoryHolder {
if (check < barrels.size()) {
Barrel barrel = barrels.get(check);
if (!barrel.checked) {
Block broken = barrel.body.getBrokenBlock(false);
if (broken != null) {
P.p.debugLog("Barrel at "
+ broken.getWorld().getName() + "/" + broken.getX() + "/" + broken.getY() + "/" + broken.getZ()
+ " has been destroyed unexpectedly, contents will drop");
// remove the barrel if it was destroyed
barrel.remove(broken, null, true);
} else {
// Dont check this barrel again, its enough to check it once after every restart (and when randomly chosen)
// as now this is only the backup if we dont register the barrel breaking,
// for example when removing it with some world editor
barrel.checked = true;
}
BreweryPlugin.getScheduler().runTaskTimer(barrel.getSpigot().getLocation(), () -> {
Block broken = barrel.body.getBrokenBlock(false);
if (broken != null) {
BreweryPlugin.getInstance().debugLog("Barrel at "
+ broken.getWorld().getName() + "/" + broken.getX() + "/" + broken.getY() + "/" + broken.getZ()
+ " has been destroyed unexpectedly, contents will drop");
// remove the barrel if it was destroyed
barrel.remove(broken, null, true);
} else {
// Dont check this barrel again, its enough to check it once after every restart (and when randomly chosen)
// as now this is only the backup if we dont register the barrel breaking,
// for example when removing it with some world editor
barrel.checked = true;
}
}, 1, 1);
repeat = false;
}
check++;

View File

@ -233,7 +233,7 @@ public class BarrelBody {
* @return true if successful, false if Barrel was broken and should be removed.
*/
public boolean regenerateBounds() {
P.p.log("Regenerating Barrel BoundingBox: " + (bounds == null ? "was null" : "area=" + bounds.area()));
BreweryPlugin.getInstance().log("Regenerating Barrel BoundingBox: " + (bounds == null ? "was null" : "area=" + bounds.area()));
Block broken = getBrokenBlock(true);
if (broken != null) {
barrel.remove(broken, null, true);

View File

@ -101,7 +101,7 @@ public class Brew implements Cloneable {
*/
@Nullable
public static Brew get(ItemMeta meta) {
if (!P.useNBT && !meta.hasLore()) return null;
if (!BreweryPlugin.useNBT && !meta.hasLore()) return null;
Brew brew = load(meta);
@ -125,7 +125,7 @@ public class Brew implements Cloneable {
ItemMeta meta = item.getItemMeta();
assert meta != null;
if (!P.useNBT && !meta.hasLore()) return null;
if (!BreweryPlugin.useNBT && !meta.hasLore()) return null;
Brew brew = load(meta);
@ -138,9 +138,9 @@ public class Brew implements Cloneable {
item.setItemMeta(meta);
} else if (brew != null && brew.needsSave) {
// Brew needs saving from a previous format
if (P.useNBT) {
if (BreweryPlugin.useNBT) {
new BrewLore(brew, (PotionMeta) meta).removeLoreData();
P.p.debugLog("removed Data from Lore");
BreweryPlugin.getInstance().debugLog("removed Data from Lore");
}
brew.save(meta);
item.setItemMeta(meta);
@ -182,7 +182,7 @@ public class Brew implements Cloneable {
public static Brew get(int uid) {
if (uid < -1) {
if (!legacyPotions.containsKey(uid)) {
P.p.errorLog("Database failure! unable to find UID " + uid + " of a custom Potion!");
BreweryPlugin.getInstance().errorLog("Database failure! unable to find UID " + uid + " of a custom Potion!");
return null;// throw some exception?
}
} else {
@ -251,10 +251,10 @@ public class Brew implements Cloneable {
/*if (!immutable) {
this.quality = calcQuality();
}*/
P.p.log("A Brew was made from Recipe: '" + name + "' which could not be found. '" + currentRecipe.getRecipeName() + "' used instead!");
BreweryPlugin.getInstance().log("A Brew was made from Recipe: '" + name + "' which could not be found. '" + currentRecipe.getRecipeName() + "' used instead!");
return true;
} else {
P.p.errorLog("A Brew was made from Recipe: '" + name + "' which could not be found!");
BreweryPlugin.getInstance().errorLog("A Brew was made from Recipe: '" + name + "' which could not be found!");
}
}
}
@ -408,7 +408,7 @@ public class Brew implements Cloneable {
}
public void updateCustomModelData(ItemMeta meta) {
if (!P.use1_14) return;
if (!BreweryPlugin.use1_14) return;
if (currentRecipe != null && currentRecipe.getCmData() != null) {
int cm;
if (quality > 7) {
@ -494,7 +494,7 @@ public class Brew implements Cloneable {
touch();
BrewModifyEvent modifyEvent = new BrewModifyEvent(this, meta, BrewModifyEvent.Type.SEAL);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
// As the brew and everything connected to it is only saved on the meta from now on,
// restoring the origMeta is enough in this case
@ -583,7 +583,7 @@ public class Brew implements Cloneable {
if (!immutable && isStripped()) {
throw new IllegalStateException("Cannot make stripped Brews non-static");
}
if (!P.use1_9 && currentRecipe != null && canDistill()) {
if (!BreweryPlugin.use1_9 && currentRecipe != null && canDistill()) {
if (immutable) {
currentRecipe.getColor().colorBrew(((PotionMeta) potion.getItemMeta()), potion, false);
} else {
@ -633,13 +633,13 @@ public class Brew implements Cloneable {
quality = calcQuality();
lore.addOrReplaceEffects(getEffects(), quality);
potionMeta.setDisplayName(P.p.color("&f" + recipe.getName(quality)));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + recipe.getName(quality)));
recipe.getColor().colorBrew(potionMeta, slotItem, canDistill());
} else {
quality = 0;
lore.removeEffects();
potionMeta.setDisplayName(P.p.color("&f" + P.p.languageReader.get("Brew_DistillUndefined")));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + BreweryPlugin.getInstance().languageReader.get("Brew_DistillUndefined")));
PotionColor.GREY.colorBrew(potionMeta, slotItem, canDistill());
}
alc = calcAlcohol();
@ -657,7 +657,7 @@ public class Brew implements Cloneable {
lore.write();
touch();
BrewModifyEvent modifyEvent = new BrewModifyEvent(this, potionMeta, BrewModifyEvent.Type.DISTILL);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
// As the brew and everything connected to it is only saved on the meta from now on,
// not saving the brew into potionMeta is enough to not change anything in case of cancel
@ -706,14 +706,14 @@ public class Brew implements Cloneable {
quality = calcQuality();
lore.addOrReplaceEffects(getEffects(), quality);
potionMeta.setDisplayName(P.p.color("&f" + recipe.getName(quality)));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + recipe.getName(quality)));
recipe.getColor().colorBrew(potionMeta, item, canDistill());
} else {
quality = 0;
lore.convertLore(false);
lore.removeEffects();
currentRecipe = null;
potionMeta.setDisplayName(P.p.color("&f" + P.p.languageReader.get("Brew_BadPotion")));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + BreweryPlugin.getInstance().languageReader.get("Brew_BadPotion")));
PotionColor.GREY.colorBrew(potionMeta, item, canDistill());
}
}
@ -739,7 +739,7 @@ public class Brew implements Cloneable {
lore.write();
touch();
BrewModifyEvent modifyEvent = new BrewModifyEvent(this, potionMeta, BrewModifyEvent.Type.AGE);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
// As the brew and everything connected to it is only saved on the meta from now on,
// not saving the brew into potionMeta is enough to not change anything in case of cancel
@ -804,7 +804,7 @@ public class Brew implements Cloneable {
recipe.getColor().colorBrew(potionMeta, potion, false);
updateCustomModelData(potionMeta);
potionMeta.setDisplayName(P.p.color("&f" + recipe.getName(quality)));
potionMeta.setDisplayName(BreweryPlugin.getInstance().color("&f" + recipe.getName(quality)));
//if (!P.use1_14) {
// Before 1.14 the effects duration would strangely be only a quarter of what we tell it to be
// This is due to the Duration Modifier, that is removed in 1.14
@ -820,14 +820,14 @@ public class Brew implements Cloneable {
touch();
if (event) {
BrewModifyEvent modifyEvent = new BrewModifyEvent(this, potionMeta, BrewModifyEvent.Type.CREATE);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
return null;
}
}
save(potionMeta);
potion.setItemMeta(potionMeta);
P.p.stats.metricsForCreate(true);
BreweryPlugin.getInstance().stats.metricsForCreate(true);
return potion;
}
@ -844,9 +844,9 @@ public class Brew implements Cloneable {
ItemMeta meta = item.getItemMeta();
assert meta != null;
if (!P.useNBT && !meta.hasLore()) return false;
if (!BreweryPlugin.useNBT && !meta.hasLore()) return false;
if (P.useNBT) {
if (BreweryPlugin.useNBT) {
// Check for Data on PersistentDataContainer
if (NBTLoadStream.hasDataInMeta(meta)) {
return true;
@ -862,7 +862,7 @@ public class Brew implements Cloneable {
private static Brew load(ItemMeta meta) {
InputStream itemLoadStream = null;
if (P.useNBT) {
if (BreweryPlugin.useNBT) {
// Try loading the Item Data from PersistentDataContainer
NBTLoadStream nbtStream = new NBTLoadStream(meta);
if (nbtStream.hasData()) {
@ -883,7 +883,7 @@ public class Brew implements Cloneable {
try (DataInputStream in = new DataInputStream(unscrambler)) {
boolean parityFailed = false;
if (in.readByte() != 86) {
P.p.errorLog("Parity check failed on Brew while loading, trying to load anyways!");
BreweryPlugin.getInstance().errorLog("Parity check failed on Brew while loading, trying to load anyways!");
parityFailed = true;
}
Brew brew = new Brew();
@ -897,33 +897,33 @@ public class Brew implements Cloneable {
break;
default:
if (parityFailed) {
P.p.errorLog("Failed to load Brew. Maybe something corrupted the Lore of the Item?");
BreweryPlugin.getInstance().errorLog("Failed to load Brew. Maybe something corrupted the Lore of the Item?");
} else {
P.p.errorLog("Brew has data stored in v" + ver + " this Plugin version supports up to v" + SAVE_VER);
BreweryPlugin.getInstance().errorLog("Brew has data stored in v" + ver + " this Plugin version supports up to v" + SAVE_VER);
}
return null;
}
XORUnscrambleStream.SuccessType successType = unscrambler.getSuccessType();
if (successType == XORUnscrambleStream.SuccessType.PREV_SEED) {
P.p.debugLog("Converting Brew from previous Seed");
BreweryPlugin.getInstance().debugLog("Converting Brew from previous Seed");
brew.setNeedsSave(true);
} else if ((BConfig.enableEncode && !brew.isStripped()) != (successType == XORUnscrambleStream.SuccessType.MAIN_SEED)) {
// We have either enabled encode and the data was not encoded or the other way round
P.p.debugLog("Converting Brew to new encode setting");
BreweryPlugin.getInstance().debugLog("Converting Brew to new encode setting");
brew.setNeedsSave(true);
} else if (P.useNBT && itemLoadStream instanceof Base91DecoderStream) {
} else if (BreweryPlugin.useNBT && itemLoadStream instanceof Base91DecoderStream) {
// We are on a version that supports nbt but the data is still in the lore of the item
// Just save it again so that it gets saved to nbt
P.p.debugLog("Converting Brew to NBT");
BreweryPlugin.getInstance().debugLog("Converting Brew to NBT");
brew.setNeedsSave(true);
}
return brew;
} catch (IOException e) {
P.p.errorLog("IO Error while loading Brew");
BreweryPlugin.getInstance().errorLog("IO Error while loading Brew");
e.printStackTrace();
} catch (InvalidKeyException e) {
P.p.errorLog("Failed to load Brew, has the data key 'encodeKey' in the config.yml been changed?");
BreweryPlugin.getInstance().errorLog("Failed to load Brew, has the data key 'encodeKey' in the config.yml been changed?");
e.printStackTrace();
}
return null;
@ -961,7 +961,7 @@ public class Brew implements Cloneable {
*/
public void save(ItemMeta meta) {
OutputStream itemSaveStream;
if (P.useNBT) {
if (BreweryPlugin.useNBT) {
itemSaveStream = new NBTSaveStream(meta);
} else {
itemSaveStream = new Base91EncoderStream(new LoreSaveStream(meta, 0));
@ -978,7 +978,7 @@ public class Brew implements Cloneable {
}
saveToStream(out);
} catch (IOException e) {
P.p.errorLog("IO Error while saving Brew");
BreweryPlugin.getInstance().errorLog("IO Error while saving Brew");
e.printStackTrace();
}
}
@ -992,7 +992,7 @@ public class Brew implements Cloneable {
public void save(ItemStack item) {
ItemMeta meta;
if (!item.hasItemMeta()) {
meta = P.p.getServer().getItemFactory().getItemMeta(item.getType());
meta = BreweryPlugin.getInstance().getServer().getItemFactory().getItemMeta(item.getType());
} else {
meta = item.getItemMeta();
}

View File

@ -24,11 +24,10 @@
package com.dre.brewery;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.filedata.BData;
import com.dre.brewery.filedata.DataSave;
import com.dre.brewery.filedata.LanguageReader;
import com.dre.brewery.filedata.UpdateChecker;
import com.dre.brewery.api.addons.AddonManager;
import com.dre.brewery.commands.CommandManager;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.filedata.*;
import com.dre.brewery.integration.ChestShopListener;
import com.dre.brewery.integration.IntegrationListener;
import com.dre.brewery.integration.ShopKeepersListener;
@ -40,11 +39,11 @@ import com.dre.brewery.recipe.*;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.LegacyUtil;
import com.dre.brewery.utility.Stats;
import com.github.Anon8281.universalScheduler.UniversalScheduler;
import com.github.Anon8281.universalScheduler.scheduling.schedulers.TaskScheduler;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
@ -55,8 +54,11 @@ import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
public class P extends JavaPlugin {
public static P p;
public class BreweryPlugin extends JavaPlugin {
private static AddonManager addonManager;
private static TaskScheduler scheduler;
private static BreweryPlugin breweryPlugin;
public static boolean debug;
public static boolean useUUID;
public static boolean useNBT;
@ -65,13 +67,8 @@ public class P extends JavaPlugin {
public static boolean use1_13;
public static boolean use1_14;
// Listeners
public BlockListener blockListener;
// Public Listeners
public PlayerListener playerListener;
public EntityListener entityListener;
public InventoryListener inventoryListener;
public WorldListener worldListener;
public IntegrationListener integrationListener;
// Registrations
public Map<String, Function<ItemLoader, Ingredient>> ingredientLoaders = new HashMap<>();
@ -85,7 +82,8 @@ public class P extends JavaPlugin {
@Override
public void onEnable() {
p = this;
breweryPlugin = this;
scheduler = UniversalScheduler.getScheduler(this);
// Version check
String v = Bukkit.getBukkitVersion();
@ -95,7 +93,12 @@ public class P extends JavaPlugin {
use1_13 = !v.matches("(^|.*[^.\\d])1\\.1[0-2]([^\\d].*|$)") && !v.matches("(^|.*[^.\\d])1\\.[0-9]([^\\d].*|$)");
use1_14 = !v.matches("(^|.*[^.\\d])1\\.1[0-3]([^\\d].*|$)") && !v.matches("(^|.*[^.\\d])1\\.[0-9]([^\\d].*|$)");
//MC 1.13 uses a different NBT API than the newer versions..
// Load Addons
addonManager = new AddonManager(this);
addonManager.loadAddons();
//MC 1.13 uses a different NBT API than the newer versions.
// We decide here which to use, the new or the old or none at all
if (LegacyUtil.initNbt()) {
useNBT = true;
@ -111,15 +114,13 @@ public class P extends JavaPlugin {
try {
FileConfiguration cfg = BConfig.loadConfigFile();
if (cfg == null) {
p = null;
getServer().getPluginManager().disablePlugin(this);
log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
BConfig.readConfig(cfg);
} catch (Exception e) {
e.printStackTrace();
p = null;
getServer().getPluginManager().disablePlugin(this);
log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
@ -134,68 +135,67 @@ public class P extends JavaPlugin {
// Setup Metrics
stats.setupBStats();
// Listeners
blockListener = new BlockListener();
playerListener = new PlayerListener();
entityListener = new EntityListener();
inventoryListener = new InventoryListener();
worldListener = new WorldListener();
integrationListener = new IntegrationListener();
PluginCommand c = getCommand("Brewery");
if (c != null) {
c.setExecutor(new CommandListener());
c.setTabCompleter(new TabListener());
}
p.getServer().getPluginManager().registerEvents(blockListener, p);
p.getServer().getPluginManager().registerEvents(playerListener, p);
p.getServer().getPluginManager().registerEvents(entityListener, p);
p.getServer().getPluginManager().registerEvents(inventoryListener, p);
p.getServer().getPluginManager().registerEvents(worldListener, p);
p.getServer().getPluginManager().registerEvents(integrationListener, p);
getCommand("brewery").setExecutor(new CommandManager());
// Listeners
playerListener = new PlayerListener();
getServer().getPluginManager().registerEvents(new BlockListener(), this);
getServer().getPluginManager().registerEvents(playerListener, this);
getServer().getPluginManager().registerEvents(new EntityListener(), this);
getServer().getPluginManager().registerEvents(new InventoryListener(), this);
getServer().getPluginManager().registerEvents(new WorldListener(), this);
getServer().getPluginManager().registerEvents(new IntegrationListener(), this);
if (use1_9) {
p.getServer().getPluginManager().registerEvents(new CauldronListener(), p);
getServer().getPluginManager().registerEvents(new CauldronListener(), this);
}
if (BConfig.hasChestShop && use1_13) {
p.getServer().getPluginManager().registerEvents(new ChestShopListener(), p);
getServer().getPluginManager().registerEvents(new ChestShopListener(), this);
}
if (BConfig.hasShopKeepers) {
p.getServer().getPluginManager().registerEvents(new ShopKeepersListener(), p);
getServer().getPluginManager().registerEvents(new ShopKeepersListener(), this);
}
if (BConfig.hasSlimefun && use1_14) {
p.getServer().getPluginManager().registerEvents(new SlimefunListener(), p);
getServer().getPluginManager().registerEvents(new SlimefunListener(), this);
}
// Heartbeat
p.getServer().getScheduler().runTaskTimer(p, new BreweryRunnable(), 650, 1200);
p.getServer().getScheduler().runTaskTimer(p, new DrunkRunnable(), 120, 120);
BreweryPlugin.getScheduler().runTaskTimer(new BreweryRunnable(), 650, 1200);
BreweryPlugin.getScheduler().runTaskTimer(new DrunkRunnable(), 120, 120);
if (use1_9) {
p.getServer().getScheduler().runTaskTimer(p, new CauldronParticles(), 1, 1);
BreweryPlugin.getScheduler().runTaskTimer(new CauldronParticles(), 1, 1);
}
// Disable Update Check for older mc versions
if (use1_14 && BConfig.updateCheck) {
try {
p.getServer().getScheduler().runTaskLaterAsynchronously(p, new UpdateChecker(), 135);
} catch (Exception e) {
e.printStackTrace();
}
new UpdateChecker(114777).query(latestVersion -> {
int pluginVersion = parseInt(getDescription().getVersion().replace(".","").strip());
int latest = parseInt(latestVersion.replace(".", "").strip());
if (latest > pluginVersion) {
UpdateChecker.setUpdateAvailable(true);
UpdateChecker.setLatestVersion(latestVersion);
msg(Bukkit.getConsoleSender(), languageReader.get("Etc_UpdateAvailable", "v" + getDescription().getVersion(), "v" + latestVersion));
}
});
}
this.debugLog("Using scheduler: " + scheduler.getClass().getSimpleName());
this.log(this.getDescription().getName() + " enabled!");
}
@Override
public void onDisable() {
addonManager.unloadAddons();
// Disable listeners
HandlerList.unregisterAll(this);
// Stop shedulers
getServer().getScheduler().cancelTasks(this);
// Stop schedulers
BreweryPlugin.getScheduler().cancelTasks(this);
if (p == null) {
if (breweryPlugin == null) {
return;
}
@ -223,6 +223,7 @@ public class P extends JavaPlugin {
FileConfiguration cfg = BConfig.loadConfigFile();
if (cfg == null) {
// Could not read yml file, do not proceed, error was printed
log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
@ -234,8 +235,7 @@ public class P extends JavaPlugin {
BConfig.readConfig(cfg);
} catch (Exception e) {
e.printStackTrace();
p = null;
getServer().getPluginManager().disablePlugin(this);
log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
@ -243,7 +243,7 @@ public class P extends JavaPlugin {
BCauldron.reload();
// Clear Recipe completions
TabListener.reload();
CommandUtil.reloadTabCompleter();
// Reload Recipes
boolean successful = true;
@ -254,15 +254,15 @@ public class P extends JavaPlugin {
}
if (sender != null) {
if (!successful) {
msg(sender, p.languageReader.get("Error_Recipeload"));
msg(sender, breweryPlugin.languageReader.get("Error_Recipeload"));
} else {
p.msg(sender, p.languageReader.get("CMD_Reload"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Reload"));
}
}
BConfig.reloader = null;
}
private void clearConfigData() {
public void clearConfigData() {
BRecipe.getConfigRecipes().clear();
BRecipe.numConfigRecipes = 0;
BCauldronRecipe.acceptedMaterials.clear();
@ -305,14 +305,14 @@ public class P extends JavaPlugin {
ingredientLoaders.remove(saveID);
}
public static P getInstance() {
return p;
public static BreweryPlugin getInstance() {
return breweryPlugin;
}
// Utility
public void msg(CommandSender sender, String msg) {
sender.sendMessage(color("&2[Brewery] &f" + msg));
sender.sendMessage(color(BConfig.pluginPrefix + msg));
}
public void log(String msg) {
@ -326,9 +326,9 @@ public class P extends JavaPlugin {
}
public void errorLog(String msg) {
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.DARK_RED + "ERROR: " + ChatColor.RED + msg);
Bukkit.getConsoleSender().sendMessage(color(BConfig.pluginPrefix + "&cERROR: " + msg));
if (BConfig.reloader != null) {
BConfig.reloader.sendMessage(ChatColor.DARK_GREEN + "[Brewery] " + ChatColor.DARK_RED + "ERROR: " + ChatColor.RED + msg);
BConfig.reloader.sendMessage(color(BConfig.pluginPrefix + "&cERROR: " + msg));
}
}
@ -370,6 +370,10 @@ public class P extends JavaPlugin {
return BUtil.color(msg);
}
public static TaskScheduler getScheduler() {
return scheduler;
}
// Runnables
@ -387,12 +391,16 @@ public class P extends JavaPlugin {
public void run() {
long t1 = System.nanoTime();
BConfig.reloader = null;
Iterator<BCauldron> iter = BCauldron.bcauldrons.values().iterator();
while (iter.hasNext()) {
// runs every min to update cooking time
Iterator<BCauldron> bCauldronsToRemove = BCauldron.bcauldrons.values().iterator();
while (bCauldronsToRemove.hasNext()) {
// runs every min to update cooking time
if (!iter.next().onUpdate()) {
iter.remove();
}
BCauldron bCauldron = bCauldronsToRemove.next();
BreweryPlugin.getScheduler().runTask(bCauldron.getBlock().getLocation(), () -> {
if (!bCauldron.onUpdate()) {
bCauldronsToRemove.remove();
}
});
}
long t2 = System.nanoTime();
Barrel.onUpdate();// runs every min to check and update ageing time

View File

@ -19,7 +19,7 @@ public class DistortChat {
public static List<String[]> ignoreText = new ArrayList<>();
public static Boolean doSigns;
public static Boolean log;
private static Map<String, Long> waitPlayers = new HashMap<>();
private static final Map<String, Long> waitPlayers = new HashMap<>();
private String from;
private String to;
@ -77,12 +77,12 @@ public class DistortChat {
if (Character.isSpaceChar(chat.charAt(command.length()))) {
if (chat.toLowerCase().startsWith(command.toLowerCase())) {
if (log) {
P.p.log(P.p.languageReader.get("Player_TriedToSay", name, chat));
BreweryPlugin.getInstance().log(BreweryPlugin.getInstance().languageReader.get("Player_TriedToSay", name, chat));
}
String message = chat.substring(command.length() + 1);
String distorted = distortMessage(message, bPlayer.getDrunkeness());
PlayerChatDistortEvent call = new PlayerChatDistortEvent(event.isAsynchronous(), event.getPlayer(), bPlayer, message, distorted);
P.p.getServer().getPluginManager().callEvent(call);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(call);
if (call.isCancelled()) {
return;
}
@ -110,7 +110,7 @@ public class DistortChat {
if (message.length() > 1) {
String distorted = distortMessage(message, bPlayer.getDrunkeness());
PlayerChatDistortEvent call = new PlayerChatDistortEvent(event.isAsynchronous(), event.getPlayer(), bPlayer, message, distorted);
P.p.getServer().getPluginManager().callEvent(call);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(call);
if (!call.isCancelled()) {
distorted = call.getDistortedMessage();
@ -133,12 +133,12 @@ public class DistortChat {
if (!words.isEmpty()) {
String message = event.getMessage();
if (log) {
P.p.log(P.p.languageReader.get("Player_TriedToSay", event.getPlayer().getName(), message));
BreweryPlugin.getInstance().log(BreweryPlugin.getInstance().languageReader.get("Player_TriedToSay", event.getPlayer().getName(), message));
}
String distorted = distortMessage(message, bPlayer.getDrunkeness());
PlayerChatDistortEvent call = new PlayerChatDistortEvent(event.isAsynchronous(), event.getPlayer(), bPlayer, message, distorted);
P.p.getServer().getPluginManager().callEvent(call);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(call);
if (call.isCancelled()) {
return;
}

View File

@ -41,14 +41,14 @@ public class MCBarrel {
if (inv.getViewers().size() == 1 && inv.getHolder() instanceof org.bukkit.block.Barrel) {
Barrel barrel = (Barrel) inv.getHolder();
PersistentDataContainer data = barrel.getPersistentDataContainer();
NamespacedKey key = new NamespacedKey(P.p, TAG);
NamespacedKey key = new NamespacedKey(BreweryPlugin.getInstance(), TAG);
if (!data.has(key, PersistentDataType.LONG)) return;
// Get the difference between the time that is stored on the Barrel and the current stored global mcBarrelTime
long time = mcBarrelTime - data.getOrDefault(key, PersistentDataType.LONG, mcBarrelTime);
data.remove(key);
barrel.update();
P.p.debugLog("Barrel Time since last open: " + time);
BreweryPlugin.getInstance().debugLog("Barrel Time since last open: " + time);
if (time > 0) {
brews = 0;
@ -67,10 +67,10 @@ public class MCBarrel {
}
}
}
if (P.debug) {
if (BreweryPlugin.debug) {
loadTime = System.nanoTime() - loadTime;
float ftime = (float) (loadTime / 1000000.0);
P.p.debugLog("opening MC Barrel with potions (" + ftime + "ms)");
BreweryPlugin.getInstance().debugLog("opening MC Barrel with potions (" + ftime + "ms)");
}
}
}
@ -88,7 +88,7 @@ public class MCBarrel {
if (inv.getHolder() instanceof org.bukkit.block.Barrel) {
Barrel barrel = (Barrel) inv.getHolder();
PersistentDataContainer data = barrel.getPersistentDataContainer();
data.set(new NamespacedKey(P.p, TAG), PersistentDataType.LONG, mcBarrelTime);
data.set(new NamespacedKey(BreweryPlugin.getInstance(), TAG), PersistentDataType.LONG, mcBarrelTime);
barrel.update();
}
return;
@ -196,7 +196,7 @@ public class MCBarrel {
}
if (brews >= maxBrews) {
event.setCancelled(true);
P.p.msg(event.getWhoClicked(), P.p.languageReader.get("Player_BarrelFull"));
BreweryPlugin.getInstance().msg(event.getWhoClicked(), BreweryPlugin.getInstance().languageReader.get("Player_BarrelFull"));
} else {
brews++;
}

View File

@ -15,7 +15,7 @@ import java.util.stream.Collectors;
public class Wakeup {
public static List<Wakeup> wakeups = new ArrayList<>();
public static P p = P.p;
public static BreweryPlugin breweryPlugin = BreweryPlugin.getInstance();
public static int checkId = -1;
public static Player checkPlayer = null;
@ -46,7 +46,7 @@ public class Wakeup {
if (w1 == null) return null;
while (!w1.check()) {
p.errorLog("Please Check Wakeup-Location with id: &6" + wakeups.indexOf(w1));
breweryPlugin.errorLog("Please Check Wakeup-Location with id: &6" + wakeups.indexOf(w1));
w1 = calcRandom(worldWakes);
if (w1 == null) {
@ -60,7 +60,7 @@ public class Wakeup {
worldWakes.remove(w2);
while (!w2.check()) {
p.errorLog("Please Check Wakeup-Location with id: &6" + wakeups.indexOf(w2));
breweryPlugin.errorLog("Please Check Wakeup-Location with id: &6" + wakeups.indexOf(w2));
w2 = calcRandom(worldWakes);
if (w2 == null) {
@ -89,16 +89,16 @@ public class Wakeup {
Player player = (Player) sender;
wakeups.add(new Wakeup(player.getLocation()));
p.msg(sender, p.languageReader.get("Player_WakeCreated", "" + (wakeups.size() - 1)));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeCreated", "" + (wakeups.size() - 1)));
} else {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_PlayerCommand"));
}
}
public static void remove(CommandSender sender, int id) {
if (wakeups.isEmpty() || id < 0 || id >= wakeups.size()) {
p.msg(sender, p.languageReader.get("Player_WakeNotExist", "" + id));//"&cDer Aufwachpunkt mit der id: &6" + id + " &cexistiert nicht!");
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeNotExist", "" + id));//"&cDer Aufwachpunkt mit der id: &6" + id + " &cexistiert nicht!");
return;
}
@ -106,16 +106,16 @@ public class Wakeup {
if (wakeup.active) {
wakeup.active = false;
p.msg(sender, p.languageReader.get("Player_WakeDeleted", "" + id));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeDeleted", "" + id));
} else {
p.msg(sender, p.languageReader.get("Player_WakeAlreadyDeleted", "" + id));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeAlreadyDeleted", "" + id));
}
}
public static void list(CommandSender sender, int page, String worldOnly) {
if (wakeups.isEmpty()) {
p.msg(sender, p.languageReader.get("Player_WakeNoPoints"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeNoPoints"));
return;
}
@ -148,7 +148,7 @@ public class Wakeup {
if (!all) {
if (wakeups.isEmpty() || id >= wakeups.size()) {
p.msg(sender, p.languageReader.get("Player_WakeNotExist", "" + id));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeNotExist", "" + id));
return;
}
@ -160,12 +160,12 @@ public class Wakeup {
int x = (int) wakeup.loc.getX();
int y = (int) wakeup.loc.getY();
int z = (int) wakeup.loc.getZ();
p.msg(sender, p.languageReader.get("Player_WakeFilled", "" + id, world, "" + x , "" + y, "" + z));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeFilled", "" + id, world, "" + x , "" + y, "" + z));
}
} else {
if (wakeups.isEmpty()) {
p.msg(sender, p.languageReader.get("Player_WakeNoPoints"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeNoPoints"));
return;
}
if (checkPlayer != null && checkPlayer != player) {
@ -177,7 +177,7 @@ public class Wakeup {
} else {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_PlayerCommand"));
}
}
@ -188,7 +188,7 @@ public class Wakeup {
public static void tpNext() {
checkId++;
if (checkId >= wakeups.size()) {
p.msg(checkPlayer, p.languageReader.get("Player_WakeLast"));
breweryPlugin.msg(checkPlayer, breweryPlugin.languageReader.get("Player_WakeLast"));
checkId = -1;
checkPlayer = null;
return;
@ -206,23 +206,23 @@ public class Wakeup {
int z = (int) wakeup.loc.getZ();
if (wakeup.check()) {
p.msg(checkPlayer, p.languageReader.get("Player_WakeTeleport", "" + checkId, world, "" + x , "" + y, "" + z));
breweryPlugin.msg(checkPlayer, breweryPlugin.languageReader.get("Player_WakeTeleport", "" + checkId, world, "" + x , "" + y, "" + z));
checkPlayer.teleport(wakeup.loc);
} else {
p.msg(checkPlayer, p.languageReader.get("Player_WakeFilled", "" + checkId, world, "" + x , "" + y, "" + z));
breweryPlugin.msg(checkPlayer, breweryPlugin.languageReader.get("Player_WakeFilled", "" + checkId, world, "" + x , "" + y, "" + z));
}
p.msg(checkPlayer, p.languageReader.get("Player_WakeHint1"));
p.msg(checkPlayer, p.languageReader.get("Player_WakeHint2"));
breweryPlugin.msg(checkPlayer, breweryPlugin.languageReader.get("Player_WakeHint1"));
breweryPlugin.msg(checkPlayer, breweryPlugin.languageReader.get("Player_WakeHint2"));
}
public static void cancel(CommandSender sender) {
if (checkPlayer != null) {
checkPlayer = null;
checkId = -1;
p.msg(sender, p.languageReader.get("Player_WakeCancel"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeCancel"));
return;
}
p.msg(sender, p.languageReader.get("Player_WakeNoCheck"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Player_WakeNoCheck"));
}
@ -268,7 +268,7 @@ public class Wakeup {
}
public static void unloadWorlds() {
List<World> worlds = P.p.getServer().getWorlds();
List<World> worlds = BreweryPlugin.getInstance().getServer().getWorlds();
wakeups.removeIf(wakeup -> !worlds.contains(wakeup.loc.getWorld()));
}

View File

@ -0,0 +1,12 @@
package com.dre.brewery.api.addons;
import org.bukkit.command.defaults.BukkitCommand;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public abstract class AddonCommand extends BukkitCommand {
public AddonCommand(@NotNull String name, @NotNull String description, @NotNull String usageMessage, @NotNull List<String> aliases) {
super(name, description, usageMessage, aliases);
}
}

View File

@ -0,0 +1,110 @@
package com.dre.brewery.api.addons;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class AddonFileManager {
private final static BreweryPlugin plugin = BreweryPlugin.getInstance();
private final BreweryAddon addon;
private final String addonName;
private final File addonFolder;
private final AddonLogger logger;
private final File configFile;
private YamlConfiguration addonConfig;
private final File jarFile;
public AddonFileManager(BreweryAddon addon, File jarFile) {
this.addon = addon;
this.jarFile = jarFile;
this.addonName = addon.getClass().getSimpleName();
this.addonFolder = new File(plugin.getDataFolder().getAbsolutePath() + File.separator + "addons" + File.separator + addonName);
this.logger = addon.getLogger();
this.configFile = new File(addonFolder, addonName + ".yml");
this.addonConfig = configFile.exists() ? YamlConfiguration.loadConfiguration(configFile) : null;
}
public void generateFile(String fileName) {
generateFile(new File(addonFolder, fileName));
}
public void generateFileAbsPath(String absolutePath) {
generateFile(new File(absolutePath));
}
public void generateFile(File parent, String fileName) {
generateFile(new File(parent, fileName));
}
public void generateFile(File file) {
createAddonFolder();
try {
if (!file.exists()) {
file.createNewFile();
try (JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile))) {
JarEntry jarEntry;
while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
if (jarEntry.isDirectory() || !jarEntry.getName().equals(file.getName())) {
continue;
}
OutputStream outputStream = Files.newOutputStream(file.toPath());
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = jarInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
break;
}
}
}
} catch (IOException ex) {
logger.severe("Failed to generate file " + file.getName(), ex);
}
}
public File getFile(String fileName) {
createAddonFolder();
return new File(addonFolder, fileName);
}
public YamlConfiguration getYamlConfiguration(String fileName) {
createAddonFolder();
return YamlConfiguration.loadConfiguration(new File(addonFolder, fileName));
}
public File getAddonFolder() {
return addonFolder;
}
public YamlConfiguration getAddonConfig() {
generateAddonConfig();
return addonConfig;
}
public void saveAddonConfig() {
generateAddonConfig();
try {
addonConfig.save(configFile);
} catch (IOException ex) {
logger.severe("Failed to save addon config", ex);
}
}
private void generateAddonConfig() {
if (addonConfig == null) {
generateFile(configFile);
addonConfig = YamlConfiguration.loadConfiguration(configFile);
}
}
private void createAddonFolder() {
if (!addonFolder.exists()) {
addonFolder.mkdirs();
}
}
}

View File

@ -0,0 +1,44 @@
package com.dre.brewery.api.addons;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.BUtil;
import org.bukkit.Bukkit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AddonLogger {
private final static Logger logger = BreweryPlugin.getInstance().getLogger();
private final String fullPrefix;
private final String prefix;
public AddonLogger(Class<? extends BreweryAddon> addonUninstantiated) {
this.fullPrefix = "[Brewery] [" + addonUninstantiated.getSimpleName() + "] ";
this.prefix = "[" + addonUninstantiated.getSimpleName() + "] ";
}
public void info(String message) {
Bukkit.getConsoleSender().sendMessage(BUtil.color(fullPrefix + message));
}
public void warning(String message) {
logger.log(Level.WARNING, prefix + message);
}
public void severe(String message) {
logger.log(Level.SEVERE, prefix + message);
}
public void info(String message, Throwable throwable) {
info(message);
throwable.printStackTrace();
}
public void warning(String message, Throwable throwable) {
logger.log(Level.WARNING, prefix + message, throwable);
}
public void severe(String message, Throwable throwable) {
logger.log(Level.SEVERE, prefix + message, throwable);
}
}

View File

@ -0,0 +1,238 @@
package com.dre.brewery.api.addons;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.logging.Level;
public class AddonManager extends ClassLoader {
private final BreweryPlugin plugin;
private final File addonsFolder;
private final static List<BreweryAddon> addons = new ArrayList<>();
private final static List<AddonCommand> addonCommands = new ArrayList<>();
public AddonManager(BreweryPlugin plugin) {
this.plugin = plugin;
this.addonsFolder = new File(plugin.getDataFolder(), "addons");
if (!addonsFolder.exists()) {
addonsFolder.mkdirs();
}
}
public void unloadAddons() {
for (BreweryAddon addon : addons) {
addon.onAddonDisable();
}
int loaded = addons.size();
if (loaded > 0) plugin.log("Disabled " + loaded + " addon(s)");
addons.clear();
}
public void reloadAddons() {
for (BreweryAddon addon : addons) {
addon.onBreweryReload();
}
int loaded = addons.size();
if (loaded > 0) plugin.log("Reloaded " + loaded + " addon(s)");
}
public List<BreweryAddon> getAddons() {
return addons;
}
/**
* Get all classes that extend Addon and instantiates them
*/
public void loadAddons() {
File[] files = addonsFolder.listFiles((dir, name) -> name.endsWith(".jar"));
if (files == null) {
return;
}
for (File file : files) {
try {
List<Class<?>> classes = loadAllClassesFromJar(file);
for (Class<?> clazz : classes) {
if (!BreweryAddon.class.isAssignableFrom(clazz)) {
continue;
}
Class<? extends BreweryAddon> addonClass = clazz.asSubclass(BreweryAddon.class);
try {
BreweryAddon addon = addonClass.getConstructor(BreweryPlugin.class, AddonLogger.class).newInstance(plugin, new AddonLogger(addonClass));
addon.onAddonEnable(new AddonFileManager(addon, file));
addons.add(addon);
} catch (Exception e) {
plugin.getLogger().log(Level.SEVERE,"Failed to load addon class " + clazz.getSimpleName(), e);
}
}
} catch (Throwable ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to load addon classes from jar " + file.getName(), ex);
}
}
int loaded = addons.size();
if (loaded > 0) plugin.log("Loaded " + loaded + " addon(s)");
}
private static <T> @NotNull List<Class<? extends T>> findClasses(@NotNull final File file, @NotNull final Class<T> clazz) throws CompletionException {
if (!file.exists()) {
return Collections.emptyList();
}
final List<Class<? extends T>> classes = new ArrayList<>();
final List<String> matches = matchingNames(file);
for (final String match : matches) {
try {
final URL jar = file.toURI().toURL();
try (final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader())) {
Class<? extends T> addonClass = loadClass(loader, match, clazz);
if (addonClass != null) {
classes.add(addonClass);
}
}
} catch (final VerifyError ignored) {
} catch (IOException | ClassNotFoundException e) {
throw new CompletionException(e.getCause());
}
}
return classes;
}
private List<Class<?>> loadAllClassesFromJar(File jarFile) {
List<Class<?>> classes = new ArrayList<>();
try (URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, getClass().getClassLoader())) {
try (JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile))) {
JarEntry jarEntry;
String mainDir = "";
while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
if (jarEntry.getName().endsWith(".class")) {
String className = jarEntry.getName().replaceAll("/", ".").replace(".class", "");
try {
Class<?> clazz;
try {
clazz = Class.forName(className, false, classLoader);
} catch (ClassNotFoundException | NoClassDefFoundError e) {
continue;
}
if (BreweryAddon.class.isAssignableFrom(clazz)) {
classLoader.loadClass(className);
mainDir = className.substring(0, className.lastIndexOf('.'));
}
if (!clazz.getName().contains(mainDir)) {
continue;
}
classes.add(clazz);
} catch (ClassNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to load class " + className, e);
}
}
}
for (Class<?> clazz : classes) {
if (!BreweryAddon.class.isAssignableFrom(clazz)) {
try {
classLoader.loadClass(clazz.getName());
} catch (ClassNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to load class " + clazz.getName(), e);
}
}
}
}
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Error loading classes from JAR", e);
}
return classes;
}
private static @NotNull List<String> matchingNames(final File file) {
final List<String> matches = new ArrayList<>();
try {
final URL jar = file.toURI().toURL();
try (final JarInputStream stream = new JarInputStream(jar.openStream())) {
JarEntry entry;
while ((entry = stream.getNextJarEntry()) != null) {
final String name = entry.getName();
if (!name.endsWith(".class")) {
continue;
}
matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.'));
}
}
} catch (Exception e) {
return Collections.emptyList();
}
return matches;
}
private static <T> @Nullable Class<? extends T> loadClass(final @NotNull URLClassLoader loader, final String match, @NotNull final Class<T> clazz) throws ClassNotFoundException {
try {
final Class<?> loaded = loader.loadClass(match);
if (clazz.isAssignableFrom(loaded)) {
return (loaded.asSubclass(clazz));
}
} catch (final NoClassDefFoundError ignored) {
}
return null;
}
public static void registerAddonCommand(AddonCommand addonCommand) {
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
if (commandMap.getCommand(addonCommand.getName()) != null) {
commandMap.getCommand(addonCommand.getName()).unregister(commandMap);
}
commandMap.register(addonCommand.getName(), "brewery", addonCommand);
addonCommands.add(addonCommand);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static void unRegisterAddonCommand(AddonCommand addonCommand) {
try { // no worky :(
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
if (commandMap == null) return;
for (AddonCommand bukkitCommand : addonCommands) {
for (String alias : bukkitCommand.getAliases()) {
commandMap.getCommand("brewery:" + alias).unregister(commandMap);
}
commandMap.getCommand("brewery:" + bukkitCommand.getName()).unregister(commandMap);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,27 @@
package com.dre.brewery.api.addons;
import com.dre.brewery.BreweryPlugin;
public abstract class BreweryAddon {
protected final BreweryPlugin plugin;
protected final AddonLogger logger;
public BreweryAddon(BreweryPlugin plugin, AddonLogger logger) {
this.plugin = plugin;
this.logger = logger;
}
public void onAddonEnable(AddonFileManager addonFileManager) {
}
public void onAddonDisable() {
}
public void onBreweryReload() {
}
public AddonLogger getLogger() {
return logger;
}
}

View File

@ -0,0 +1,98 @@
package com.dre.brewery.commands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.subcommands.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandManager implements TabExecutor {
private static final BreweryPlugin plugin = BreweryPlugin.getInstance();
private static final Map<String, SubCommand> subCommands = new HashMap<>();
public CommandManager() {
subCommands.put("help" , new HelpCommand());
subCommands.put("reload", new ReloadCommand(plugin));
subCommands.put("wakeup", new WakeupCommand());
subCommands.put("itemName", new ItemName());
subCommands.put("create", new CreateCommand(plugin));
subCommands.put("info", new InfoCommand(plugin));
subCommands.put("seal", new SealCommand());
subCommands.put("copy", new CopyCommand(plugin));
subCommands.put("delete", new DeleteCommand(plugin));
subCommands.put("static", new StaticCommand());
subCommands.put("unLabel", new UnLabelCommand());
subCommands.put("debuginfo", new DebugInfoCommand(plugin));
subCommands.put("showstats", new ShowStatsCommand());
subCommands.put("puke", new PukeCommand());
subCommands.put("drink", new DrinkCommand());
subCommands.put("reloadaddons", new ReloadAddonsCommand());
subCommands.put("version", new VersionCommand());
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
if (args.length < 1) {
CommandUtil.cmdHelp(sender, args);
return true;
}
SubCommand subCommand = subCommands.get(args[0]); //
if (subCommand == null) {
CommandUtil.cmdHelp(sender, args);
return true;
}
boolean playerOnly = subCommand.playerOnly();
String permission = subCommand.permission();
if (playerOnly && !(sender instanceof Player)) {
plugin.msg(sender, plugin.languageReader.get("Error_NotPlayer"));
return true;
} else if (permission != null && !sender.hasPermission(permission)) {
plugin.msg(sender, plugin.languageReader.get("Error_NoPermission"));
return true;
}
subCommand.execute(plugin, sender, s, args);
return false;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) {
if (strings.length == 1) {
List<String> commands = new ArrayList<>();
for (Map.Entry<String, SubCommand> entry : subCommands.entrySet()) {
String perm = entry.getValue().permission();
if (perm != null && commandSender.hasPermission(perm)) {
commands.add(entry.getKey());
}
}
return commands;
}
SubCommand subCommand = subCommands.get(strings[0].toLowerCase());
if (subCommand != null) {
return subCommand.tabComplete(plugin, commandSender, s, strings);
}
return null;
}
public static void addSubCommand(String name, SubCommand subCommand) {
subCommands.put(name, subCommand);
}
public static void removeSubCommand(String name) {
subCommands.remove(name);
}
}

View File

@ -0,0 +1,248 @@
package com.dre.brewery.commands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.recipe.BRecipe;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.PermissionUtil;
import com.dre.brewery.utility.Tuple;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
import static com.dre.brewery.utility.PermissionUtil.BPermission.*;
public class CommandUtil {
private static final BreweryPlugin BREWERY_PLUGIN = BreweryPlugin.getInstance();
private static Set<Tuple<String, String>> mainSet;
private static Set<Tuple<String, String>> altSet;
private static final String[] QUALITY = {"1", "10"};
public static void cmdHelp(CommandSender sender, String[] args) {
int page = 1;
if (args.length > 1) {
page = BREWERY_PLUGIN.parseInt(args[1]);
}
ArrayList<String> commands = getCommands(sender);
if (page == 1) {
BREWERY_PLUGIN.msg(sender, "&6" + BREWERY_PLUGIN.getDescription().getName() + " v" + BREWERY_PLUGIN.getDescription().getVersion());
}
BUtil.list(sender, commands, page);
}
@Nullable
public static Tuple<Brew, Player> getFromCommand(CommandSender sender, String[] args) {
if (args.length < 2) {
return null;
}
int quality = 10;
boolean hasQuality = false;
String pName = null;
if (args.length > 2) {
quality = BREWERY_PLUGIN.parseInt(args[args.length - 1]);
if (quality <= 0 || quality > 10) {
pName = args[args.length - 1];
if (args.length > 3) {
quality = BREWERY_PLUGIN.parseInt(args[args.length - 2]);
}
}
if (quality > 0 && quality <= 10) {
hasQuality = true;
} else {
quality = 10;
}
}
Player player = null;
if (pName != null) {
player = BREWERY_PLUGIN.getServer().getPlayer(pName);
}
if (!(sender instanceof Player) && player == null) {
BREWERY_PLUGIN.msg(sender, BREWERY_PLUGIN.languageReader.get("Error_PlayerCommand"));
return null;
}
if (player == null) {
player = ((Player) sender);
pName = null;
}
int stringLength = args.length - 1;
if (pName != null) {
stringLength--;
}
if (hasQuality) {
stringLength--;
}
String name;
if (stringLength > 1) {
StringBuilder builder = new StringBuilder(args[1]);
for (int i = 2; i < stringLength + 1; i++) {
builder.append(" ").append(args[i]);
}
name = builder.toString();
} else {
name = args[1];
}
name = name.replaceAll("\"", "");
BRecipe recipe = BRecipe.getMatching(name);
if (recipe != null) {
return new Tuple<>(recipe.createBrew(quality), player);
} else {
BREWERY_PLUGIN.msg(sender, BREWERY_PLUGIN.languageReader.get("Error_NoBrewName", name));
}
return null;
}
public static ArrayList<String> getCommands(CommandSender sender) {
ArrayList<String> cmds = new ArrayList<>();
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Help"));
PermissionUtil.evaluateExtendedPermissions(sender);
if (PLAYER.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_Player"));
}
if (INFO.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_Info"));
}
if (BreweryPlugin.use1_13 && SEAL.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_Seal"));
}
if (UNLABEL.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_UnLabel"));
}
if (PermissionUtil.noExtendedPermissions(sender)) {
return cmds;
}
if (INFO_OTHER.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_InfoOther"));
}
if (CREATE.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Create"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Give"));
}
if (DRINK.checkCached(sender) || DRINK_OTHER.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Drink"));
}
if (RELOAD.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Configname"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Reload"));
}
if (PUKE.checkCached(sender) || PUKE_OTHER.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Puke"));
}
if (WAKEUP.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Wakeup"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_WakeupList"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_WakeupCheck"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_WakeupCheckSpecific"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_WakeupAdd"));
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_WakeupRemove"));
}
if (STATIC.checkCached(sender)) {
cmds.add(BREWERY_PLUGIN.languageReader.get("Help_Static"));
}
if (COPY.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_Copy"));
}
if (DELETE.checkCached(sender)) {
cmds.add (BREWERY_PLUGIN.languageReader.get("Help_Delete"));
}
return cmds;
}
public static List<String> tabCreateAndDrink(String[] args) {
if (args.length == 2) {
if (mainSet == null) {
mainSet = new HashSet<>();
altSet = new HashSet<>();
for (BRecipe recipe : BRecipe.getAllRecipes()) {
mainSet.addAll(createLookupFromName(recipe.getName(5)));
Set<String> altNames = new HashSet<>(3);
altNames.add(recipe.getName(1));
altNames.add(recipe.getName(10));
if (recipe.getOptionalID().isPresent()) {
altNames.add(recipe.getOptionalID().get());
}
for (String altName : altNames) {
altSet.addAll(createLookupFromName(altName));
}
}
}
final String input = args[1].toLowerCase();
List<String> options = mainSet.stream()
.filter(s -> s.a().startsWith(input))
.map(Tuple::second)
.collect(Collectors.toList());
if (options.isEmpty()) {
options = altSet.stream()
.filter(s -> s.a().startsWith(input))
.map(Tuple::second)
.collect(Collectors.toList());
}
return options;
} else {
if (args[args.length - 2].matches("\\d")) {
// Player list
return null;
} else {
return filterWithInput(QUALITY, args[args.length - 1]);
}
}
}
private static List<Tuple<String, String>> createLookupFromName(final String name) {
return Arrays.stream(name.split(" "))
.map(word -> new Tuple<>(word.toLowerCase(), name))
.collect(Collectors.toList());
}
public static List<String> filterWithInput(String[] options, String input) {
return Arrays.stream(options)
.filter(s -> s.startsWith(input))
.collect(Collectors.toList());
}
public static void reloadTabCompleter() {
mainSet = null;
altSet = null;
}
}

View File

@ -0,0 +1,38 @@
package com.dre.brewery.commands;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.command.CommandSender;
import java.util.List;
public interface SubCommand {
/**
* Executes the subcommand's code
* @param breweryPlugin Instance of the Brewery plugin
* @param sender The CommandSender that executed the command
* @param label The command label (alias)
* @param args The command arguments
*/
void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args);
/**
* Returns a list of possible tab completions for the subcommand
* @param breweryPlugin Instance of the Brewery plugin
* @param sender The CommandSender that executed the command
* @param label The command label (alias)
* @param args The command arguments
* @return A list of possible tab completions for the subcommand
*/
List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args);
/**
* @return the subcommand's required permission node
*/
String permission();
/**
* @return if the command can only be executed by a player
*/
boolean playerOnly();
}

View File

@ -0,0 +1,70 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class CopyCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public CopyCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length > 1) {
cmdCopy(sender, breweryPlugin.parseInt(args[1]));
} else {
cmdCopy(sender, 1);
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.copy";
}
@Override
public boolean playerOnly() {
return true;
}
//@Deprecated but still used?
public void cmdCopy(CommandSender sender, int count) {
if (count < 1 || count > 36) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Etc_Usage"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Help_Copy"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
if (Brew.isBrew(hand)) {
while (count > 0) {
ItemStack item = hand.clone();
if (!(player.getInventory().addItem(item)).isEmpty()) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Copy_Error", "" + count));
return;
}
count--;
}
return;
}
}
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_ItemNotPotion"));
}
}

View File

@ -0,0 +1,62 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.utility.Tuple;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class CreateCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public CreateCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length < 2) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Etc_Usage"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Help_Create"));
return;
}
// Is this just a map?
Tuple<Brew, Player> brewForPlayer = CommandUtil.getFromCommand(sender, args);
if (brewForPlayer != null) {
if (brewForPlayer.b().getInventory().firstEmpty() == -1) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Copy_Error", "1"));
return;
}
ItemStack item = brewForPlayer.a().createItem(null);
if (item != null) {
brewForPlayer.b().getInventory().addItem(item);
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Created"));
}
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return CommandUtil.tabCreateAndDrink(args);
}
@Override
public String permission() {
return "brewery.cmd.create";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,95 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BIngredients;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.recipe.BRecipe;
import com.dre.brewery.recipe.Ingredient;
import com.dre.brewery.recipe.RecipeItem;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class DebugInfoCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public DebugInfoCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
debugInfo(sender, args.length > 1 ? args[1] : null);
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.debuginfo";
}
@Override
public boolean playerOnly() {
return true;
}
public void debugInfo(CommandSender sender, String recipeName) {
if (!BreweryPlugin.use1_9 || !sender.isOp()) return;
Player player = (Player) sender;
ItemStack hand = player.getInventory().getItemInMainHand();
if (hand != null) {
Brew brew = Brew.get(hand);
if (brew == null) return;
BreweryPlugin.getInstance().log(brew.toString());
BIngredients ingredients = brew.getIngredients();
if (recipeName == null) {
BreweryPlugin.getInstance().log("&lIngredients:");
for (Ingredient ing : ingredients.getIngredientList()) {
BreweryPlugin.getInstance().log(ing.toString());
}
BreweryPlugin.getInstance().log("&lTesting Recipes");
for (BRecipe recipe : BRecipe.getAllRecipes()) {
int ingQ = ingredients.getIngredientQuality(recipe);
int cookQ = ingredients.getCookingQuality(recipe, false);
int cookDistQ = ingredients.getCookingQuality(recipe, true);
int ageQ = ingredients.getAgeQuality(recipe, brew.getAgeTime());
BreweryPlugin.getInstance().log(recipe.getRecipeName() + ": ingQlty: " + ingQ + ", cookQlty:" + cookQ + ", cook+DistQlty: " + cookDistQ + ", ageQlty: " + ageQ);
}
BRecipe distill = ingredients.getBestRecipe(brew.getWood(), brew.getAgeTime(), true);
BRecipe nonDistill = ingredients.getBestRecipe(brew.getWood(), brew.getAgeTime(), false);
BreweryPlugin.getInstance().log("&lWould prefer Recipe: " + (nonDistill == null ? "none" : nonDistill.getRecipeName()) + " and Distill-Recipe: " + (distill == null ? "none" : distill.getRecipeName()));
} else {
BRecipe recipe = BRecipe.getMatching(recipeName);
if (recipe == null) {
BreweryPlugin.getInstance().msg(player, "Could not find Recipe " + recipeName);
return;
}
BreweryPlugin.getInstance().log("&lIngredients in Recipe " + recipe.getRecipeName() + ":");
for (RecipeItem ri : recipe.getIngredients()) {
BreweryPlugin.getInstance().log(ri.toString());
}
BreweryPlugin.getInstance().log("&lIngredients in Brew:");
for (Ingredient ingredient : ingredients.getIngredientList()) {
int amountInRecipe = recipe.amountOf(ingredient);
BreweryPlugin.getInstance().log(ingredient.toString() + ": " + amountInRecipe + " of this are in the Recipe");
}
int ingQ = ingredients.getIngredientQuality(recipe);
int cookQ = ingredients.getCookingQuality(recipe, false);
int cookDistQ = ingredients.getCookingQuality(recipe, true);
int ageQ = ingredients.getAgeQuality(recipe, brew.getAgeTime());
BreweryPlugin.getInstance().log("ingQlty: " + ingQ + ", cookQlty:" + cookQ + ", cook+DistQlty: " + cookDistQ + ", ageQlty: " + ageQ);
}
BreweryPlugin.getInstance().msg(player, "Debug Info for item written into Log");
}
}
}

View File

@ -0,0 +1,49 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
public class DeleteCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public DeleteCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
if (Brew.isBrew(hand)) {
player.setItemInHand(new ItemStack(Material.AIR));
return;
}
}
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_ItemNotPotion"));
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.delete";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,51 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BPlayer;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.utility.Tuple;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class DrinkCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length < 2) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Etc_Usage"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Help_Drink"));
return;
}
Tuple<Brew, Player> brewForPlayer = CommandUtil.getFromCommand(sender, args);
if (brewForPlayer != null) {
Player player = brewForPlayer.b();
Brew brew = brewForPlayer.a();
String brewName = brew.getCurrentRecipe().getName(brew.getQuality());
BPlayer.drink(brew, null, player);
breweryPlugin.msg(player, breweryPlugin.languageReader.get("CMD_Drink", brewName));
if (!sender.equals(player)) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_DrinkOther", player.getDisplayName(), brewName));
}
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return CommandUtil.tabCreateAndDrink(args);
}
@Override
public String permission() {
return "brewery.cmd.drink";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,46 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.utility.BUtil;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class HelpCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
int page = 1;
if (args.length > 1) {
page = breweryPlugin.parseInt(args[1]);
}
ArrayList<String> commands = CommandUtil.getCommands(sender);
if (page == 1) {
breweryPlugin.msg(sender, "&6" + breweryPlugin.getDescription().getName() + " v" + breweryPlugin.getDescription().getVersion());
}
BUtil.list(sender, commands, page);
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return null;
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -0,0 +1,82 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BPlayer;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class InfoCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public InfoCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length > 1) {
if (sender.hasPermission("brewery.cmd.infoOther")) {
cmdInfo(sender, args[1]);
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_NoPermissions"));
}
} else {
if (sender.hasPermission("brewery.cmd.info")) {
cmdInfo(sender, null);
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_NoPermissions"));
}
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.info";
}
@Override
public boolean playerOnly() {
return false;
}
public void cmdInfo(CommandSender sender, String playerName) {
boolean selfInfo = playerName == null;
if (selfInfo) {
if (sender instanceof Player) {
Player player = (Player) sender;
playerName = player.getName();
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_PlayerCommand"));
return;
}
}
Player player = BreweryPlugin.getInstance().getServer().getPlayerExact(playerName);
BPlayer bPlayer;
if (player == null) {
bPlayer = BPlayer.getByName(playerName);
} else {
bPlayer = BPlayer.get(player);
}
if (bPlayer == null) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Info_NotDrunk", playerName));
} else {
if (selfInfo) {
bPlayer.showDrunkeness(player);
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Info_Drunk", playerName, "" + bPlayer.getDrunkeness(), "" + bPlayer.getQuality()));
}
}
}
}

View File

@ -0,0 +1,39 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Locale;
public class ItemName implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
Player player = (Player) sender;
@SuppressWarnings("deprecation")
ItemStack hand = BreweryPlugin.use1_9 ? player.getInventory().getItemInMainHand() : player.getItemInHand();
if (hand != null) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Configname", hand.getType().name().toLowerCase(Locale.ENGLISH)));
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Configname_Error"));
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.itemname";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,59 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BPlayer;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class PukeCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
Player player = null;
if (args.length > 1) {
player = breweryPlugin.getServer().getPlayer(args[1]);
if (player == null) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_NoPlayer", args[1]));
return;
}
}
if (!(sender instanceof Player) && player == null) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_PlayerCommand"));
return;
}
if (player == null) {
player = ((Player) sender);
} else {
if (!sender.hasPermission("brewery.cmd.pukeOther") && !player.equals(sender)) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_NoPermissions"));
return;
}
}
int count = 0;
if (args.length > 2) {
count = BreweryPlugin.getInstance().parseInt(args[2]);
}
if (count <= 0) {
count = 20 + (int) (Math.random() * 40);
}
BPlayer.addPuke(player, count);
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.puke";
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -0,0 +1,38 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.addons.AddonManager;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import java.util.List;
public class ReloadAddonsCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length > 1 && args[1].equalsIgnoreCase("confirm")) {
AddonManager addonManager = new AddonManager(breweryPlugin);
addonManager.unloadAddons();
addonManager.loadAddons();
breweryPlugin.msg(sender, "Loaded " + addonManager.getAddons().size() + " addons");
} else {
breweryPlugin.msg(sender, "&rThis command should be avoided as it can cause unpredictable behavior within addons, use &c/brewery reloadaddons confirm &r to confirm.");
breweryPlugin.msg(sender, "&aMost addons support reloading without using this command! Try using &c/brewery reload &ainstead.");
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return List.of("confirm");
}
@Override
public String permission() {
return "brewery.cmd.reloadaddons";
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -0,0 +1,87 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BCauldron;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.addons.AddonManager;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.filedata.BConfig;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.List;
public class ReloadCommand implements SubCommand {
private final BreweryPlugin breweryPlugin;
public ReloadCommand(BreweryPlugin breweryPlugin) {
this.breweryPlugin = breweryPlugin;
}
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (sender != null && !sender.equals(Bukkit.getConsoleSender())) {
BConfig.reloader = sender;
}
FileConfiguration cfg = BConfig.loadConfigFile();
if (cfg == null) {
// Could not read yml file, do not proceed, error was printed
breweryPlugin.log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
// clear all existent config Data
breweryPlugin. clearConfigData();
// load the Config
try {
BConfig.readConfig(cfg);
} catch (Exception e) {
e.printStackTrace();
breweryPlugin.log("Something went wrong when trying to load the config file! Please check your config.yml");
return;
}
// Reload Cauldron Particle Recipes
BCauldron.reload();
// Clear Recipe completions
CommandUtil.reloadTabCompleter();
// Reload Recipes
boolean successful = true;
for (Brew brew : Brew.legacyPotions.values()) {
if (!brew.reloadRecipe()) {
successful = false;
}
}
if (sender != null) {
if (!successful) {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_Recipeload"));
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Reload"));
}
}
new AddonManager(breweryPlugin).reloadAddons();
BConfig.reloader = null;
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.reload";
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -0,0 +1,37 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BSealer;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class SealCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (!BreweryPlugin.use1_13) {
BreweryPlugin.getInstance().msg(sender, "Sealing requires minecraft 1.13 or higher");
return;
}
Player player = (Player) sender;
player.openInventory(new BSealer(player).getInventory());
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.seal";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,37 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.*;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.recipe.BRecipe;
import org.bukkit.command.CommandSender;
import java.util.List;
public class ShowStatsCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
//if (sender instanceof ConsoleCommandSender && !sender.isOp()) return;
BreweryPlugin.getInstance().msg(sender, "Drunk Players: " + BPlayer.numDrunkPlayers());
BreweryPlugin.getInstance().msg(sender, "Brews created: " + BreweryPlugin.getInstance().stats.brewsCreated);
BreweryPlugin.getInstance().msg(sender, "Barrels built: " + Barrel.barrels.size());
BreweryPlugin.getInstance().msg(sender, "Cauldrons boiling: " + BCauldron.bcauldrons.size());
BreweryPlugin.getInstance().msg(sender, "Number of Recipes: " + BRecipe.getAllRecipes().size());
BreweryPlugin.getInstance().msg(sender, "Wakeups: " + Wakeup.wakeups.size());
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.showstats";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,65 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.brew.BrewModifyEvent;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
public class StaticCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand.getType() != Material.AIR) {
Brew brew = Brew.get(hand);
if (brew != null) {
if (brew.isStatic()) {
if (!brew.isStripped()) {
brew.setStatic(false, hand);
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_NonStatic"));
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_SealedAlwaysStatic"));
return;
}
} else {
brew.setStatic(true, hand);
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_Static"));
}
brew.touch();
ItemMeta meta = hand.getItemMeta();
assert meta != null;
BrewModifyEvent modifyEvent = new BrewModifyEvent(brew, meta, BrewModifyEvent.Type.STATIC);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
return;
}
brew.save(meta);
hand.setItemMeta(meta);
return;
}
}
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_ItemNotPotion"));
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.static";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,62 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.Brew;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.brew.BrewModifyEvent;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
public class UnLabelCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
Player player = (Player) sender;
ItemStack hand = player.getInventory().getItemInMainHand();
if (hand.getType() != Material.AIR) {
Brew brew = Brew.get(hand);
if (brew != null) {
if (!brew.isUnlabeled()) {
ItemMeta origMeta = hand.getItemMeta();
brew.unLabel(hand);
brew.touch();
ItemMeta meta = hand.getItemMeta();
assert meta != null;
BrewModifyEvent modifyEvent = new BrewModifyEvent(brew, meta, BrewModifyEvent.Type.UNLABEL);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
hand.setItemMeta(origMeta);
return;
}
brew.save(meta);
hand.setItemMeta(meta);
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("CMD_UnLabel"));
return;
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_AlreadyUnlabeled"));
return;
}
}
}
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_ItemNotPotion"));
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.unlabel";
}
@Override
public boolean playerOnly() {
return true;
}
}

View File

@ -0,0 +1,45 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.addons.AddonManager;
import com.dre.brewery.api.addons.BreweryAddon;
import com.dre.brewery.commands.SubCommand;
import com.dre.brewery.filedata.UpdateChecker;
import org.bukkit.command.CommandSender;
import java.util.List;
public class VersionCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
List<BreweryAddon> addons = new AddonManager(breweryPlugin).getAddons();
StringBuilder addonString = new StringBuilder();
for (BreweryAddon addon : addons) {
addonString.append(addon.getClass().getSimpleName());
if (addons.indexOf(addon) < addons.size() - 1) {
addonString.append("&f, &a");
}
}
breweryPlugin.msg(sender, "&2BreweryX version&7: &av" + breweryPlugin.getDescription().getVersion() + " &7(Latest: v" + UpdateChecker.getLatestVersion() + ")");
breweryPlugin.msg(sender, "&2Original Authors&7: &aGrafe&f, &aTTTheKing&f, &aSn0wStorm");
breweryPlugin.msg(sender, "&2BreweryX Authors/Maintainers&7: &aJsinco");
breweryPlugin.msg(sender, "&2Loaded addons&7: &a" + addonString);
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.version";
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -0,0 +1,82 @@
package com.dre.brewery.commands.subcommands;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.Wakeup;
import com.dre.brewery.commands.CommandUtil;
import com.dre.brewery.commands.SubCommand;
import org.bukkit.command.CommandSender;
import java.util.List;
public class WakeupCommand implements SubCommand {
@Override
public void execute(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
if (args.length == 1) {
CommandUtil.cmdHelp(sender, args);
return;
}
if (args[1].equalsIgnoreCase("add")) {
Wakeup.set(sender);
} else if (args[1].equalsIgnoreCase("list")){
int page = 1;
String world = null;
if (args.length > 2) {
page = breweryPlugin.parseInt(args[2]);
}
if (args.length > 3) {
world = args[3];
}
Wakeup.list(sender, page, world);
} else if (args[1].equalsIgnoreCase("remove")){
if (args.length > 2) {
int id = breweryPlugin.parseInt(args[2]);
Wakeup.remove(sender, id);
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Etc_Usage"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Help_WakeupRemove"));
}
} else if (args[1].equalsIgnoreCase("check")){
int id = -1;
if (args.length > 2) {
id = breweryPlugin.parseInt(args[2]);
if (id < 0) {
id = 0;
}
}
Wakeup.check(sender, id, id == -1);
} else if (args[1].equalsIgnoreCase("cancel")){
Wakeup.cancel(sender);
} else {
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_UnknownCommand"));
breweryPlugin.msg(sender, breweryPlugin.languageReader.get("Error_ShowHelp"));
}
}
@Override
public List<String> tabComplete(BreweryPlugin breweryPlugin, CommandSender sender, String label, String[] args) {
return null;
}
@Override
public String permission() {
return "brewery.cmd.wakeup";
}
@Override
public boolean playerOnly() {
return false;
}
}

View File

@ -1,10 +1,7 @@
package com.dre.brewery.filedata;
import com.dre.brewery.BSealer;
import com.dre.brewery.Brew;
import com.dre.brewery.DistortChat;
import com.dre.brewery.MCBarrel;
import com.dre.brewery.P;
import com.dre.brewery.*;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.ConfigLoadEvent;
import com.dre.brewery.integration.barrel.BlocklockerBarrel;
import com.dre.brewery.integration.barrel.WGBarrel;
@ -37,6 +34,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class BConfig {
@ -72,7 +70,7 @@ public class BConfig {
//BPlayer
public static Map<Material, Integer> drainItems = new HashMap<>();// DrainItem Material and Strength
public static Material pukeItem;
public static List<Material> pukeItem;
public static boolean showStatusOnDrink;
public static int pukeDespawntime;
public static float stumbleModifier;
@ -90,11 +88,13 @@ public class BConfig {
public static boolean enableEncode;
public static boolean alwaysShowQuality; // Always show quality stars
public static boolean alwaysShowAlc; // Always show alc%
public static boolean showBrewer;
public static boolean brewHopperDump; // Allow Dumping of Brew liquid into Hoppers
//Features
public static boolean craftSealingTable; // Allow Crafting of Sealing Table
public static boolean enableSealingTable; // Allow Usage of Sealing Table
public static String pluginPrefix = "&2[Brewery]&f ";
//Item
public static List<RecipeItem> customItems = new ArrayList<>();
@ -104,28 +104,28 @@ public class BConfig {
public static SQLSync sqlSync;
public static boolean sqlDrunkSync;
public static P p = P.p;
public static BreweryPlugin breweryPlugin = BreweryPlugin.getInstance();
private static boolean checkConfigs() {
File cfg = new File(p.getDataFolder(), "config.yml");
File cfg = new File(breweryPlugin.getDataFolder(), "config.yml");
if (!cfg.exists()) {
p.log("§1§lNo config.yml found, creating default file! You may want to choose a config according to your language!");
p.log("§1§lYou can find them in plugins/Brewery/configs/");
p.log("§1§lJust copy the config for your language into the Brewery folder and /brew reload");
InputStream defconf = p.getResource("config/" + (P.use1_13 ? "v13/" : "v12/") + "en/config.yml");
breweryPlugin.log("§1§lNo config.yml found, creating default file! You may want to choose a config according to your language!");
breweryPlugin.log("§1§lYou can find them in plugins/Brewery/configs/");
breweryPlugin.log("§1§lJust copy the config for your language into the Brewery folder and /brew reload");
InputStream defconf = breweryPlugin.getResource("config/" + (BreweryPlugin.use1_13 ? "v13/" : "v12/") + "en/config.yml");
if (defconf == null) {
p.errorLog("default config file not found, your jarfile may be corrupt. Disabling Brewery!");
breweryPlugin.errorLog("default config file not found, your jarfile may be corrupt. Disabling Brewery!");
return false;
}
try {
BUtil.saveFile(defconf, p.getDataFolder(), "config.yml", false);
BUtil.saveFile(defconf, breweryPlugin.getDataFolder(), "config.yml", false);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
if (!cfg.exists()) {
p.errorLog("default config file could not be copied, your jarfile may be corrupt. Disabling Brewery!");
breweryPlugin.errorLog("default config file could not be copied, your jarfile may be corrupt. Disabling Brewery!");
return false;
}
@ -134,13 +134,13 @@ public class BConfig {
}
private static void copyDefaultConfigs(boolean overwrite) {
File configs = new File(p.getDataFolder(), "configs");
File languages = new File(p.getDataFolder(), "languages");
File configs = new File(breweryPlugin.getDataFolder(), "configs");
File languages = new File(breweryPlugin.getDataFolder(), "languages");
for (String l : new String[] {"de", "en", "fr", "it", "zh", "tw"}) {
File lfold = new File(configs, l);
try {
BUtil.saveFile(p.getResource("config/" + (P.use1_13 ? "v13/" : "v12/") + l + "/config.yml"), lfold, "config.yml", overwrite);
BUtil.saveFile(p.getResource("languages/" + l + ".yml"), languages, l + ".yml", false); // Never overwrite languages, they get updated with their updater
BUtil.saveFile(breweryPlugin.getResource("config/" + (BreweryPlugin.use1_13 ? "v13/" : "v12/") + l + "/config.yml"), lfold, "config.yml", overwrite);
BUtil.saveFile(breweryPlugin.getResource("languages/" + l + ".yml"), languages, l + ".yml", false); // Never overwrite languages, they get updated with their updater
} catch (IOException e) {
if (!(l.equals("zh") || l.equals("tw"))) {
// zh and tw not available for some versions
@ -151,7 +151,7 @@ public class BConfig {
}
public static FileConfiguration loadConfigFile() {
File file = new File(P.p.getDataFolder(), "config.yml");
File file = new File(BreweryPlugin.getInstance().getDataFolder(), "config.yml");
if (!checkConfigs()) {
return null;
}
@ -166,20 +166,20 @@ public class BConfig {
}
// Failed to load
if (p.languageReader != null) {
P.p.errorLog(p.languageReader.get("Error_YmlRead"));
if (breweryPlugin.languageReader != null) {
BreweryPlugin.getInstance().errorLog(breweryPlugin.languageReader.get("Error_YmlRead"));
} else {
P.p.errorLog("Could not read file config.yml, please make sure the file is in valid yml format (correct spaces etc.)");
BreweryPlugin.getInstance().errorLog("Could not read file config.yml, please make sure the file is in valid yml format (correct spaces etc.)");
}
return null;
}
public static void readConfig(FileConfiguration config) {
// Set the Language
p.language = config.getString("language", "en");
breweryPlugin.language = config.getString("language", "en");
// Load LanguageReader
p.languageReader = new LanguageReader(new File(p.getDataFolder(), "languages/" + p.language + ".yml"), "languages/" + p.language + ".yml");
breweryPlugin.languageReader = new LanguageReader(new File(breweryPlugin.getDataFolder(), "languages/" + breweryPlugin.language + ".yml"), "languages/" + breweryPlugin.language + ".yml");
// Has to config still got old materials
boolean oldMat = config.getBoolean("oldMat", false);
@ -187,11 +187,11 @@ public class BConfig {
// Check if config is the newest version
String version = config.getString("version", null);
if (version != null) {
if (!version.equals(configVersion) || (oldMat && P.use1_13)) {
File file = new File(P.p.getDataFolder(), "config.yml");
if (!version.equals(configVersion) || (oldMat && BreweryPlugin.use1_13)) {
File file = new File(BreweryPlugin.getInstance().getDataFolder(), "config.yml");
copyDefaultConfigs(true);
new ConfigUpdater(file).update(version, oldMat, p.language, config);
P.p.log("Config Updated to version: " + configVersion);
new ConfigUpdater(file).update(version, oldMat, breweryPlugin.language, config);
BreweryPlugin.getInstance().log("Config Updated to version: " + configVersion);
config = YamlConfiguration.loadConfiguration(file);
}
}
@ -199,7 +199,7 @@ public class BConfig {
// If the Update Checker should be enabled
updateCheck = config.getBoolean("updateCheck", false);
PluginManager plMan = p.getServer().getPluginManager();
PluginManager plMan = breweryPlugin.getServer().getPluginManager();
// Third-Party
useWG = config.getBoolean("useWorldGuard", true) && plMan.isPluginEnabled("WorldGuard");
@ -220,8 +220,9 @@ public class BConfig {
// various Settings
DataSave.autosave = config.getInt("autosave", 3);
P.debug = config.getBoolean("debug", false);
pukeItem = Material.matchMaterial(config.getString("pukeItem", "SOUL_SAND"));
BreweryPlugin.debug = config.getBoolean("debug", false);
pukeItem = !config.getStringList("pukeItem").isEmpty() ? config.getStringList("pukeItem").stream().map(Material::matchMaterial).collect(Collectors.toList())
: List.of(Material.matchMaterial(config.getString("pukeItem"))); //Material.matchMaterial(config.getString("pukeItem", "SOUL_SAND"));
hangoverTime = config.getInt("hangoverDays", 0) * 24 * 60;
overdrinkKick = config.getBoolean("enableKickOnOverdrink", false);
enableHome = config.getBoolean("enableHome", false);
@ -234,26 +235,28 @@ public class BConfig {
enableWake = config.getBoolean("enableWake", false);
craftSealingTable = config.getBoolean("craftSealingTable", false);
enableSealingTable = config.getBoolean("enableSealingTable", false);
pluginPrefix = config.getString("pluginPrefix", "&2[Brewery]&f ");
colorInBarrels = config.getBoolean("colorInBarrels", false);
colorInBrewer = config.getBoolean("colorInBrewer", false);
alwaysShowQuality = config.getBoolean("alwaysShowQuality", false);
alwaysShowAlc = config.getBoolean("alwaysShowAlc", false);
showBrewer = config.getBoolean("showBrewer", false);
enableEncode = config.getBoolean("enableEncode", false);
openEverywhere = config.getBoolean("openLargeBarrelEverywhere", false);
enableCauldronParticles = P.use1_9 && config.getBoolean("enableCauldronParticles", false);
enableCauldronParticles = BreweryPlugin.use1_9 && config.getBoolean("enableCauldronParticles", false);
minimalParticles = config.getBoolean("minimalParticles", false);
useOffhandForCauldron = config.getBoolean("useOffhandForCauldron", false);
loadDataAsync = config.getBoolean("loadDataAsync", true);
brewHopperDump = config.getBoolean("brewHopperDump", false);
if (P.use1_14) {
if (BreweryPlugin.use1_14) {
MCBarrel.maxBrews = config.getInt("maxBrewsInMCBarrels", 6);
MCBarrel.enableAging = config.getBoolean("ageInMCBarrels", true);
}
Brew.loadSeed(config, new File(P.p.getDataFolder(), "config.yml"));
Brew.loadSeed(config, new File(BreweryPlugin.getInstance().getDataFolder(), "config.yml"));
if (!P.use1_13) {
if (!BreweryPlugin.use1_13) {
// world.getBlockAt loads Chunks in 1.12 and lower. Can't load async
loadDataAsync = false;
}
@ -272,7 +275,7 @@ public class BConfig {
custom.makeImmutable();
customItems.add(custom);
} else {
p.errorLog("Loading the Custom Item with id: '" + custId + "' failed!");
breweryPlugin.errorLog("Loading the Custom Item with id: '" + custId + "' failed!");
}
}
}
@ -286,7 +289,7 @@ public class BConfig {
if (recipe != null && recipe.isValid()) {
configRecipes.add(recipe);
} else {
p.errorLog("Loading the Recipe with id: '" + recipeId + "' failed!");
breweryPlugin.errorLog("Loading the Recipe with id: '" + recipeId + "' failed!");
}
}
BRecipe.numConfigRecipes = configRecipes.size();
@ -301,7 +304,7 @@ public class BConfig {
if (recipe != null) {
configRecipes.add(recipe);
} else {
p.errorLog("Loading the Cauldron-Recipe with id: '" + id + "' failed!");
breweryPlugin.errorLog("Loading the Cauldron-Recipe with id: '" + id + "' failed!");
}
}
BCauldronRecipe.numConfigRecipes = configRecipes.size();
@ -322,7 +325,7 @@ public class BConfig {
String[] drainSplit = drainString.split("/");
if (drainSplit.length > 1) {
Material mat = Material.matchMaterial(drainSplit[0]);
int strength = p.parseInt(drainSplit[1]);
int strength = breweryPlugin.parseInt(drainSplit[1]);
if (mat == null && hasVault && strength > 0) {
try {
net.milkbowl.vault.item.ItemInfo vaultItem = net.milkbowl.vault.item.Items.itemByString(drainSplit[0]);
@ -330,7 +333,7 @@ public class BConfig {
mat = vaultItem.getType();
}
} catch (Exception e) {
P.p.errorLog("Could not check vault for Item Name");
BreweryPlugin.getInstance().errorLog("Could not check vault for Item Name");
e.printStackTrace();
}
}
@ -357,7 +360,7 @@ public class BConfig {
DistortChat.doSigns = config.getBoolean("distortSignText", false);
// Register Sealing Table Recipe
if (P.use1_14) {
if (BreweryPlugin.use1_14) {
if (craftSealingTable && !BSealer.recipeRegistered) {
BSealer.registerRecipe();
} else if (!craftSealingTable && BSealer.recipeRegistered) {
@ -378,9 +381,9 @@ public class BConfig {
}
}
if (wg == null) {
P.p.errorLog("Failed loading WorldGuard Integration! Opening Barrels will NOT work!");
P.p.errorLog("Brewery was tested with version 5.8, 6.1 and 7.0 of WorldGuard!");
P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed loading WorldGuard Integration! Opening Barrels will NOT work!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 5.8, 6.1 and 7.0 of WorldGuard!");
BreweryPlugin.getInstance().errorLog("Disable the WorldGuard support in the config and do /brew reload");
}
}
if (useBlocklocker) {
@ -390,7 +393,7 @@ public class BConfig {
BlocklockerBarrel.registerBarrelAsProtectable();
} catch (ClassNotFoundException e) {
useBlocklocker = false;
P.p.log("Unsupported Version of 'BlockLocker', locking Brewery Barrels disabled");
BreweryPlugin.getInstance().log("Unsupported Version of 'BlockLocker', locking Brewery Barrels disabled");
}
}
@ -421,7 +424,7 @@ public class BConfig {
// The Config was reloaded, call Event
ConfigLoadEvent event = new ConfigLoadEvent();
P.p.getServer().getPluginManager().callEvent(event);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(event);
}

View File

@ -2,9 +2,7 @@ package com.dre.brewery.filedata;
import com.dre.brewery.*;
import com.dre.brewery.lore.Base91DecoderStream;
import com.dre.brewery.recipe.CustomItem;
import com.dre.brewery.recipe.Ingredient;
import com.dre.brewery.recipe.PluginItem;
import com.dre.brewery.recipe.SimpleItem;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.BoundingBox;
@ -22,7 +20,6 @@ import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class BData {
@ -32,7 +29,7 @@ public class BData {
// load all Data
public static void readData() {
File file = new File(P.p.getDataFolder(), "data.yml");
File file = new File(BreweryPlugin.getInstance().getDataFolder(), "data.yml");
if (file.exists()) {
long t1 = System.currentTimeMillis();
@ -40,17 +37,17 @@ public class BData {
long t2 = System.currentTimeMillis();
P.p.debugLog("Loading data.yml: " + (t2 - t1) + "ms");
BreweryPlugin.getInstance().debugLog("Loading data.yml: " + (t2 - t1) + "ms");
// Check if data is the newest version
String version = data.getString("Version", null);
if (version != null) {
if (!version.equals(DataSave.dataVersion)) {
P.p.log("Data File is being updated...");
File worldFile = new File(P.p.getDataFolder(), "worlddata.yml");
BreweryPlugin.getInstance().log("Data File is being updated...");
File worldFile = new File(BreweryPlugin.getInstance().getDataFolder(), "worlddata.yml");
new DataUpdater(data, file, worldFile).update(version);
data = YamlConfiguration.loadConfiguration(file);
P.p.log("Data Updated to version: " + DataSave.dataVersion);
BreweryPlugin.getInstance().log("Data Updated to version: " + DataSave.dataVersion);
}
}
@ -64,13 +61,13 @@ public class BData {
int hash = data.getInt("brewsCreatedH");
// Check the hash to prevent tampering with statistics
if (brewsCreated.hashCode() == hash) {
P.p.stats.brewsCreated = brewsCreated.get(0);
P.p.stats.brewsCreatedCmd = brewsCreated.get(1);
P.p.stats.exc = brewsCreated.get(2);
P.p.stats.good = brewsCreated.get(3);
P.p.stats.norm = brewsCreated.get(4);
P.p.stats.bad = brewsCreated.get(5);
P.p.stats.terr = brewsCreated.get(6);
BreweryPlugin.getInstance().stats.brewsCreated = brewsCreated.get(0);
BreweryPlugin.getInstance().stats.brewsCreatedCmd = brewsCreated.get(1);
BreweryPlugin.getInstance().stats.exc = brewsCreated.get(2);
BreweryPlugin.getInstance().stats.good = brewsCreated.get(3);
BreweryPlugin.getInstance().stats.norm = brewsCreated.get(4);
BreweryPlugin.getInstance().stats.bad = brewsCreated.get(5);
BreweryPlugin.getInstance().stats.terr = brewsCreated.get(6);
}
}
@ -88,7 +85,7 @@ public class BData {
List<Ingredient> ingredients = oldDeserializeIngredients(matSection);
ingMap.put(id, new BIngredients(ingredients, section.getInt(id + ".cookedTime", 0), true));
} else {
P.p.errorLog("Ingredient id: '" + id + "' incomplete in data.yml");
BreweryPlugin.getInstance().errorLog("Ingredient id: '" + id + "' incomplete in data.yml");
}
} else {
// New way of saving ingredients
@ -114,22 +111,22 @@ public class BData {
boolean stat = section.getBoolean(uid + ".stat", false);
int lastUpdate = section.getInt(uid + ".lastUpdate", 0);
Brew.loadLegacy(ingredients, P.p.parseInt(uid), quality, alc, distillRuns, ageTime, wood, recipe, unlabeled, persistent, stat, lastUpdate);
Brew.loadLegacy(ingredients, BreweryPlugin.getInstance().parseInt(uid), quality, alc, distillRuns, ageTime, wood, recipe, unlabeled, persistent, stat, lastUpdate);
}
}
// Store how many legacy brews were created
if (P.p.stats.brewsCreated <= 0) {
P.p.stats.brewsCreated = 0;
P.p.stats.brewsCreatedCmd = 0;
P.p.stats.exc = 0;
P.p.stats.good = 0;
P.p.stats.norm = 0;
P.p.stats.bad = 0;
P.p.stats.terr = 0;
if (BreweryPlugin.getInstance().stats.brewsCreated <= 0) {
BreweryPlugin.getInstance().stats.brewsCreated = 0;
BreweryPlugin.getInstance().stats.brewsCreatedCmd = 0;
BreweryPlugin.getInstance().stats.exc = 0;
BreweryPlugin.getInstance().stats.good = 0;
BreweryPlugin.getInstance().stats.norm = 0;
BreweryPlugin.getInstance().stats.bad = 0;
BreweryPlugin.getInstance().stats.terr = 0;
if (!Brew.noLegacy()) {
for (int i = Brew.legacyPotions.size(); i > 0; i--) {
P.p.stats.metricsForCreate(false);
BreweryPlugin.getInstance().stats.metricsForCreate(false);
}
}
}
@ -148,7 +145,7 @@ public class BData {
}
}
if (removed > 0) {
P.p.log("Removed " + removed + " Legacy Brews older than 3 months");
BreweryPlugin.getInstance().log("Removed " + removed + " Legacy Brews older than 3 months");
}
}
}
@ -161,11 +158,11 @@ public class BData {
try {
//noinspection ResultOfMethodCallIgnored
UUID.fromString(uuid);
if (!P.useUUID) {
if (!BreweryPlugin.useUUID) {
continue;
}
} catch (IllegalArgumentException e) {
if (P.useUUID) {
if (BreweryPlugin.useUUID) {
continue;
}
}
@ -179,15 +176,15 @@ public class BData {
}
final List<World> worlds = P.p.getServer().getWorlds();
final List<World> worlds = BreweryPlugin.getInstance().getServer().getWorlds();
if (BConfig.loadDataAsync) {
P.p.getServer().getScheduler().runTaskAsynchronously(P.p, () -> lwDataTask(worlds));
BreweryPlugin.getScheduler().runTaskAsynchronously(() -> lwDataTask(worlds));
} else {
lwDataTask(worlds);
}
} else {
P.p.log("No data.yml found, will create new one!");
BreweryPlugin.getInstance().log("No data.yml found, will create new one!");
}
}
@ -207,18 +204,18 @@ public class BData {
for (String mat : matSection.getKeys(false)) {
String[] matSplit = mat.split(",");
Material m = Material.getMaterial(matSplit[0]);
if (m == null && P.use1_13) {
if (m == null && BreweryPlugin.use1_13) {
if (matSplit[0].equals("LONG_GRASS")) {
m = Material.GRASS;
} else {
m = Material.matchMaterial(matSplit[0], true);
}
P.p.debugLog("converting Data Material from " + matSplit[0] + " to " + m);
BreweryPlugin.getInstance().debugLog("converting Data Material from " + matSplit[0] + " to " + m);
}
if (m == null) continue;
SimpleItem item;
if (matSplit.length == 2) {
item = new SimpleItem(m, (short) P.p.parseInt(matSplit[1]));
item = new SimpleItem(m, (short) BreweryPlugin.getInstance().parseInt(matSplit[1]));
} else {
item = new SimpleItem(m);
}
@ -235,7 +232,7 @@ public class BData {
return ingMap.get(id);
}
}
P.p.errorLog("Ingredient id: '" + id + "' not found in data.yml");
BreweryPlugin.getInstance().errorLog("Ingredient id: '" + id + "' not found in data.yml");
return new BIngredients();
}
@ -248,7 +245,7 @@ public class BData {
// matSection has all the materials + amount as Integers
return new BIngredients(oldDeserializeIngredients(section), 0);
} else {
P.p.errorLog("Cauldron is missing Ingredient Section");
BreweryPlugin.getInstance().errorLog("Cauldron is missing Ingredient Section");
return new BIngredients();
}
} else {
@ -273,7 +270,7 @@ public class BData {
} finally {
releaseDataLoadMutex();
if (BConfig.loadDataAsync && BData.dataMutex.get() == 0) {
P.p.log("Background data loading complete.");
BreweryPlugin.getInstance().log("Background data loading complete.");
}
}
}
@ -282,7 +279,7 @@ public class BData {
// can be run async
public static void loadWorldData(String uuid, World world) {
if (BData.worldData == null) {
File file = new File(P.p.getDataFolder(), "worlddata.yml");
File file = new File(BreweryPlugin.getInstance().getDataFolder(), "worlddata.yml");
if (file.exists()) {
long t1 = System.currentTimeMillis();
BData.worldData = YamlConfiguration.loadConfiguration(file);
@ -290,10 +287,10 @@ public class BData {
if (t2 - t1 > 15000) {
// Spigot is _very_ slow at loading inventories from yml. Paper is way faster.
// Notify Admin that loading Data took long (its async so not much of a problem)
P.p.log("Bukkit took " + (t2 - t1) / 1000.0 + "s to load Inventories from the World-Data File (in the Background),");
P.p.log("consider switching to Paper, or have less items in Barrels if it takes a long time for Barrels to become available");
BreweryPlugin.getInstance().log("Bukkit took " + (t2 - t1) / 1000.0 + "s to load Inventories from the World-Data File (in the Background),");
BreweryPlugin.getInstance().log("consider switching to Paper, or have less items in Barrels if it takes a long time for Barrels to become available");
} else {
P.p.debugLog("Loading worlddata.yml: " + (t2 - t1) + "ms");
BreweryPlugin.getInstance().debugLog("Loading worlddata.yml: " + (t2 - t1) + "ms");
}
} else {
return;
@ -311,16 +308,16 @@ public class BData {
String[] splitted = block.split("/");
if (splitted.length == 3) {
Block worldBlock = world.getBlockAt(P.p.parseInt(splitted[0]), P.p.parseInt(splitted[1]), P.p.parseInt(splitted[2]));
Block worldBlock = world.getBlockAt(BreweryPlugin.getInstance().parseInt(splitted[0]), BreweryPlugin.getInstance().parseInt(splitted[1]), BreweryPlugin.getInstance().parseInt(splitted[2]));
BIngredients ingredients = loadCauldronIng(section, cauldron + ".ingredients");
int state = section.getInt(cauldron + ".state", 0);
initCauldrons.put(worldBlock, new BCauldron(worldBlock, ingredients, state));
} else {
P.p.errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
BreweryPlugin.getInstance().errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
}
} else {
P.p.errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
BreweryPlugin.getInstance().errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + cauldron);
}
}
}
@ -339,7 +336,7 @@ public class BData {
// load itemStacks from invSection
ConfigurationSection invSection = section.getConfigurationSection(barrel + ".inv");
Block block = world.getBlockAt(P.p.parseInt(splitted[0]), P.p.parseInt(splitted[1]), P.p.parseInt(splitted[2]));
Block block = world.getBlockAt(BreweryPlugin.getInstance().parseInt(splitted[0]), BreweryPlugin.getInstance().parseInt(splitted[1]), BreweryPlugin.getInstance().parseInt(splitted[2]));
float time = (float) section.getDouble(barrel + ".time", 0.0);
byte sign = (byte) section.getInt(barrel + ".sign", 0);
@ -347,7 +344,7 @@ public class BData {
if (section.contains(barrel + ".bounds")) {
String[] bds = section.getString(barrel + ".bounds", "").split(",");
if (bds.length == 6) {
box = new BoundingBox(P.p.parseInt(bds[0]), P.p.parseInt(bds[1]), P.p.parseInt(bds[2]), P.p.parseInt(bds[3]), P.p.parseInt(bds[4]), P.p.parseInt(bds[5]));
box = new BoundingBox(BreweryPlugin.getInstance().parseInt(bds[0]), BreweryPlugin.getInstance().parseInt(bds[1]), BreweryPlugin.getInstance().parseInt(bds[2]), BreweryPlugin.getInstance().parseInt(bds[3]), BreweryPlugin.getInstance().parseInt(bds[4]), BreweryPlugin.getInstance().parseInt(bds[5]));
}
} else if (section.contains(barrel + ".st")) {
// Convert from Stair and Wood Locations to BoundingBox
@ -362,7 +359,7 @@ public class BData {
if (woLength > 1) {
System.arraycopy(wo, 0, points, st.length, woLength);
}
int[] locs = Arrays.stream(points).mapToInt(s -> P.p.parseInt(s)).toArray();
int[] locs = Arrays.stream(points).mapToInt(s -> BreweryPlugin.getInstance().parseInt(s)).toArray();
try {
box = BoundingBox.fromPoints(locs);
} catch (Exception e) {
@ -370,26 +367,29 @@ public class BData {
}
}
Barrel b;
if (invSection != null) {
b = new Barrel(block, sign, box, invSection.getValues(true), time, true);
} else {
// Barrel has no inventory
b = new Barrel(block, sign, box, null, time, true);
}
final BoundingBox bbox = box;
BreweryPlugin.getScheduler().runTask(block.getLocation(), () -> {
Barrel b;
if (invSection != null) {
b = new Barrel(block, sign, bbox, invSection.getValues(true), time, true);
} else {
// Barrel has no inventory
b = new Barrel(block, sign, bbox, null, time, true);
}
if (b.getBody().getBounds() != null) {
initBarrels.add(b);
} else {
// The Barrel Bounds need recreating, as they were missing or corrupt
initBadBarrels.add(b);
}
if (b.getBody().getBounds() != null) {
initBarrels.add(b);
} else {
// The Barrel Bounds need recreating, as they were missing or corrupt
initBadBarrels.add(b);
}
});
} else {
P.p.errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
BreweryPlugin.getInstance().errorLog("Incomplete Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
}
} else {
P.p.errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
BreweryPlugin.getInstance().errorLog("Missing Block-Data in data.yml: " + section.getCurrentPath() + "." + barrel);
}
}
}
@ -405,25 +405,25 @@ public class BData {
String[] splitted = loc.split("/");
if (splitted.length == 5) {
double x = P.p.parseDouble(splitted[0]);
double y = P.p.parseDouble(splitted[1]);
double z = P.p.parseDouble(splitted[2]);
float pitch = P.p.parseFloat(splitted[3]);
float yaw = P.p.parseFloat(splitted[4]);
double x = BreweryPlugin.getInstance().parseDouble(splitted[0]);
double y = BreweryPlugin.getInstance().parseDouble(splitted[1]);
double z = BreweryPlugin.getInstance().parseDouble(splitted[2]);
float pitch = BreweryPlugin.getInstance().parseFloat(splitted[3]);
float yaw = BreweryPlugin.getInstance().parseFloat(splitted[4]);
Location location = new Location(world, x, y, z, yaw, pitch);
initWakeups.add(new Wakeup(location));
} else {
P.p.errorLog("Incomplete Location-Data in data.yml: " + section.getCurrentPath() + "." + wakeup);
BreweryPlugin.getInstance().errorLog("Incomplete Location-Data in data.yml: " + section.getCurrentPath() + "." + wakeup);
}
}
}
}
// Merge Loaded Data in Main Thread
P.p.getServer().getScheduler().runTask(P.p, () -> {
if (P.p.getServer().getWorld(world.getUID()) == null) {
BreweryPlugin.getScheduler().runTask(() -> {
if (BreweryPlugin.getInstance().getServer().getWorld(world.getUID()) == null) {
return;
}
if (!initCauldrons.isEmpty()) {
@ -453,7 +453,7 @@ public class BData {
while (BData.dataMutex.updateAndGet(i -> i >= 0 ? i + 1 : i) <= 0) {
wait++;
if (!BConfig.loadDataAsync || wait > 60) {
P.p.errorLog("Could not load World Data, Mutex: " + BData.dataMutex.get());
BreweryPlugin.getInstance().errorLog("Could not load World Data, Mutex: " + BData.dataMutex.get());
return false;
}
try {

View File

@ -1,6 +1,6 @@
package com.dre.brewery.filedata;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.LegacyUtil;
import com.dre.brewery.utility.Tuple;
import org.bukkit.Material;
@ -196,7 +196,7 @@ public class ConfigUpdater {
}
if (fromVersion.equals("1.5") || fromVersion.equals("1.6")) {
update15(P.use1_13, de);
update15(BreweryPlugin.use1_13, de);
fromVersion = "1.7";
oldMat = false;
}
@ -261,13 +261,13 @@ public class ConfigUpdater {
fromVersion = "3.1";
}
if (P.use1_13 && oldMat) {
if (BreweryPlugin.use1_13 && oldMat) {
updateMaterials(true);
updateMaterialDescriptions(de);
}
if (!fromVersion.equals(BConfig.configVersion)) {
P.p.log(P.p.languageReader.get("Error_ConfigUpdate", fromVersion));
BreweryPlugin.getInstance().log(BreweryPlugin.getInstance().languageReader.get("Error_ConfigUpdate", fromVersion));
return;
}
saveConfig();
@ -300,7 +300,7 @@ public class ConfigUpdater {
int index = indexOfStart("language: en");
if (index != -1) {
setLine(index, "language: de");
P.p.language = "de";
BreweryPlugin.getInstance().language = "de";
}
// Add the new entries for the Word Distortion above the words section
@ -1266,7 +1266,7 @@ public class ConfigUpdater {
if (index != -1) {
addLines(index + 1, "# Das Minecraft Fass besteht aus Eiche");
}
if (P.use1_13) updateMaterialDescriptions(true);
if (BreweryPlugin.use1_13) updateMaterialDescriptions(true);
}
// Update en from 1.7 to 1.8
@ -1317,7 +1317,7 @@ public class ConfigUpdater {
if (index != -1) {
addLines(index + 1, "# The Minecraft barrel is made of oak");
}
if (P.use1_13) updateMaterialDescriptions(false);
if (BreweryPlugin.use1_13) updateMaterialDescriptions(false);
}
private void update18de(FileConfiguration yml) {
@ -1359,7 +1359,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT1%%%%");
if (index != -1) {
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
setLine(index, " material: Barrier");
} else {
setLine(index, " material: BEDROCK");
@ -1368,7 +1368,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT2%%%%");
if (index != -1) {
removeLine(index);
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
addLines(index, " material:",
" - Acacia_Door",
" - Oak_Door",
@ -1460,7 +1460,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT1%%%%");
if (index != -1) {
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
setLine(index, " material: Barrier");
} else {
setLine(index, " material: BEDROCK");
@ -1469,7 +1469,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT2%%%%");
if (index != -1) {
removeLine(index);
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
addLines(index, " material:",
" - Acacia_Door",
" - Oak_Door",
@ -1561,7 +1561,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT1%%%%");
if (index != -1) {
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
setLine(index, " material: Barrier");
} else {
setLine(index, " material: BEDROCK");
@ -1570,7 +1570,7 @@ public class ConfigUpdater {
index = indexOfStart("%%%%MAT2%%%%");
if (index != -1) {
removeLine(index);
if (P.use1_13) {
if (BreweryPlugin.use1_13) {
addLines(index, " material:",
" - Acacia_Door",
" - Oak_Door",
@ -2057,7 +2057,7 @@ public class ConfigUpdater {
public void applyPatch(String resourcePath, int toLine) {
try {
List<String> patch = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(P.p.getResource(resourcePath), "Resource not found")));
BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(BreweryPlugin.getInstance().getResource(resourcePath), "Resource not found")));
String currentLine;
while((currentLine = reader.readLine()) != null) {
patch.add(currentLine);
@ -2065,7 +2065,7 @@ public class ConfigUpdater {
reader.close();
config.addAll(toLine, patch);
} catch (IOException | NullPointerException e) {
P.p.errorLog("Could not apply Patch: " + resourcePath);
BreweryPlugin.getInstance().errorLog("Could not apply Patch: " + resourcePath);
e.printStackTrace();
}
}
@ -2185,11 +2185,11 @@ public class ConfigUpdater {
private String convertIdtoMaterial(String line, String regexPrefix, String regexPostfix) {
String idString = line.replaceFirst(regexPrefix, "").replaceFirst(regexPostfix, "");
int id = P.p.parseInt(idString);
int id = BreweryPlugin.getInstance().parseInt(idString);
if (id > 0) {
Material material = LegacyUtil.getMaterial(id);
if (material == null) {
P.p.errorLog("Could not find Material with id: " + line);
BreweryPlugin.getInstance().errorLog("Could not find Material with id: " + line);
return line;
} else {
return line.replaceAll(idString, material.name());

View File

@ -3,17 +3,17 @@ package com.dre.brewery.filedata;
import com.dre.brewery.*;
import com.dre.brewery.utility.BUtil;
import com.github.Anon8281.universalScheduler.UniversalRunnable;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class DataSave extends BukkitRunnable {
public class DataSave extends UniversalRunnable {
public static int lastBackup = 0;
public static int lastSave = 1;
@ -31,7 +31,7 @@ public class DataSave extends BukkitRunnable {
public DataSave(ReadOldData read) {
this.read = read;
time = System.currentTimeMillis();
loadedWorlds = P.p.getServer().getWorlds();
loadedWorlds = BreweryPlugin.getInstance().getServer().getWorlds();
}
@ -46,7 +46,7 @@ public class DataSave extends BukkitRunnable {
if (!read.done) {
// Wait for async thread to load old data
if (System.currentTimeMillis() - time > 50000) {
P.p.errorLog("Old Data took too long to load! Mutex: " + BData.dataMutex.get());
BreweryPlugin.getInstance().errorLog("Old Data took too long to load! Mutex: " + BData.dataMutex.get());
try {
cancel();
read.cancel();
@ -76,13 +76,13 @@ public class DataSave extends BukkitRunnable {
Brew.writePrevSeeds(data);
List<Integer> brewsCreated = new ArrayList<>(7);
brewsCreated.add(P.p.stats.brewsCreated);
brewsCreated.add(P.p.stats.brewsCreatedCmd);
brewsCreated.add(P.p.stats.exc);
brewsCreated.add(P.p.stats.good);
brewsCreated.add(P.p.stats.norm);
brewsCreated.add(P.p.stats.bad);
brewsCreated.add(P.p.stats.terr);
brewsCreated.add(BreweryPlugin.getInstance().stats.brewsCreated);
brewsCreated.add(BreweryPlugin.getInstance().stats.brewsCreatedCmd);
brewsCreated.add(BreweryPlugin.getInstance().stats.exc);
brewsCreated.add(BreweryPlugin.getInstance().stats.good);
brewsCreated.add(BreweryPlugin.getInstance().stats.norm);
brewsCreated.add(BreweryPlugin.getInstance().stats.bad);
brewsCreated.add(BreweryPlugin.getInstance().stats.terr);
data.set("brewsCreated", brewsCreated);
data.set("brewsCreatedH", brewsCreated.hashCode());
@ -126,10 +126,10 @@ public class DataSave extends BukkitRunnable {
unloadingWorlds.clear();
}
P.p.debugLog("saving: " + ((System.nanoTime() - saveTime) / 1000000.0) + "ms");
BreweryPlugin.getInstance().debugLog("saving: " + ((System.nanoTime() - saveTime) / 1000000.0) + "ms");
if (P.p.isEnabled()) {
P.p.getServer().getScheduler().runTaskAsynchronously(P.p, new WriteData(data, worldData));
if (BreweryPlugin.getInstance().isEnabled()) {
BreweryPlugin.getScheduler().runTaskAsynchronously(new WriteData(data, worldData));
} else {
new WriteData(data, worldData).run();
}
@ -173,7 +173,7 @@ public class DataSave extends BukkitRunnable {
// Save all data. Takes a boolean whether all data should be collected in instantly
public static void save(boolean collectInstant) {
if (running != null) {
P.p.log("Another Save was started while a Save was in Progress");
BreweryPlugin.getInstance().log("Another Save was started while a Save was in Progress");
if (collectInstant) {
running.now();
}
@ -186,9 +186,9 @@ public class DataSave extends BukkitRunnable {
running = new DataSave(read);
running.run();
} else {
read.runTaskAsynchronously(P.p);
read.runTaskAsynchronously(BreweryPlugin.getInstance());
running = new DataSave(read);
running.runTaskTimer(P.p, 1, 2);
running.runTaskTimer(BreweryPlugin.getInstance(), 1, 2);
}
}

View File

@ -1,7 +1,7 @@
package com.dre.brewery.filedata;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.LegacyUtil;
import com.dre.brewery.P;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
@ -60,20 +60,20 @@ public class DataUpdater {
Map<String, Integer> ingredients = new HashMap<>();
for (String ingredient : matSection.getKeys(false)) {
// convert to Material
Material mat = LegacyUtil.getMaterial(P.p.parseInt(ingredient));
Material mat = LegacyUtil.getMaterial(BreweryPlugin.getInstance().parseInt(ingredient));
if (mat != null) {
ingredients.put(mat.name(), matSection.getInt(ingredient));
}
}
section.set(id + ".mats", ingredients);
} else {
P.p.errorLog("Ingredient id: '" + id + "' incomplete in data.yml");
BreweryPlugin.getInstance().errorLog("Ingredient id: '" + id + "' incomplete in data.yml");
}
}
}
} catch (Exception e) {
// Getting Material by id may not work in the future
P.p.errorLog("Error Converting Ingredient Section of the Data File, newer versions of Bukkit may not support the old Save File anymore:");
BreweryPlugin.getInstance().errorLog("Error Converting Ingredient Section of the Data File, newer versions of Bukkit may not support the old Save File anymore:");
e.printStackTrace();
}
@ -90,21 +90,21 @@ public class DataUpdater {
Map<String, Integer> ingredients = new HashMap<>();
for (String ingredient : ingredientSection.getKeys(false)) {
// convert to Material
Material mat = LegacyUtil.getMaterial(P.p.parseInt(ingredient));
Material mat = LegacyUtil.getMaterial(BreweryPlugin.getInstance().parseInt(ingredient));
if (mat != null) {
ingredients.put(mat.name(), ingredientSection.getInt(ingredient));
}
}
cauldrons.set(id + ".ingredients", ingredients);
} else {
P.p.errorLog("BCauldron " + id + " is missing Ingredient Section");
BreweryPlugin.getInstance().errorLog("BCauldron " + id + " is missing Ingredient Section");
}
}
}
}
} catch (Exception e) {
// Getting Material by id may not work in the future
P.p.errorLog("Error Converting Ingredient Section of Cauldrons, newer versions of Bukkit may not support the old Save File anymore:");
BreweryPlugin.getInstance().errorLog("Error Converting Ingredient Section of Cauldrons, newer versions of Bukkit may not support the old Save File anymore:");
e.printStackTrace();
}
}
@ -133,9 +133,9 @@ public class DataUpdater {
try {
worldData.save(worldFile);
File bkup = new File(P.p.getDataFolder(), "dataBackup.yml");
File bkup = new File(BreweryPlugin.getInstance().getDataFolder(), "dataBackup.yml");
if (bkup.exists()) {
bkup.renameTo(new File(P.p.getDataFolder(), "worlddataBackup.yml"));
bkup.renameTo(new File(BreweryPlugin.getInstance().getDataFolder(), "worlddataBackup.yml"));
}
} catch (IOException e) {
e.printStackTrace();

View File

@ -1,6 +1,6 @@
package com.dre.brewery.filedata;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
@ -39,7 +39,7 @@ public class LanguageReader {
FileConfiguration defaults = null;
ConfigUpdater updater = null;
String line;
InputStream resource = P.p.getResource(defaultPath);
InputStream resource = BreweryPlugin.getInstance().getResource(defaultPath);
if (resource == null) return;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) {
while ((line = reader.readLine()) != null) {
@ -49,7 +49,7 @@ public class LanguageReader {
if (!entries.containsKey(key)) {
if (defaults == null) {
defaults = new YamlConfiguration();
defaults.load(new BufferedReader(new InputStreamReader(Objects.requireNonNull(P.p.getResource(defaultPath)))));
defaults.load(new BufferedReader(new InputStreamReader(Objects.requireNonNull(BreweryPlugin.getInstance().getResource(defaultPath)))));
updater = new ConfigUpdater(file);
updater.appendLines("", "# Updated");
}
@ -61,11 +61,11 @@ public class LanguageReader {
if (updater != null) {
createBackup();
updater.saveConfig();
P.p.log("Language file updated");
BreweryPlugin.getInstance().log("Language file updated");
}
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
P.p.errorLog("Language File could not be updated");
BreweryPlugin.getInstance().errorLog("Language File could not be updated");
}
}

View File

@ -1,15 +1,14 @@
package com.dre.brewery.filedata;
import java.io.File;
import com.dre.brewery.BreweryPlugin;
import com.github.Anon8281.universalScheduler.UniversalRunnable;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import com.dre.brewery.P;
import java.io.File;
public class ReadOldData extends BukkitRunnable {
public class ReadOldData extends UniversalRunnable {
public FileConfiguration data;
public boolean done = false;
@ -21,7 +20,7 @@ public class ReadOldData extends BukkitRunnable {
// Set the Data Mutex to -1 if it is 0=Free
while (!BData.dataMutex.compareAndSet(0, -1)) {
if (wait > 300) {
P.p.errorLog("Loading Process active for too long while trying to save! Mutex: " + BData.dataMutex.get());
BreweryPlugin.getInstance().errorLog("Loading Process active for too long while trying to save! Mutex: " + BData.dataMutex.get());
return;
}
wait++;
@ -33,7 +32,7 @@ public class ReadOldData extends BukkitRunnable {
}
File worldDataFile = new File(P.p.getDataFolder(), "worlddata.yml");
File worldDataFile = new File(BreweryPlugin.getInstance().getDataFolder(), "worlddata.yml");
if (BData.worldData == null) {
if (!worldDataFile.exists()) {
data = new YamlConfiguration();
@ -47,7 +46,7 @@ public class ReadOldData extends BukkitRunnable {
}
if (DataSave.lastBackup > 10) {
worldDataFile.renameTo(new File(P.p.getDataFolder(), "worlddataBackup.yml"));
worldDataFile.renameTo(new File(BreweryPlugin.getInstance().getDataFolder(), "worlddataBackup.yml"));
DataSave.lastBackup = 0;
} else {
DataSave.lastBackup++;

View File

@ -1,136 +1,62 @@
package com.dre.brewery.filedata;
import com.dre.brewery.P;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.logging.Level;
/**
* Update Checker modified from the Gravity Update Checker Example:
* https://github.com/gravitylow/ServerModsAPI-Example/blob/master/Update.java
* Update Checker modified for BreweryX
*/
public class UpdateChecker implements Runnable {
// The project's unique ID
private static final int projectID = 68006;
public class UpdateChecker {
// Used for locating version numbers in file names
private static final String DELIMETER = "^v|[\\s_-]v";
private final static BreweryPlugin plugin = BreweryPlugin.getInstance();
private final int resourceID;
private static String latestVersion = plugin.getDescription().getVersion();
private static boolean updateAvailable = false;
// Keys for extracting file information from JSON response
private static final String API_NAME_VALUE = "name";
/* private static final String API_LINK_VALUE = "downloadUrl";
private static final String API_RELEASE_TYPE_VALUE = "releaseType";
private static final String API_FILE_NAME_VALUE = "fileName";
private static final String API_GAME_VERSION_VALUE = "gameVersion";*/
// Static information for querying the API
private static final String API_QUERY = "/servermods/files?projectIds=";
private static final String API_HOST = "https://api.curseforge.com";
public static String update = null;
public static void notify(final Player player) {
if (update == null || !player.isOp()) {
return;
}
P.p.msg(player, update);
public UpdateChecker(int resourceID) {
this.resourceID = resourceID;
}
@Override
public void run() {
query();
public static void notify(final Player player) {
if (!updateAvailable || !player.hasPermission("brewery.update")) {
return;
}
plugin.msg(player, plugin.languageReader.get("Etc_UpdateAvailable", "v"+plugin.getDescription().getVersion(), "v"+latestVersion));
}
/**
* Query the API to find the latest approved file's details.
*/
public void query() {
URL url;
try {
// Create the URL to query using the project's ID
url = new URL(API_HOST + API_QUERY + projectID);
} catch (MalformedURLException e) {
// There was an error creating the URL
e.printStackTrace();
return;
}
try {
// Open a connection and query the project
URLConnection conn = url.openConnection();
/*if (apiKey != null) {
// Add the API key to the request if present
conn.addRequestProperty("X-API-Key", apiKey);
}*/
// Add the user-agent to identify the program
conn.addRequestProperty("User-Agent", "Brewery UpdateChecker (by Gravity)");
// Read the response of the query
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// Parse the array of files from the query's response
JsonArray array = JsonParser.parseReader(reader).getAsJsonArray();
if (array.size() > 0) {
// Get the newest file's details
JsonObject latest = array.get(array.size() - 1).getAsJsonObject();
// Get the version's title
String versionName = latest.get(API_NAME_VALUE).getAsString();
/*// Get the version's link
String versionLink = (String) latest.get(API_LINK_VALUE);
// Get the version's release type
String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);
// Get the version's file name
String versionFileName = (String) latest.get(API_FILE_NAME_VALUE);
// Get the version's game version
String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);*/
String[] split = versionName.split(DELIMETER);
if (split.length < 2) {
P.p.log("Malformed Remote File Name, could not check for updates");
} else {
String version = split[1];
if (!P.p.getDescription().getVersion().equals(split[1].split(" ")[0])) {
String[] verNew = version.split("\\.");
String[] verOld = P.p.getDescription().getVersion().split("\\.");
for (int i = 0; i < verNew.length; i++) {
if (i < verOld.length && P.p.parseInt(verOld[i]) > P.p.parseInt(verNew[i])) {
break;
} else if (i >= verOld.length || P.p.parseInt(verOld[i]) < P.p.parseInt(verNew[i])) {
P.p.log("Update available for Brewery-" + P.p.getDescription().getVersion() + ": " + versionName);
update = "Update available: v" + version;
break;
}
}
}
public void query(final Consumer<String> consumer) {
BreweryPlugin.getScheduler().runTaskAsynchronously(() -> {
try (InputStream is = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + resourceID + "/~").openStream(); Scanner scann = new Scanner(is)) {
if (scann.hasNext()) {
consumer.accept(scann.next());
}
} else {
P.p.log("There are no files for this project");
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Cannot look for updates: " + e);
}
} catch (IOException e) {
// There was an error reading the query
P.p.errorLog("Could not check for Updates. This error can probably be ignored");
e.printStackTrace();
}
});
}
public static void setLatestVersion(String version) {
latestVersion = version;
}
public static String getLatestVersion() {
return latestVersion;
}
public static void setUpdateAvailable(boolean available) {
updateAvailable = available;
}
}

View File

@ -3,10 +3,9 @@ package com.dre.brewery.filedata;
import java.io.File;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.configuration.file.FileConfiguration;
import com.dre.brewery.P;
/**
* Writes the collected Data to file in Async Thread
*/
@ -22,8 +21,8 @@ public class WriteData implements Runnable {
@Override
public void run() {
File datafile = new File(P.p.getDataFolder(), "data.yml");
File worlddatafile = new File(P.p.getDataFolder(), "worlddata.yml");
File datafile = new File(BreweryPlugin.getInstance().getDataFolder(), "data.yml");
File worlddatafile = new File(BreweryPlugin.getInstance().getDataFolder(), "worlddata.yml");
try {
data.save(datafile);

View File

@ -2,7 +2,7 @@ package com.dre.brewery.integration;
import com.Acrobot.ChestShop.Events.ShopCreatedEvent;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import org.bukkit.Material;
import org.bukkit.block.Container;
@ -22,7 +22,7 @@ public class ChestShopListener implements Listener {
if (item != null && item.getType() == Material.POTION) {
Brew brew = Brew.get(item);
if (brew != null && !brew.isSealed()) {
event.getPlayer().sendTitle("", P.p.color(P.p.languageReader.get("Player_ShopSealBrew")), 10, 70, 20);
event.getPlayer().sendTitle("", BreweryPlugin.getInstance().color(BreweryPlugin.getInstance().languageReader.get("Player_ShopSealBrew")), 10, 70, 20);
return;
}
}
@ -32,7 +32,7 @@ public class ChestShopListener implements Listener {
HandlerList.unregisterAll(this);
BConfig.hasChestShop = false;
e.printStackTrace();
P.p.errorLog("Failed to notify Player using ChestShop. Disabling ChestShop support");
BreweryPlugin.getInstance().errorLog("Failed to notify Player using ChestShop. Disabling ChestShop support");
}
}
}

View File

@ -1,7 +1,7 @@
package com.dre.brewery.integration;
import com.dre.brewery.Barrel;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelAccessEvent;
import com.dre.brewery.api.events.barrel.BarrelDestroyEvent;
import com.dre.brewery.api.events.barrel.BarrelRemoveEvent;
@ -36,25 +36,25 @@ public class IntegrationListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBarrelAccessLowest(BarrelAccessEvent event) {
if (BConfig.useWG) {
Plugin plugin = P.p.getServer().getPluginManager().getPlugin("WorldGuard");
Plugin plugin = BreweryPlugin.getInstance().getServer().getPluginManager().getPlugin("WorldGuard");
if (plugin != null) {
try {
if (!BConfig.wg.checkAccess(event.getPlayer(), event.getSpigot(), plugin)) {
event.setCancelled(true);
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check WorldGuard for Barrel Open Permissions!");
P.p.errorLog("Brewery was tested with version 5.8, 6.1 to 7.0 of WorldGuard!");
P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check WorldGuard for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 5.8, 6.1 to 7.0 of WorldGuard!");
BreweryPlugin.getInstance().errorLog("Disable the WorldGuard support in the config and do /brew reload");
e.printStackTrace();
Player player = event.getPlayer();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cWorldGuard check Error, Brewery was tested with up to v7.0 of Worldguard");
P.p.msg(player, "&cSet &7useWorldGuard: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cWorldGuard check Error, Brewery was tested with up to v7.0 of Worldguard");
BreweryPlugin.getInstance().msg(player, "&cSet &7useWorldGuard: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
}
}
@ -64,7 +64,7 @@ public class IntegrationListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBarrelAccess(BarrelAccessEvent event) {
if (BConfig.useGMInventories) {
Plugin pl = P.p.getServer().getPluginManager().getPlugin("GameModeInventories");
Plugin pl = BreweryPlugin.getInstance().getServer().getPluginManager().getPlugin("GameModeInventories");
if (pl != null && pl.isEnabled()) {
try {
if (pl.getConfig().getBoolean("restrict_creative")) {
@ -73,15 +73,15 @@ public class IntegrationListener implements Listener {
if (!pl.getConfig().getBoolean("bypass.inventories") || (!player.hasPermission("gamemodeinventories.bypass") && !player.isOp())) {
event.setCancelled(true);
if (!pl.getConfig().getBoolean("dont_spam_chat")) {
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
}
return;
}
}
}
} catch (Throwable e) {
P.p.errorLog("Failed to Check GameModeInventories for Barrel Open Permissions!");
P.p.errorLog("Players will be able to open Barrel with GameMode Creative");
BreweryPlugin.getInstance().errorLog("Failed to Check GameModeInventories for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Players will be able to open Barrel with GameMode Creative");
e.printStackTrace();
BConfig.useGMInventories = false;
}
@ -90,25 +90,25 @@ public class IntegrationListener implements Listener {
}
}
if (BConfig.useGP) {
if (P.p.getServer().getPluginManager().isPluginEnabled("GriefPrevention")) {
if (BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("GriefPrevention")) {
try {
if (!GriefPreventionBarrel.checkAccess(event)) {
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
event.setCancelled(true);
return;
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check GriefPrevention for Barrel Open Permissions!");
P.p.errorLog("Brewery was tested with GriefPrevention v14.5 - v16.9");
P.p.errorLog("Disable the GriefPrevention support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check GriefPrevention for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with GriefPrevention v14.5 - v16.9");
BreweryPlugin.getInstance().errorLog("Disable the GriefPrevention support in the config and do /brew reload");
e.printStackTrace();
Player player = event.getPlayer();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cGriefPrevention check Error, Brewery was tested with up to v16.9 of GriefPrevention");
P.p.msg(player, "&cSet &7useGriefPrevention: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cGriefPrevention check Error, Brewery was tested with up to v16.9 of GriefPrevention");
BreweryPlugin.getInstance().msg(player, "&cSet &7useGriefPrevention: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
return;
}
@ -116,7 +116,7 @@ public class IntegrationListener implements Listener {
}
if (BConfig.useLWC) {
Plugin plugin = P.p.getServer().getPluginManager().getPlugin("LWC");
Plugin plugin = BreweryPlugin.getInstance().getServer().getPluginManager().getPlugin("LWC");
if (plugin != null) {
// If the Clicked Block was the Sign, LWC already knows and we dont need to do anything here
@ -127,21 +127,21 @@ public class IntegrationListener implements Listener {
Player player = event.getPlayer();
try {
if (!LWCBarrel.checkAccess(player, sign, plugin)) {
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
event.setCancelled(true);
return;
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check LWC for Barrel Open Permissions!");
P.p.errorLog("Brewery was tested with version 4.5.0 of LWC!");
P.p.errorLog("Disable the LWC support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check LWC for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 4.5.0 of LWC!");
BreweryPlugin.getInstance().errorLog("Disable the LWC support in the config and do /brew reload");
e.printStackTrace();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cLWC check Error, Brewery was tested with up to v4.5.0 of LWC");
P.p.msg(player, "&cSet &7useLWC: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cLWC check Error, Brewery was tested with up to v4.5.0 of LWC");
BreweryPlugin.getInstance().msg(player, "&cSet &7useLWC: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
return;
}
@ -151,25 +151,25 @@ public class IntegrationListener implements Listener {
}
if (BConfig.useTowny) {
if (P.p.getServer().getPluginManager().isPluginEnabled("Towny")) {
if (BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("Towny")) {
try {
if (!TownyBarrel.checkAccess(event)) {
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
event.setCancelled(true);
return;
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check Towny for Barrel Open Permissions!");
P.p.errorLog("Brewery was tested with Towny v0.96.3.0");
P.p.errorLog("Disable the Towny support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check Towny for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with Towny v0.96.3.0");
BreweryPlugin.getInstance().errorLog("Disable the Towny support in the config and do /brew reload");
e.printStackTrace();
Player player = event.getPlayer();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cTowny check Error, Brewery was tested with up to v0.96.3.0 of Towny");
P.p.msg(player, "&cSet &7useTowny: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cTowny check Error, Brewery was tested with up to v0.96.3.0 of Towny");
BreweryPlugin.getInstance().msg(player, "&cSet &7useTowny: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
return;
}
@ -177,25 +177,25 @@ public class IntegrationListener implements Listener {
}
if (BConfig.useBlocklocker) {
if (P.p.getServer().getPluginManager().isPluginEnabled("BlockLocker")) {
if (BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("BlockLocker")) {
try {
if (!BlocklockerBarrel.checkAccess(event)) {
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
event.setCancelled(true);
return;
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check BlockLocker for Barrel Open Permissions!");
P.p.errorLog("Brewery was tested with BlockLocker v1.9");
P.p.errorLog("Disable the BlockLocker support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check BlockLocker for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with BlockLocker v1.9");
BreweryPlugin.getInstance().errorLog("Disable the BlockLocker support in the config and do /brew reload");
e.printStackTrace();
Player player = event.getPlayer();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cBlockLocker check Error, Brewery was tested with v1.9 of BlockLocker");
P.p.msg(player, "&cSet &7useBlockLocker: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cBlockLocker check Error, Brewery was tested with v1.9 of BlockLocker");
BreweryPlugin.getInstance().msg(player, "&cSet &7useBlockLocker: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
return;
}
@ -216,16 +216,16 @@ public class IntegrationListener implements Listener {
EquipmentSlot.HAND);
try {
P.p.getServer().getPluginManager().callEvent(simulatedEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(simulatedEvent);
} catch (Throwable e) {
P.p.errorLog("Failed to simulate a Chest for Barrel Open Permissions!");
P.p.errorLog("Disable useVirtualChestPerms in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to simulate a Chest for Barrel Open Permissions!");
BreweryPlugin.getInstance().errorLog("Disable useVirtualChestPerms in the config and do /brew reload");
e.printStackTrace();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cVirtual Chest Error");
P.p.msg(player, "&cSet &7useVirtualChestPerms: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cVirtual Chest Error");
BreweryPlugin.getInstance().msg(player, "&cSet &7useVirtualChestPerms: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError opening Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError opening Barrel, please report to an Admin!");
}
} finally {
event.getClickedBlock().setType(Material.AIR, false);
@ -234,7 +234,7 @@ public class IntegrationListener implements Listener {
if (simulatedEvent.useInteractedBlock() == Event.Result.DENY) {
event.setCancelled(true);
P.p.msg(event.getPlayer(), P.p.languageReader.get("Error_NoBarrelAccess"));
BreweryPlugin.getInstance().msg(event.getPlayer(), BreweryPlugin.getInstance().languageReader.get("Error_NoBarrelAccess"));
//return;
}
}
@ -253,15 +253,15 @@ public class IntegrationListener implements Listener {
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check LWC for Barrel Break Permissions!");
P.p.errorLog("Brewery was tested with version 4.5.0 of LWC!");
P.p.errorLog("Disable the LWC support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check LWC for Barrel Break Permissions!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 4.5.0 of LWC!");
BreweryPlugin.getInstance().errorLog("Disable the LWC support in the config and do /brew reload");
e.printStackTrace();
if (player.hasPermission("brewery.admin") || player.hasPermission("brewery.mod")) {
P.p.msg(player, "&cLWC check Error, Brewery was tested with up to v4.5.0 of LWC");
P.p.msg(player, "&cSet &7useLWC: false &cin the config and /brew reload");
BreweryPlugin.getInstance().msg(player, "&cLWC check Error, Brewery was tested with up to v4.5.0 of LWC");
BreweryPlugin.getInstance().msg(player, "&cSet &7useLWC: false &cin the config and /brew reload");
} else {
P.p.msg(player, "&cError breaking Barrel, please report to an Admin!");
BreweryPlugin.getInstance().msg(player, "&cError breaking Barrel, please report to an Admin!");
}
}
} else {
@ -277,9 +277,9 @@ public class IntegrationListener implements Listener {
}
} catch (Throwable e) {
event.setCancelled(true);
P.p.errorLog("Failed to Check LWC on Barrel Destruction!");
P.p.errorLog("Brewery was tested with version 4.5.0 of LWC!");
P.p.errorLog("Disable the LWC support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Check LWC on Barrel Destruction!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 4.5.0 of LWC!");
BreweryPlugin.getInstance().errorLog("Disable the LWC support in the config and do /brew reload");
e.printStackTrace();
}
}
@ -292,8 +292,8 @@ public class IntegrationListener implements Listener {
try {
LWCBarrel.remove(event.getBarrel());
} catch (Throwable e) {
P.p.errorLog("Failed to Remove LWC Lock from Barrel!");
P.p.errorLog("Brewery was tested with version 4.5.0 of LWC!");
BreweryPlugin.getInstance().errorLog("Failed to Remove LWC Lock from Barrel!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 4.5.0 of LWC!");
e.printStackTrace();
}
}
@ -305,8 +305,8 @@ public class IntegrationListener implements Listener {
try {
LogBlockBarrel.closeBarrel(event.getPlayer(), event.getInventory());
} catch (Exception e) {
P.p.errorLog("Failed to Log Barrel to LogBlock!");
P.p.errorLog("Brewery was tested with version 1.94 of LogBlock!");
BreweryPlugin.getInstance().errorLog("Failed to Log Barrel to LogBlock!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 1.94 of LogBlock!");
e.printStackTrace();
}
}
@ -316,10 +316,10 @@ public class IntegrationListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
// Catch the Interact Event early, so MMOItems does not act before us and cancel the event while we try to add it to the Cauldron
if (!P.use1_9) return;
if (!BreweryPlugin.use1_9) return;
if (BConfig.hasMMOItems == null) {
BConfig.hasMMOItems = P.p.getServer().getPluginManager().isPluginEnabled("MMOItems")
&& P.p.getServer().getPluginManager().isPluginEnabled("MythicLib");
BConfig.hasMMOItems = BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("MMOItems")
&& BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("MythicLib");
}
if (!BConfig.hasMMOItems) return;
try {
@ -332,7 +332,7 @@ public class IntegrationListener implements Listener {
MMOItemsPluginItem mmo = ((MMOItemsPluginItem) rItem);
if (mmo.matches(event.getItem())) {
event.setCancelled(true);
P.p.playerListener.onPlayerInteract(event);
BreweryPlugin.getInstance().playerListener.onPlayerInteract(event);
return;
}
}
@ -341,7 +341,7 @@ public class IntegrationListener implements Listener {
}
}
} catch (Throwable e) {
P.p.errorLog("Could not check MMOItems for Item");
BreweryPlugin.getInstance().errorLog("Could not check MMOItems for Item");
e.printStackTrace();
BConfig.hasMMOItems = false;
}

View File

@ -1,7 +1,7 @@
package com.dre.brewery.integration;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import com.nisovin.shopkeepers.api.events.PlayerOpenUIEvent;
import com.nisovin.shopkeepers.api.ui.DefaultUITypes;
@ -45,7 +45,7 @@ public class ShopKeepersListener implements Listener {
if (item != null && item.getType() == Material.POTION && event.getClickedInventory() == event.getView().getTopInventory()) {
Brew brew = Brew.get(item);
if (brew != null && !brew.isSealed()) {
P.p.msg(event.getWhoClicked(), P.p.languageReader.get("Player_ShopSealBrew"));
BreweryPlugin.getInstance().msg(event.getWhoClicked(), BreweryPlugin.getInstance().languageReader.get("Player_ShopSealBrew"));
}
}
}
@ -60,7 +60,7 @@ public class ShopKeepersListener implements Listener {
HandlerList.unregisterAll(this);
BConfig.hasShopKeepers = false;
e.printStackTrace();
P.p.errorLog("Failed to notify Player using 'ShopKeepers'. Disabling 'ShopKeepers' support");
BreweryPlugin.getInstance().errorLog("Failed to notify Player using 'ShopKeepers'. Disabling 'ShopKeepers' support");
openedEditors.clear();
}

View File

@ -1,24 +1,16 @@
package com.dre.brewery.integration;
import com.Acrobot.ChestShop.Events.ShopCreatedEvent;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.integration.item.SlimefunPluginItem;
import com.dre.brewery.recipe.BCauldronRecipe;
import com.dre.brewery.recipe.RecipeItem;
import com.dre.brewery.utility.LegacyUtil;
import io.github.thebusybiscuit.slimefun4.api.events.PlayerRightClickEvent;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Container;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.util.Optional;
@ -39,7 +31,7 @@ public class SlimefunListener implements Listener {
if (rItem instanceof SlimefunPluginItem) {
if (slimefunItem.get().getId().equalsIgnoreCase(((SlimefunPluginItem) rItem).getItemId())) {
event.cancel();
P.p.playerListener.onPlayerInteract(event.getInteractEvent());
BreweryPlugin.getInstance().playerListener.onPlayerInteract(event.getInteractEvent());
return;
}
}
@ -49,7 +41,7 @@ public class SlimefunListener implements Listener {
}
} catch (Throwable e) {
HandlerList.unregisterAll(this);
P.p.errorLog("Slimefun check failed");
BreweryPlugin.getInstance().errorLog("Slimefun check failed");
e.printStackTrace();
}
}

View File

@ -2,7 +2,7 @@ package com.dre.brewery.integration.barrel;
import com.dre.brewery.Barrel;
import com.dre.brewery.BarrelBody;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelAccessEvent;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.utility.LegacyUtil;
@ -30,7 +30,7 @@ public class BlocklockerBarrel implements ProtectableBlocksSettings {
}
public boolean isOrWillCreateBarrel(Block block) {
if (!P.p.isEnabled() || !BConfig.useBlocklocker) {
if (!BreweryPlugin.getInstance().isEnabled() || !BConfig.useBlocklocker) {
return false;
}
if (!LegacyUtil.isWoodPlanks(block.getType()) && !LegacyUtil.isWoodStairs(block.getType())) {

View File

@ -1,6 +1,6 @@
package com.dre.brewery.integration.barrel;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelAccessEvent;
import me.ryanhamshire.GriefPrevention.Claim;
import me.ryanhamshire.GriefPrevention.ClaimPermission;
@ -12,7 +12,7 @@ import java.util.function.Supplier;
public class GriefPreventionBarrel {
private static P brewery = P.p;
private static BreweryPlugin brewery = BreweryPlugin.getInstance();
public static boolean checkAccess(BarrelAccessEvent event) {
GriefPrevention griefPrevention = GriefPrevention.instance;

View File

@ -1,7 +1,7 @@
package com.dre.brewery.integration.barrel;
import com.dre.brewery.Barrel;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.griefcraft.listeners.LWCPlayerListener;
import com.griefcraft.lwc.LWC;
import com.griefcraft.model.Flag;
@ -40,7 +40,7 @@ public class LWCBarrel {
}
} catch (Exception e) {
lwc.sendLocale(player, "protection.internalerror", "id", "BLOCK_BREAK");
P.p.errorLog("Failed to dispatch LWCProtectionDestroyEvent");
BreweryPlugin.getInstance().errorLog("Failed to dispatch LWCProtectionDestroyEvent");
e.printStackTrace();
return true;
}
@ -71,7 +71,7 @@ public class LWCBarrel {
}
} catch (EventException e) {
lwc.sendLocale(player, "protection.internalerror", "id", "PLAYER_INTERACT");
P.p.errorLog("Block Interact could not be passed to LWC");
BreweryPlugin.getInstance().errorLog("Block Interact could not be passed to LWC");
e.printStackTrace();
return false;
}

View File

@ -1,7 +1,7 @@
package com.dre.brewery.integration.barrel;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.LegacyUtil;
import com.dre.brewery.P;
import de.diddiz.LogBlock.Actor;
import java.util.ArrayList;
@ -31,14 +31,14 @@ public class LogBlockBarrel {
private static Method queueChestAccess;
static {
if (!P.use1_13) {
if (!BreweryPlugin.use1_13) {
try {
rawData = BukkitUtils.class.getDeclaredMethod("rawData", ItemStack.class);
queueChestAccess = Consumer.class.getDeclaredMethod("queueChestAccess", String.class, Location.class, int.class, short.class, short.class, short.class);
} catch (NoSuchMethodException e) {
P.p.errorLog("Failed to hook into LogBlock to log barrels. Logging barrel contents is not going to work.");
P.p.errorLog("Brewery was tested with version 1.12 to 1.13.1 of LogBlock.");
P.p.errorLog("Disable LogBlock support in the configuration file and type /brew reload.");
BreweryPlugin.getInstance().errorLog("Failed to hook into LogBlock to log barrels. Logging barrel contents is not going to work.");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 1.12 to 1.13.1 of LogBlock.");
BreweryPlugin.getInstance().errorLog("Disable LogBlock support in the configuration file and type /brew reload.");
e.printStackTrace();
}
}
@ -61,7 +61,7 @@ public class LogBlockBarrel {
}
final ItemStack[] diff = compareInventories(items, after);
for (final ItemStack item : diff) {
if (!P.use1_13) {
if (!BreweryPlugin.use1_13) {
try {
//noinspection deprecation
queueChestAccess.invoke(consumer, player.getName(), loc, LegacyUtil.getBlockTypeIdAt(loc), (short) item.getType().getId(), (short) item.getAmount(), rawData.invoke(null, item));
@ -109,7 +109,7 @@ public class LogBlockBarrel {
if (!isLogging(spigotLoc.getWorld(), Logging.CHESTACCESS)) return;
final ItemStack[] items = compressInventory(contents);
for (final ItemStack item : items) {
if (!P.use1_13) {
if (!BreweryPlugin.use1_13) {
try {
//noinspection deprecation
queueChestAccess.invoke(consumer, player.getName(), spigotLoc, LegacyUtil.getBlockTypeIdAt(spigotLoc), (short) item.getType().getId(), (short) (item.getAmount() * -1), rawData.invoke(null, item));

View File

@ -1,6 +1,6 @@
package com.dre.brewery.integration.barrel;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelAccessEvent;
import com.palmergames.bukkit.towny.TownySettings;
@ -12,7 +12,7 @@ import org.bukkit.Material;
public class TownyBarrel {
public static boolean checkAccess(BarrelAccessEvent event) {
Location barrelLoc = event.getSpigot().getLocation();
Material mat = P.use1_14 ? Material.BARREL : Material.CHEST;
Material mat = BreweryPlugin.use1_14 ? Material.BARREL : Material.CHEST;
if (!TownySettings.isSwitchMaterial(mat, barrelLoc)) {
return true;

View File

@ -3,12 +3,12 @@ package com.dre.brewery.integration.barrel;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.block.Block;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.dre.brewery.P;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
@ -29,9 +29,9 @@ public class WGBarrel5 implements WGBarrel {
canBuild = ApplicableRegionSet.class.getMethod("canBuild", LocalPlayer.class);
getApplicableRegions = RegionManager.class.getMethod("getApplicableRegions", Location.class);
} catch (NoSuchMethodException e) {
P.p.errorLog("Failed to Hook WorldGuard for Barrel Open Permissions! Opening Barrels will NOT work!");
P.p.errorLog("Brewery was tested with version 5.8, 6.1 to 7.0 of WorldGuard!");
P.p.errorLog("Disable the WorldGuard support in the config and do /brew reload");
BreweryPlugin.getInstance().errorLog("Failed to Hook WorldGuard for Barrel Open Permissions! Opening Barrels will NOT work!");
BreweryPlugin.getInstance().errorLog("Brewery was tested with version 5.8, 6.1 to 7.0 of WorldGuard!");
BreweryPlugin.getInstance().errorLog("Disable the WorldGuard support in the config and do /brew reload");
e.printStackTrace();
}
}

View File

@ -1,12 +1,12 @@
package com.dre.brewery.integration.barrel;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import com.dre.brewery.P;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
@ -46,7 +46,7 @@ public class WGBarrel7 implements WGBarrel {
world = ((World) getWorldByName.invoke(platform, spigot.getWorld().getName()));
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
P.p.msg(player, "Error in WorldGuard");
BreweryPlugin.getInstance().msg(player, "Error in WorldGuard");
return false;
}
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.integration.item;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.recipe.PluginItem;
import io.lumine.mythic.lib.api.item.NBTItem;
@ -15,8 +15,8 @@ public class MMOItemsPluginItem extends PluginItem {
@Override
public boolean matches(ItemStack item) {
if (BConfig.hasMMOItems == null) {
BConfig.hasMMOItems = P.p.getServer().getPluginManager().isPluginEnabled("MMOItems")
&& P.p.getServer().getPluginManager().isPluginEnabled("MythicLib");
BConfig.hasMMOItems = BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("MMOItems")
&& BreweryPlugin.getInstance().getServer().getPluginManager().isPluginEnabled("MythicLib");
}
if (!BConfig.hasMMOItems) return false;
@ -25,7 +25,7 @@ public class MMOItemsPluginItem extends PluginItem {
return nbtItem.hasType() && nbtItem.getString("MMOITEMS_ITEM_ID").equalsIgnoreCase(getItemId());
} catch (Throwable e) {
e.printStackTrace();
P.p.errorLog("Could not check MMOItems for Item ID");
BreweryPlugin.getInstance().errorLog("Could not check MMOItems for Item ID");
BConfig.hasMMOItems = false;
return false;
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.integration.item;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.recipe.PluginItem;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem;
@ -24,7 +24,7 @@ public class SlimefunPluginItem extends PluginItem {
}
} catch (Exception | LinkageError e) {
e.printStackTrace();
P.p.errorLog("Could not check Slimefun for Item ID");
BreweryPlugin.getInstance().errorLog("Could not check Slimefun for Item ID");
BConfig.hasSlimefun = false;
return false;
}

View File

@ -1,10 +1,7 @@
package com.dre.brewery.listeners;
import com.dre.brewery.BPlayer;
import com.dre.brewery.BSealer;
import com.dre.brewery.Barrel;
import com.dre.brewery.DistortChat;
import com.dre.brewery.P;
import com.dre.brewery.*;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelDestroyEvent;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.filedata.BData;
@ -27,22 +24,22 @@ public class BlockListener implements Listener {
if (hasBarrelLine(lines)) {
Player player = event.getPlayer();
if (!player.hasPermission("brewery.createbarrel.small") && !player.hasPermission("brewery.createbarrel.big")) {
P.p.msg(player, P.p.languageReader.get("Perms_NoBarrelCreate"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Perms_NoBarrelCreate"));
return;
}
if (BData.dataMutex.get() > 0) {
P.p.msg(player, "§cCurrently loading Data");
BreweryPlugin.getInstance().msg(player, "§cCurrently loading Data");
return;
}
if (Barrel.create(event.getBlock(), player)) {
P.p.msg(player, P.p.languageReader.get("Player_BarrelCreated"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Player_BarrelCreated"));
}
}
}
public static boolean hasBarrelLine(String[] lines) {
for (String line : lines) {
if (line.equalsIgnoreCase("Barrel") || line.equalsIgnoreCase(P.p.languageReader.get("Etc_Barrel"))) {
if (line.equalsIgnoreCase("Barrel") || line.equalsIgnoreCase(BreweryPlugin.getInstance().languageReader.get("Etc_Barrel"))) {
return true;
}
}
@ -66,7 +63,7 @@ public class BlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (!P.use1_14 || event.getBlock().getType() != Material.SMOKER) return;
if (!BreweryPlugin.use1_14 || event.getBlock().getType() != Material.SMOKER) return;
BSealer.blockPlace(event.getItemInHand(), event.getBlock());
}

View File

@ -1,16 +1,20 @@
package com.dre.brewery.listeners;
import com.dre.brewery.BCauldron;
import com.dre.brewery.P;
import com.dre.brewery.utility.LegacyUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.Levelled;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.CauldronLevelChangeEvent;
import java.util.List;
public class CauldronListener implements Listener {
/**
@ -37,8 +41,9 @@ public class CauldronListener implements Listener {
}
} else { // newType == Material.WATER_CAULDRON
// Water level change
Levelled oldCauldron = ((Levelled) event.getBlock().getBlockData());
Levelled newCauldron = ((Levelled) newState.getBlockData());
Levelled oldCauldron = (Levelled) event.getBlock().getBlockData();
Levelled newCauldron = (Levelled) newState.getBlockData();
// Water Level increased somehow, might be Bucket, Bottle, Rain, etc.
if (newCauldron.getLevel() > oldCauldron.getLevel()) {
@ -48,6 +53,17 @@ public class CauldronListener implements Listener {
}
}
/* PATCH - "My friend found a way to dupe brews #541" https://github.com/DieReicheErethons/Brewery/issues/541
* Check if piston is pushing a BreweryCauldron and remove it
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPistonExtend(BlockPistonExtendEvent event) {
for (Block block : event.getBlocks()) {
if (BCauldron.bcauldrons.containsKey(block)) {
BCauldron.remove(block);
}
}
}
@SuppressWarnings("deprecation")
private void oldCauldronChange(CauldronLevelChangeEvent event) {

View File

@ -1,798 +0,0 @@
package com.dre.brewery.listeners;
import com.dre.brewery.*;
import com.dre.brewery.api.events.brew.BrewModifyEvent;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.recipe.BRecipe;
import com.dre.brewery.recipe.Ingredient;
import com.dre.brewery.recipe.RecipeItem;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.PermissionUtil;
import com.dre.brewery.utility.Tuple;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Locale;
import static com.dre.brewery.utility.PermissionUtil.BPermission.*;
public class CommandListener implements CommandExecutor {
public P p = P.p;
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
String cmd = "help";
if (args.length > 0) {
cmd = args[0];
}
if (cmd.equalsIgnoreCase("help")) {
cmdHelp(sender, args);
} else if (cmd.equalsIgnoreCase("reload")) {
if (sender.hasPermission("brewery.cmd.reload")) {
p.reload(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("configname") || cmd.equalsIgnoreCase("itemname") || cmd.equalsIgnoreCase("iteminfo")) {
if (sender.hasPermission("brewery.cmd.reload")) {
cmdItemName(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("wakeup")) {
if (sender.hasPermission("brewery.cmd.wakeup")) {
cmdWakeup(sender, args);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("create") || cmd.equalsIgnoreCase("give")) {
if (sender.hasPermission("brewery.cmd.create")) {
cmdCreate(sender, args);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("info")) {
if (args.length > 1) {
if (sender.hasPermission("brewery.cmd.infoOther")) {
cmdInfo(sender, args[1]);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else {
if (sender.hasPermission("brewery.cmd.info")) {
cmdInfo(sender, null);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
}
} else if (cmd.equalsIgnoreCase("seal") || cmd.startsWith("seal") || cmd.startsWith("Seal")) {
if (sender.hasPermission("brewery.cmd.seal")) {
cmdSeal(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("copy") || cmd.equalsIgnoreCase("cp")) {
if (sender.hasPermission("brewery.cmd.copy")) {
if (args.length > 1) {
cmdCopy(sender, p.parseInt(args[1]));
} else {
cmdCopy(sender, 1);
}
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("delete") || cmd.equalsIgnoreCase("rm") || cmd.equalsIgnoreCase("remove")) {
if (sender.hasPermission("brewery.cmd.delete")) {
cmdDelete(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("static")) {
if (sender.hasPermission("brewery.cmd.static")) {
cmdStatic(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("unlabel")) {
if (sender.hasPermission("brewery.cmd.unlabel")) {
cmdUnlabel(sender);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
} else if (cmd.equalsIgnoreCase("debuginfo")) {
debugInfo(sender, args.length > 1 ? args[1] : null);
} else if (cmd.equalsIgnoreCase("showstats")) {
showStats(sender);
} else if (cmd.equalsIgnoreCase("puke") || cmd.equalsIgnoreCase("vomit") || cmd.equalsIgnoreCase("barf")) {
cmdPuke(sender, args);
} else if (cmd.equalsIgnoreCase("drink")) {
cmdDrink(sender, args);
} else {
if (p.getServer().getPlayerExact(cmd) != null || BPlayer.hasPlayerbyName(cmd)) {
if (args.length == 1) {
if (sender.hasPermission("brewery.cmd.infoOther")) {
cmdInfo(sender, cmd);
}
} else {
if (sender.hasPermission("brewery.cmd.player")) {
cmdPlayer(sender, args);
} else {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
}
}
} else {
p.msg(sender, p.languageReader.get("Error_UnknownCommand"));
p.msg(sender, p.languageReader.get("Error_ShowHelp"));
}
}
return true;
}
public void cmdHelp(CommandSender sender, String[] args) {
int page = 1;
if (args.length > 1) {
page = p.parseInt(args[1]);
}
ArrayList<String> commands = getCommands(sender);
if (page == 1) {
p.msg(sender, "&6" + p.getDescription().getName() + " v" + p.getDescription().getVersion());
}
BUtil.list(sender, commands, page);
}
public ArrayList<String> getCommands(CommandSender sender) {
ArrayList<String> cmds = new ArrayList<>();
cmds.add(p.languageReader.get("Help_Help"));
PermissionUtil.evaluateExtendedPermissions(sender);
if (PLAYER.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_Player"));
}
if (INFO.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_Info"));
}
if (P.use1_13 && SEAL.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_Seal"));
}
if (UNLABEL.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_UnLabel"));
}
if (PermissionUtil.noExtendedPermissions(sender)) {
return cmds;
}
if (INFO_OTHER.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_InfoOther"));
}
if (CREATE.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Create"));
cmds.add(p.languageReader.get("Help_Give"));
}
if (DRINK.checkCached(sender) || DRINK_OTHER.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Drink"));
}
if (RELOAD.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Configname"));
cmds.add(p.languageReader.get("Help_Reload"));
}
if (PUKE.checkCached(sender) || PUKE_OTHER.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Puke"));
}
if (WAKEUP.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Wakeup"));
cmds.add(p.languageReader.get("Help_WakeupList"));
cmds.add(p.languageReader.get("Help_WakeupCheck"));
cmds.add(p.languageReader.get("Help_WakeupCheckSpecific"));
cmds.add(p.languageReader.get("Help_WakeupAdd"));
cmds.add(p.languageReader.get("Help_WakeupRemove"));
}
if (STATIC.checkCached(sender)) {
cmds.add(p.languageReader.get("Help_Static"));
}
if (COPY.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_Copy"));
}
if (DELETE.checkCached(sender)) {
cmds.add (p.languageReader.get("Help_Delete"));
}
return cmds;
}
public void cmdWakeup(CommandSender sender, String[] args) {
if (args.length == 1) {
cmdHelp(sender, args);
return;
}
if (args[1].equalsIgnoreCase("add")) {
Wakeup.set(sender);
} else if (args[1].equalsIgnoreCase("list")){
int page = 1;
String world = null;
if (args.length > 2) {
page = p.parseInt(args[2]);
}
if (args.length > 3) {
world = args[3];
}
Wakeup.list(sender, page, world);
} else if (args[1].equalsIgnoreCase("remove")){
if (args.length > 2) {
int id = p.parseInt(args[2]);
Wakeup.remove(sender, id);
} else {
p.msg(sender, p.languageReader.get("Etc_Usage"));
p.msg(sender, p.languageReader.get("Help_WakeupRemove"));
}
} else if (args[1].equalsIgnoreCase("check")){
int id = -1;
if (args.length > 2) {
id = p.parseInt(args[2]);
if (id < 0) {
id = 0;
}
}
Wakeup.check(sender, id, id == -1);
} else if (args[1].equalsIgnoreCase("cancel")){
Wakeup.cancel(sender);
} else {
p.msg(sender, p.languageReader.get("Error_UnknownCommand"));
p.msg(sender, p.languageReader.get("Error_ShowHelp"));
}
}
public void cmdPlayer(CommandSender sender, String[] args) {
int drunkeness = p.parseInt(args[1]);
if (drunkeness < 0) {
return;
}
int quality = -1;
if (args.length > 2) {
quality = p.parseInt(args[2]);
if (quality < 1 || quality > 10) {
p.msg(sender, p.languageReader.get("CMD_Player_Error"));
return;
}
}
String playerName = args[0];
Player player = P.p.getServer().getPlayerExact(playerName);
BPlayer bPlayer;
if (player == null) {
bPlayer = BPlayer.getByName(playerName);
} else {
bPlayer = BPlayer.get(player);
}
if (bPlayer == null && player != null) {
if (drunkeness == 0) {
return;
}
bPlayer = BPlayer.addPlayer(player);
}
if (bPlayer == null) {
return;
}
if (drunkeness == 0) {
bPlayer.remove();
} else {
bPlayer.setData(drunkeness, quality);
if (BConfig.showStatusOnDrink) {
bPlayer.showDrunkeness(player);
}
}
if (drunkeness > 100) {
if (player != null) {
bPlayer.drinkCap(player);
} else {
if (!BConfig.overdrinkKick) {
bPlayer.setData(100, 0);
}
}
}
p.msg(sender, p.languageReader.get("CMD_Player", playerName, "" + drunkeness, "" + bPlayer.getQuality()));
}
public void cmdInfo(CommandSender sender, String playerName) {
boolean selfInfo = playerName == null;
if (selfInfo) {
if (sender instanceof Player) {
Player player = (Player) sender;
playerName = player.getName();
} else {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
}
Player player = P.p.getServer().getPlayerExact(playerName);
BPlayer bPlayer;
if (player == null) {
bPlayer = BPlayer.getByName(playerName);
} else {
bPlayer = BPlayer.get(player);
}
if (bPlayer == null) {
p.msg(sender, p.languageReader.get("CMD_Info_NotDrunk", playerName));
} else {
if (selfInfo) {
bPlayer.showDrunkeness(player);
} else {
p.msg(sender, p.languageReader.get("CMD_Info_Drunk", playerName, "" + bPlayer.getDrunkeness(), "" + bPlayer.getQuality()));
}
}
}
public void cmdItemName(CommandSender sender) {
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
@SuppressWarnings("deprecation")
ItemStack hand = P.use1_9 ? player.getInventory().getItemInMainHand() : player.getItemInHand();
if (hand != null) {
p.msg(sender, p.languageReader.get("CMD_Configname", hand.getType().name().toLowerCase(Locale.ENGLISH)));
} else {
p.msg(sender, p.languageReader.get("CMD_Configname_Error"));
}
}
public void cmdSeal(CommandSender sender) {
if (!P.use1_13) {
P.p.msg(sender, "Sealing requires minecraft 1.13 or higher");
return;
}
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
player.openInventory(new BSealer(player).getInventory());
}
@Deprecated
public void cmdCopy(CommandSender sender, int count) {
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
if (count < 1 || count > 36) {
p.msg(sender, p.languageReader.get("Etc_Usage"));
p.msg(sender, p.languageReader.get("Help_Copy"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
if (Brew.isBrew(hand)) {
while (count > 0) {
ItemStack item = hand.clone();
if (!(player.getInventory().addItem(item)).isEmpty()) {
p.msg(sender, p.languageReader.get("CMD_Copy_Error", "" + count));
return;
}
count--;
}
return;
}
}
p.msg(sender, p.languageReader.get("Error_ItemNotPotion"));
}
@Deprecated
public void cmdDelete(CommandSender sender) {
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
if (Brew.isBrew(hand)) {
player.setItemInHand(new ItemStack(Material.AIR));
return;
}
}
p.msg(sender, p.languageReader.get("Error_ItemNotPotion"));
}
public void debugInfo(CommandSender sender, String recipeName) {
if (!P.use1_9 || !sender.isOp()) return;
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getInventory().getItemInMainHand();
if (hand != null) {
Brew brew = Brew.get(hand);
if (brew == null) return;
P.p.log(brew.toString());
BIngredients ingredients = brew.getIngredients();
if (recipeName == null) {
P.p.log("&lIngredients:");
for (Ingredient ing : ingredients.getIngredientList()) {
P.p.log(ing.toString());
}
P.p.log("&lTesting Recipes");
for (BRecipe recipe : BRecipe.getAllRecipes()) {
int ingQ = ingredients.getIngredientQuality(recipe);
int cookQ = ingredients.getCookingQuality(recipe, false);
int cookDistQ = ingredients.getCookingQuality(recipe, true);
int ageQ = ingredients.getAgeQuality(recipe, brew.getAgeTime());
P.p.log(recipe.getRecipeName() + ": ingQlty: " + ingQ + ", cookQlty:" + cookQ + ", cook+DistQlty: " + cookDistQ + ", ageQlty: " + ageQ);
}
BRecipe distill = ingredients.getBestRecipe(brew.getWood(), brew.getAgeTime(), true);
BRecipe nonDistill = ingredients.getBestRecipe(brew.getWood(), brew.getAgeTime(), false);
P.p.log("&lWould prefer Recipe: " + (nonDistill == null ? "none" : nonDistill.getRecipeName()) + " and Distill-Recipe: " + (distill == null ? "none" : distill.getRecipeName()));
} else {
BRecipe recipe = BRecipe.getMatching(recipeName);
if (recipe == null) {
P.p.msg(player, "Could not find Recipe " + recipeName);
return;
}
P.p.log("&lIngredients in Recipe " + recipe.getRecipeName() + ":");
for (RecipeItem ri : recipe.getIngredients()) {
P.p.log(ri.toString());
}
P.p.log("&lIngredients in Brew:");
for (Ingredient ingredient : ingredients.getIngredientList()) {
int amountInRecipe = recipe.amountOf(ingredient);
P.p.log(ingredient.toString() + ": " + amountInRecipe + " of this are in the Recipe");
}
int ingQ = ingredients.getIngredientQuality(recipe);
int cookQ = ingredients.getCookingQuality(recipe, false);
int cookDistQ = ingredients.getCookingQuality(recipe, true);
int ageQ = ingredients.getAgeQuality(recipe, brew.getAgeTime());
P.p.log("ingQlty: " + ingQ + ", cookQlty:" + cookQ + ", cook+DistQlty: " + cookDistQ + ", ageQlty: " + ageQ);
}
P.p.msg(player, "Debug Info for item written into Log");
}
}
public void showStats(CommandSender sender) {
if (sender instanceof ConsoleCommandSender && !sender.isOp()) return;
P.p.msg(sender, "Drunk Players: " + BPlayer.numDrunkPlayers());
P.p.msg(sender, "Brews created: " + P.p.stats.brewsCreated);
P.p.msg(sender, "Barrels built: " + Barrel.barrels.size());
P.p.msg(sender, "Cauldrons boiling: " + BCauldron.bcauldrons.size());
P.p.msg(sender, "Number of Recipes: " + BRecipe.getAllRecipes().size());
P.p.msg(sender, "Wakeups: " + Wakeup.wakeups.size());
}
@SuppressWarnings("deprecation")
public void cmdStatic(CommandSender sender) {
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
Brew brew = Brew.get(hand);
if (brew != null) {
if (brew.isStatic()) {
if (!brew.isStripped()) {
brew.setStatic(false, hand);
p.msg(sender, p.languageReader.get("CMD_NonStatic"));
} else {
p.msg(sender, p.languageReader.get("Error_SealedAlwaysStatic"));
return;
}
} else {
brew.setStatic(true, hand);
p.msg(sender, p.languageReader.get("CMD_Static"));
}
brew.touch();
ItemMeta meta = hand.getItemMeta();
assert meta != null;
BrewModifyEvent modifyEvent = new BrewModifyEvent(brew, meta, BrewModifyEvent.Type.STATIC);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
return;
}
brew.save(meta);
hand.setItemMeta(meta);
return;
}
}
p.msg(sender, p.languageReader.get("Error_ItemNotPotion"));
}
@SuppressWarnings("deprecation")
public void cmdUnlabel(CommandSender sender) {
if (!(sender instanceof Player)) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
Player player = (Player) sender;
ItemStack hand = player.getItemInHand();
if (hand != null) {
Brew brew = Brew.get(hand);
if (brew != null) {
if (!brew.isUnlabeled()) {
ItemMeta origMeta = hand.getItemMeta();
brew.unLabel(hand);
brew.touch();
ItemMeta meta = hand.getItemMeta();
assert meta != null;
BrewModifyEvent modifyEvent = new BrewModifyEvent(brew, meta, BrewModifyEvent.Type.UNLABEL);
P.p.getServer().getPluginManager().callEvent(modifyEvent);
if (modifyEvent.isCancelled()) {
hand.setItemMeta(origMeta);
return;
}
brew.save(meta);
hand.setItemMeta(meta);
p.msg(sender, p.languageReader.get("CMD_UnLabel"));
return;
} else {
p.msg(sender, p.languageReader.get("Error_AlreadyUnlabeled"));
return;
}
}
}
p.msg(sender, p.languageReader.get("Error_ItemNotPotion"));
}
public void cmdCreate(CommandSender sender, String[] args) {
if (args.length < 2) {
p.msg(sender, p.languageReader.get("Etc_Usage"));
p.msg(sender, p.languageReader.get("Help_Create"));
return;
}
Tuple<Brew, Player> brewForPlayer = getFromCommand(sender, args);
if (brewForPlayer != null) {
if (brewForPlayer.b().getInventory().firstEmpty() == -1) {
p.msg(sender, p.languageReader.get("CMD_Copy_Error", "1"));
return;
}
ItemStack item = brewForPlayer.a().createItem(null);
if (item != null) {
brewForPlayer.b().getInventory().addItem(item);
p.msg(sender, p.languageReader.get("CMD_Created"));
}
}
}
@Nullable
public Tuple<Brew, Player> getFromCommand(CommandSender sender, String[] args) {
if (args.length < 2) {
return null;
}
int quality = 10;
boolean hasQuality = false;
String pName = null;
if (args.length > 2) {
quality = p.parseInt(args[args.length - 1]);
if (quality <= 0 || quality > 10) {
pName = args[args.length - 1];
if (args.length > 3) {
quality = p.parseInt(args[args.length - 2]);
}
}
if (quality > 0 && quality <= 10) {
hasQuality = true;
} else {
quality = 10;
}
}
Player player = null;
if (pName != null) {
player = p.getServer().getPlayer(pName);
}
if (!(sender instanceof Player) && player == null) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return null;
}
if (player == null) {
player = ((Player) sender);
pName = null;
}
int stringLength = args.length - 1;
if (pName != null) {
stringLength--;
}
if (hasQuality) {
stringLength--;
}
String name;
if (stringLength > 1) {
StringBuilder builder = new StringBuilder(args[1]);
for (int i = 2; i < stringLength + 1; i++) {
builder.append(" ").append(args[i]);
}
name = builder.toString();
} else {
name = args[1];
}
name = name.replaceAll("\"", "");
BRecipe recipe = BRecipe.getMatching(name);
if (recipe != null) {
return new Tuple<>(recipe.createBrew(quality), player);
} else {
p.msg(sender, p.languageReader.get("Error_NoBrewName", name));
}
return null;
}
public void cmdPuke(CommandSender sender, String[] args) {
if (!sender.hasPermission("brewery.cmd.puke")) {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
return;
}
Player player = null;
if (args.length > 1) {
player = p.getServer().getPlayer(args[1]);
if (player == null) {
p.msg(sender, p.languageReader.get("Error_NoPlayer", args[1]));
return;
}
}
if (!(sender instanceof Player) && player == null) {
p.msg(sender, p.languageReader.get("Error_PlayerCommand"));
return;
}
if (player == null) {
player = ((Player) sender);
} else {
if (!sender.hasPermission("brewery.cmd.pukeOther") && !player.equals(sender)) {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
return;
}
}
int count = 0;
if (args.length > 2) {
count = P.p.parseInt(args[2]);
}
if (count <= 0) {
count = 20 + (int) (Math.random() * 40);
}
BPlayer.addPuke(player, count);
}
public void cmdDrink(CommandSender sender, String[] args) {
if (!sender.hasPermission("brewery.cmd.drink") || !sender.hasPermission("brewery.cmd.drink")) {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
return;
}
if (args.length < 2) {
p.msg(sender, p.languageReader.get("Etc_Usage"));
p.msg(sender, p.languageReader.get("Help_Drink"));
return;
}
Tuple<Brew, Player> brewForPlayer = getFromCommand(sender, args);
if (brewForPlayer != null) {
Player player = brewForPlayer.b();
if ((!sender.equals(player) && !sender.hasPermission("brewery.cmd.drinkOther")) ||
(sender.equals(player) && !sender.hasPermission("brewery.cmd.drink"))) {
p.msg(sender, p.languageReader.get("Error_NoPermissions"));
} else {
Brew brew = brewForPlayer.a();
String brewName = brew.getCurrentRecipe().getName(brew.getQuality());
BPlayer.drink(brew, null, player);
p.msg(player, p.languageReader.get("CMD_Drink", brewName));
if (!sender.equals(player)) {
p.msg(sender, p.languageReader.get("CMD_DrinkOther", player.getDisplayName(), brewName));
}
}
}
}
}

View File

@ -2,7 +2,7 @@ package com.dre.brewery.listeners;
import com.dre.brewery.Barrel;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.api.events.barrel.BarrelDestroyEvent;
import org.bukkit.Material;
import org.bukkit.block.Block;
@ -72,7 +72,7 @@ public class EntityListener implements Listener {
if (barrel != null) {
BarrelDestroyEvent breakEvent = new BarrelDestroyEvent(barrel, block, BarrelDestroyEvent.Reason.EXPLODED, null);
// Listened to by LWCBarrel (IntegrationListener)
P.p.getServer().getPluginManager().callEvent(breakEvent);
BreweryPlugin.getInstance().getServer().getPluginManager().callEvent(breakEvent);
breakEvents.add(breakEvent);
if (breakEvent.isCancelled()) {
iter.remove();

View File

@ -31,12 +31,12 @@ public class InventoryListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBrewerOpen(InventoryOpenEvent event) {
if (!P.use1_9) return;
if (!BreweryPlugin.use1_9) return;
HumanEntity player = event.getPlayer();
Inventory inv = event.getInventory();
if (player == null || !(inv instanceof BrewerInventory)) return;
P.p.debugLog("Starting brew inventory tracking");
BreweryPlugin.getInstance().debugLog("Starting brew inventory tracking");
trackedBrewmen.add(player.getUniqueId());
}
@ -45,18 +45,18 @@ public class InventoryListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBrewerClose(InventoryCloseEvent event) {
if (!P.use1_9) return;
if (!BreweryPlugin.use1_9) return;
HumanEntity player = event.getPlayer();
Inventory inv = event.getInventory();
if (player == null || !(inv instanceof BrewerInventory)) return;
P.p.debugLog("Stopping brew inventory tracking");
BreweryPlugin.getInstance().debugLog("Stopping brew inventory tracking");
trackedBrewmen.remove(player.getUniqueId());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBrewerDrag(InventoryDragEvent event) {
if (!P.use1_9) return;
if (!BreweryPlugin.use1_9) return;
// Workaround the Drag event when only clicking a slot
if (event.getInventory() instanceof BrewerInventory) {
onBrewerClick(new InventoryClickEvent(event.getView(), InventoryType.SlotType.CONTAINER, 0, ClickType.LEFT, InventoryAction.PLACE_ALL));
@ -70,7 +70,7 @@ public class InventoryListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBrewerClick(InventoryClickEvent event) {
if (!P.use1_9) return;
if (!BreweryPlugin.use1_9) return;
HumanEntity player = event.getWhoClicked();
Inventory inv = event.getInventory();
@ -87,7 +87,7 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBrew(BrewEvent event) {
if (P.use1_9) {
if (BreweryPlugin.use1_9) {
if (BDistiller.hasBrew(event.getContents(), BDistiller.getDistillContents(event.getContents())) != 0) {
event.setCancelled(true);
}
@ -106,7 +106,7 @@ public class InventoryListener implements Listener {
if (item.hasItemMeta()) {
PotionMeta potion = ((PotionMeta) item.getItemMeta());
assert potion != null;
if (P.use1_11) {
if (BreweryPlugin.use1_11) {
// Convert potions from 1.10 to 1.11 for new color
if (potion.getColor() == null) {
Brew brew = Brew.get(potion);
@ -116,7 +116,7 @@ public class InventoryListener implements Listener {
}
} else {
// convert potions from 1.8 to 1.9 for color and to remove effect descriptions
if (P.use1_9 && !potion.hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)) {
if (BreweryPlugin.use1_9 && !potion.hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)) {
Brew brew = Brew.get(potion);
if (brew != null) {
brew.convertPre1_9(item);
@ -138,7 +138,7 @@ public class InventoryListener implements Listener {
if (event.getSlot() > 2) {
return;
}
} else if (!(event.getInventory().getHolder() instanceof Barrel) && !(P.use1_14 && event.getInventory().getHolder() instanceof org.bukkit.block.Barrel)) {
} else if (!(event.getInventory().getHolder() instanceof Barrel) && !(BreweryPlugin.use1_14 && event.getInventory().getHolder() instanceof org.bukkit.block.Barrel)) {
return;
}
@ -164,7 +164,7 @@ public class InventoryListener implements Listener {
case MOVE_TO_OTHER_INVENTORY:
case HOTBAR_SWAP:
// Fix a Graphical glitch of item still showing colors until clicking it
P.p.getServer().getScheduler().runTask(P.p, () -> ((Player) event.getWhoClicked()).updateInventory());
BreweryPlugin.getScheduler().runTask(() -> ((Player) event.getWhoClicked()).updateInventory());
}
}
}
@ -175,7 +175,7 @@ public class InventoryListener implements Listener {
// Check if the player tries to add more than the allowed amount of brews into an mc-barrel
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onInventoryClickMCBarrel(InventoryClickEvent event) {
if (!P.use1_14) return;
if (!BreweryPlugin.use1_14) return;
if (event.getInventory().getType() != InventoryType.BARREL) return;
if (!MCBarrel.enableAging) return;
@ -194,7 +194,7 @@ public class InventoryListener implements Listener {
// Handle the Brew Sealer Inventory
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onInventoryClickBSealer(InventoryClickEvent event) {
if (!P.use1_13) return;
if (!BreweryPlugin.use1_13) return;
InventoryHolder holder = event.getInventory().getHolder();
if (!(holder instanceof BSealer)) {
return;
@ -227,20 +227,9 @@ public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) {
if (!P.use1_14) return;
if (!BreweryPlugin.use1_14) return;
if (!MCBarrel.enableAging) return;
/*Barrel x = null;
if (event.getInventory().getHolder() instanceof Barrel) {
x = ((Barrel) event.getInventory().getHolder());
}
if (!opening) {
opening = true;
Barrel finalBarrel = x;
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> {finalBarrel.remove(null, null); opening = false;}, 100);
}*/
// Check for MC Barrel
if (event.getInventory().getType() == InventoryType.BARREL) {
Inventory inv = event.getInventory();
@ -259,7 +248,7 @@ public class InventoryListener implements Listener {
// block the pickup of items where getPickupDelay is > 1000 (puke)
@EventHandler(ignoreCancelled = true)
public void onHopperPickupPuke(InventoryPickupItemEvent event){
if (event.getItem().getPickupDelay() > 1000 && event.getItem().getItemStack().getType() == BConfig.pukeItem) {
if (event.getItem().getPickupDelay() > 1000 && BConfig.pukeItem.contains(event.getItem().getItemStack().getType())) {
event.setCancelled(true);
}
}
@ -275,7 +264,7 @@ public class InventoryListener implements Listener {
return;
}
if (!P.use1_14) return;
if (!BreweryPlugin.use1_14) return;
if (event.getSource().getType() == InventoryType.BARREL) {
ItemStack item = event.getItem();
@ -299,12 +288,12 @@ public class InventoryListener implements Listener {
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
if (!P.use1_13) return;
if (!BreweryPlugin.use1_13) return;
if (event.getInventory().getHolder() instanceof BSealer) {
((BSealer) event.getInventory().getHolder()).closeInv();
}
if (!P.use1_14) return;
if (!BreweryPlugin.use1_14) return;
// Barrel Closing Sound
if (event.getInventory().getHolder() instanceof Barrel) {

View File

@ -37,12 +37,12 @@ public class PlayerListener implements Listener {
// -- Clicking an Hopper --
if (type == Material.HOPPER) {
if (BConfig.brewHopperDump && event.getPlayer().isSneaking()) {
if (!P.use1_9 || event.getHand() == EquipmentSlot.HAND) {
if (!BreweryPlugin.use1_9 || event.getHand() == EquipmentSlot.HAND) {
ItemStack item = event.getItem();
if (Brew.isBrew(item)) {
event.setCancelled(true);
BUtil.setItemInHand(event, Material.GLASS_BOTTLE, false);
if (P.use1_11) {
if (BreweryPlugin.use1_11) {
clickedBlock.getWorld().playSound(clickedBlock.getLocation(), Sound.ITEM_BOTTLE_EMPTY, 1f, 1f);
}
}
@ -52,7 +52,7 @@ public class PlayerListener implements Listener {
}
// -- Opening a Sealing Table --
if (P.use1_14 && BSealer.isBSealer(clickedBlock)) {
if (BreweryPlugin.use1_14 && BSealer.isBSealer(clickedBlock)) {
if (player.isSneaking()) {
event.setUseInteractedBlock(Event.Result.DENY);
return;
@ -62,7 +62,7 @@ public class PlayerListener implements Listener {
BSealer sealer = new BSealer(player);
event.getPlayer().openInventory(sealer.getInventory());
} else {
P.p.msg(player, P.p.languageReader.get("Error_SealingTableDisabled"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Error_SealingTableDisabled"));
}
return;
}
@ -78,16 +78,16 @@ public class PlayerListener implements Listener {
}
// -- Opening a Minecraft Barrel --
if (P.use1_14 && type == Material.BARREL) {
if (BreweryPlugin.use1_14 && type == Material.BARREL) {
if (!player.hasPermission("brewery.openbarrel.mc")) {
event.setCancelled(true);
P.p.msg(player, P.p.languageReader.get("Error_NoPermissions"));
BreweryPlugin.getInstance().msg(player, BreweryPlugin.getInstance().languageReader.get("Error_NoPermissions"));
}
return;
}
// Do not process Off Hand for Barrel interaction
if (P.use1_9 && event.getHand() != EquipmentSlot.HAND) {
if (BreweryPlugin.use1_9 && event.getHand() != EquipmentSlot.HAND) {
return;
}
@ -117,7 +117,7 @@ public class PlayerListener implements Listener {
barrel.open(player);
if (P.use1_14) {
if (BreweryPlugin.use1_14) {
// When right clicking a normal Block in 1.14 with a potion or any edible item in hand,
// even when cancelled, the consume animation will continue playing while opening the Barrel inventory.
@ -142,7 +142,7 @@ public class PlayerListener implements Listener {
}
if (useSlot != -1) {
inv.setHeldItemSlot(useSlot);
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, () -> player.getInventory().setHeldItemSlot(held), 2);
BreweryPlugin.getScheduler().runTaskLater(() -> player.getInventory().setHeldItemSlot(held), 2);
}
}
@ -180,7 +180,7 @@ public class PlayerListener implements Listener {
/*if (player.getGameMode() != org.bukkit.GameMode.CREATIVE) {
brew.remove(item);
}*/
if (P.use1_9) {
if (BreweryPlugin.use1_9) {
if (player.getGameMode() != GameMode.CREATIVE) {
// replace the potion with an empty potion to avoid effects
event.setItem(new ItemStack(Material.POTION));
@ -263,10 +263,10 @@ public class PlayerListener implements Listener {
bplayer.join(player);
return;
case 2:
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, P.p.languageReader.get("Player_LoginDeny"));
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, BreweryPlugin.getInstance().languageReader.get("Player_LoginDeny"));
return;
case 3:
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, P.p.languageReader.get("Player_LoginDenyLong"));
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, BreweryPlugin.getInstance().languageReader.get("Player_LoginDenyLong"));
}
}
}

View File

@ -1,154 +0,0 @@
package com.dre.brewery.listeners;
import com.dre.brewery.recipe.BRecipe;
import com.dre.brewery.utility.PermissionUtil;
import com.dre.brewery.utility.Tuple;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.stream.Collectors;
import static com.dre.brewery.utility.PermissionUtil.BPermission.*;
public class TabListener implements TabCompleter {
private static final Map<String, PermissionUtil.BPermission> COMMAND_COMPLETIONS = new HashMap<>(10);
static {
COMMAND_COMPLETIONS.put("help", null);
COMMAND_COMPLETIONS.put("unLabel", UNLABEL);
COMMAND_COMPLETIONS.put("create", CREATE);
COMMAND_COMPLETIONS.put("reload", RELOAD);
COMMAND_COMPLETIONS.put("drink", DRINK);
COMMAND_COMPLETIONS.put("itemName", RELOAD);
COMMAND_COMPLETIONS.put("seal", SEAL);
COMMAND_COMPLETIONS.put("static", STATIC);
COMMAND_COMPLETIONS.put("puke", PUKE);
COMMAND_COMPLETIONS.put("wakeup", WAKEUP);
}
private static final String[] QUALITY = {"1", "10"};
private static Set<Tuple<String, String>> mainSet;
private static Set<Tuple<String, String>> altSet;
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String command, String[] args) {
if (args.length < 1) {
return null;
}
if (args.length == 1) {
List<String> commands = COMMAND_COMPLETIONS.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(args[0]) && (entry.getValue() == null || entry.getValue().checkCached(sender)))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (commands.isEmpty()) {
if (PLAYER.checkCached(sender)) {
return null; // Player List
} else {
return new ArrayList<>(0);
}
} else {
return commands;
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("wakeup")) {
if (WAKEUP.checkCached(sender)) {
return tabWakeup(args[1]);
}
}
}
if (args[0].equalsIgnoreCase("create") || args[0].equalsIgnoreCase("drink")) {
if (DRINK.checkCached(sender)) {
return tabCreateAndDrink(args);
}
}
return null;
}
private static final String[] WAK = {"list", "add", "check", "remove", "cancel"};
public List<String> tabWakeup(String input) {
return filterWithInput(WAK, input);
}
public List<String> tabCreateAndDrink(String[] args) {
if (args.length == 2) {
if (mainSet == null) {
mainSet = new HashSet<>();
altSet = new HashSet<>();
for (BRecipe recipe : BRecipe.getAllRecipes()) {
mainSet.addAll(createLookupFromName(recipe.getName(5)));
Set<String> altNames = new HashSet<>(3);
altNames.add(recipe.getName(1));
altNames.add(recipe.getName(10));
if (recipe.getOptionalID().isPresent()) {
altNames.add(recipe.getOptionalID().get());
}
for (String altName : altNames) {
altSet.addAll(createLookupFromName(altName));
}
}
}
final String input = args[1].toLowerCase();
List<String> options = mainSet.stream()
.filter(s -> s.a().startsWith(input))
.map(Tuple::second)
.collect(Collectors.toList());
if (options.isEmpty()) {
options = altSet.stream()
.filter(s -> s.a().startsWith(input))
.map(Tuple::second)
.collect(Collectors.toList());
}
return options;
} else {
if (args[args.length - 2].matches("\\d")) {
// Player list
return null;
} else {
return filterWithInput(QUALITY, args[args.length - 1]);
}
}
}
private static List<Tuple<String, String>> createLookupFromName(final String name) {
return Arrays.stream(name.split(" "))
.map(word -> new Tuple<>(word.toLowerCase(), name))
.collect(Collectors.toList());
}
public static List<String> filterWithInput(String[] options, String input) {
return Arrays.stream(options)
.filter(s -> s.startsWith(input))
.collect(Collectors.toList());
}
public static List<String> filterWithInput(Collection<String> options, String input) {
return options.stream()
.filter(s -> s.startsWith(input))
.collect(Collectors.toList());
}
public static void reload() {
mainSet = null;
altSet = null;
}
}

View File

@ -2,8 +2,7 @@ package com.dre.brewery.listeners;
import com.dre.brewery.BCauldron;
import com.dre.brewery.Barrel;
import com.dre.brewery.P;
import com.dre.brewery.Wakeup;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.filedata.BData;
import com.dre.brewery.filedata.DataSave;
@ -21,7 +20,7 @@ public class WorldListener implements Listener {
public void onWorldLoad(WorldLoadEvent event) {
final World world = event.getWorld();
if (BConfig.loadDataAsync) {
P.p.getServer().getScheduler().runTaskAsynchronously(P.p, () -> lwDataTask(world));
BreweryPlugin.getScheduler().runTaskAsynchronously(() -> lwDataTask(world));
} else {
lwDataTask(world);
}

View File

@ -1,10 +1,10 @@
package com.dre.brewery.lore;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.recipe.BEffect;
import com.dre.brewery.BIngredients;
import com.dre.brewery.recipe.BRecipe;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.utility.BUtil;
import org.bukkit.inventory.meta.PotionMeta;
@ -20,9 +20,9 @@ import java.util.List;
* <p>Can efficiently replace certain lines of lore, to update brew information on an item.
*/
public class BrewLore {
private Brew brew;
private PotionMeta meta;
private List<String> lore;
private final Brew brew;
private final PotionMeta meta;
private final List<String> lore;
private boolean lineAddedOrRem = false;
public BrewLore(Brew brew, PotionMeta meta) {
@ -62,7 +62,7 @@ public class BrewLore {
} else if (t != null && t.isAfter(Type.SPACE)) {
if (hasSpace) return;
if (hasCustom || P.useNBT) {
if (hasCustom || BreweryPlugin.useNBT) {
// We want to add the spacer if we have Custom Lore, to have a space between custom and brew lore.
// Also add a space if there is no Custom Lore but we don't already have a invisible data line
lore.add(i, Type.SPACE.id);
@ -115,9 +115,9 @@ public class BrewLore {
int quality = brew.getIngredients().getIngredientQuality(brew.getCurrentRecipe());
String prefix = getQualityColor(quality);
char icon = getQualityIcon(quality);
addOrReplaceLore(Type.INGR, prefix, P.p.languageReader.get("Brew_Ingredients"), " " + icon);
addOrReplaceLore(Type.INGR, prefix, BreweryPlugin.getInstance().languageReader.get("Brew_Ingredients"), " " + icon);
} else {
removeLore(Type.INGR, P.p.languageReader.get("Brew_Ingredients"));
removeLore(Type.INGR, BreweryPlugin.getInstance().languageReader.get("Brew_Ingredients"));
}
}
@ -130,13 +130,13 @@ public class BrewLore {
if (qualityColor && brew.hasRecipe() && brew.getDistillRuns() > 0 == brew.getCurrentRecipe().needsDistilling() && !brew.isStripped()) {
BIngredients ingredients = brew.getIngredients();
int quality = ingredients.getCookingQuality(brew.getCurrentRecipe(), brew.getDistillRuns() > 0);
String prefix = getQualityColor(quality) + ingredients.getCookedTime() + " " + P.p.languageReader.get("Brew_minute");
String prefix = getQualityColor(quality) + ingredients.getCookedTime() + " " + BreweryPlugin.getInstance().languageReader.get("Brew_minute");
if (ingredients.getCookedTime() > 1) {
prefix = prefix + P.p.languageReader.get("Brew_MinutePluralPostfix");
prefix = prefix + BreweryPlugin.getInstance().languageReader.get("Brew_MinutePluralPostfix");
}
addOrReplaceLore(Type.COOK, prefix, " " + P.p.languageReader.get("Brew_fermented"), " " + getQualityIcon(quality));
addOrReplaceLore(Type.COOK, prefix, " " + BreweryPlugin.getInstance().languageReader.get("Brew_fermented"), " " + getQualityIcon(quality));
} else {
removeLore(Type.COOK, P.p.languageReader.get("Brew_fermented"));
removeLore(Type.COOK, BreweryPlugin.getInstance().languageReader.get("Brew_fermented"));
}
}
@ -159,13 +159,13 @@ public class BrewLore {
}
if (!brew.isUnlabeled()) {
if (distillRuns > 1) {
prefix = prefix + distillRuns + P.p.languageReader.get("Brew_-times") + " ";
prefix = prefix + distillRuns + BreweryPlugin.getInstance().languageReader.get("Brew_-times") + " ";
}
}
if (brew.isUnlabeled() && brew.hasRecipe() && distillRuns < brew.getCurrentRecipe().getDistillRuns()) {
addOrReplaceLore(Type.DISTILL, prefix, P.p.languageReader.get("Brew_LessDistilled"), suffix);
addOrReplaceLore(Type.DISTILL, prefix, BreweryPlugin.getInstance().languageReader.get("Brew_LessDistilled"), suffix);
} else {
addOrReplaceLore(Type.DISTILL, prefix, P.p.languageReader.get("Brew_Distilled"), suffix);
addOrReplaceLore(Type.DISTILL, prefix, BreweryPlugin.getInstance().languageReader.get("Brew_Distilled"), suffix);
}
}
@ -188,14 +188,14 @@ public class BrewLore {
}
if (!brew.isUnlabeled()) {
if (age >= 1 && age < 2) {
prefix = prefix + P.p.languageReader.get("Brew_OneYear") + " ";
prefix = prefix + BreweryPlugin.getInstance().languageReader.get("Brew_OneYear") + " ";
} else if (age < 201) {
prefix = prefix + (int) Math.floor(age) + " " + P.p.languageReader.get("Brew_Years") + " ";
prefix = prefix + (int) Math.floor(age) + " " + BreweryPlugin.getInstance().languageReader.get("Brew_Years") + " ";
} else {
prefix = prefix + P.p.languageReader.get("Brew_HundredsOfYears") + " ";
prefix = prefix + BreweryPlugin.getInstance().languageReader.get("Brew_HundredsOfYears") + " ";
}
}
addOrReplaceLore(Type.AGE, prefix, P.p.languageReader.get("Brew_BarrelRiped"), suffix);
addOrReplaceLore(Type.AGE, prefix, BreweryPlugin.getInstance().languageReader.get("Brew_BarrelRiped"), suffix);
}
/**
@ -206,9 +206,9 @@ public class BrewLore {
public void updateWoodLore(boolean qualityColor) {
if (qualityColor && brew.hasRecipe() && !brew.isUnlabeled()) {
int quality = brew.getIngredients().getWoodQuality(brew.getCurrentRecipe(), brew.getWood());
addOrReplaceLore(Type.WOOD, getQualityColor(quality), P.p.languageReader.get("Brew_Woodtype"), " " + getQualityIcon(quality));
addOrReplaceLore(Type.WOOD, getQualityColor(quality), BreweryPlugin.getInstance().languageReader.get("Brew_Woodtype"), " " + getQualityIcon(quality));
} else {
removeLore(Type.WOOD, P.p.languageReader.get("Brew_Woodtype"));
removeLore(Type.WOOD, BreweryPlugin.getInstance().languageReader.get("Brew_Woodtype"));
}
}
@ -285,12 +285,20 @@ public class BrewLore {
public void updateAlc(boolean inDistiller) {
if (!brew.isUnlabeled() && (inDistiller || BConfig.alwaysShowAlc) && (!brew.hasRecipe() || brew.getCurrentRecipe().getAlcohol() != 0)) {
int alc = brew.getOrCalcAlc();
addOrReplaceLore(Type.ALC, "§8", P.p.languageReader.get("Brew_Alc", alc + ""));
addOrReplaceLore(Type.ALC, "§8", BreweryPlugin.getInstance().languageReader.get("Brew_Alc", alc + ""));
} else {
removeLore(Type.ALC);
}
}
public void updateBrewer(String name) {
if (name != null && BConfig.showBrewer) {
addOrReplaceLore(Type.BREWER, "§8", BreweryPlugin.getInstance().languageReader.get("Brew_Brewer", name));
} else {
removeLore(Type.BREWER);
}
}
/**
* Converts to/from qualitycolored Lore
*/
@ -445,7 +453,7 @@ public class BrewLore {
* Adds the Effect names to the Items description
*/
public void addOrReplaceEffects(List<BEffect> effects, int quality) {
if (!P.use1_9 && effects != null) {
if (!BreweryPlugin.use1_9 && effects != null) {
for (BEffect effect : effects) {
if (!effect.isHidden()) {
effect.writeInto(meta, quality);
@ -482,7 +490,7 @@ public class BrewLore {
* Remove the Old Spacer from the legacy potion data system
*/
public void removeLegacySpacing() {
if (P.useNBT) {
if (BreweryPlugin.useNBT) {
// Using NBT we don't get the invisible line, so we keep our spacing
return;
}
@ -539,7 +547,7 @@ public class BrewLore {
} else {
color = "&4";
}
return P.p.color(color);
return BreweryPlugin.getInstance().color(color);
}
/**
@ -577,7 +585,8 @@ public class BrewLore {
DISTILL("§p"),
AGE("§y"),
WOOD("§z"),
ALC("§q");
ALC("§q"),
BREWER("§g");
public final String id;

View File

@ -1,6 +1,6 @@
package com.dre.brewery.lore;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.LegacyUtil;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.meta.ItemMeta;
@ -9,7 +9,7 @@ import java.io.ByteArrayInputStream;
public class NBTLoadStream extends ByteArrayInputStream {
private static final String TAG = "brewdata";
private static final NamespacedKey KEY = new NamespacedKey(P.p, TAG);
private static final NamespacedKey KEY = new NamespacedKey(BreweryPlugin.getInstance(), TAG);
public NBTLoadStream(ItemMeta meta) {
super(getNBTBytes(meta));

View File

@ -1,6 +1,6 @@
package com.dre.brewery.lore;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.LegacyUtil;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.meta.ItemMeta;
@ -10,7 +10,7 @@ import java.io.IOException;
public class NBTSaveStream extends ByteArrayOutputStream {
private static final String TAG = "brewdata";
private static final NamespacedKey KEY = new NamespacedKey(P.p, TAG);
private static final NamespacedKey KEY = new NamespacedKey(BreweryPlugin.getInstance(), TAG);
private final ItemMeta meta;

View File

@ -1,6 +1,6 @@
package com.dre.brewery.lore;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import org.jetbrains.annotations.NotNull;
import java.io.FilterInputStream;
@ -66,7 +66,7 @@ public class XORUnscrambleStream extends FilterInputStream {
if (id == 0) {
running = false;
successType = SuccessType.UNSCRAMBLED;
P.p.debugLog("Unscrambled data");
BreweryPlugin.getInstance().debugLog("Unscrambled data");
return;
}
int parity = in.read();
@ -74,7 +74,7 @@ public class XORUnscrambleStream extends FilterInputStream {
boolean success = checkParity(parity);
if (success) {
successType = SuccessType.MAIN_SEED;
P.p.debugLog("Using main Seed to unscramble");
BreweryPlugin.getInstance().debugLog("Using main Seed to unscramble");
}
if (!success && prevSeeds != null) {
@ -83,7 +83,7 @@ public class XORUnscrambleStream extends FilterInputStream {
xorStream = new SeedInputStream(seed ^ id);
if (success = checkParity(parity)) {
successType = SuccessType.PREV_SEED;
P.p.debugLog("Had to use prevSeed to unscramble");
BreweryPlugin.getInstance().debugLog("Had to use prevSeed to unscramble");
break;
}
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.recipe;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.StringParser;
import com.dre.brewery.utility.Tuple;
import org.bukkit.Color;
@ -48,9 +48,9 @@ public class BCauldronRecipe {
String name = cfg.getString(id + ".name");
if (name != null) {
name = P.p.color(name);
name = BreweryPlugin.getInstance().color(name);
} else {
P.p.errorLog("Missing name for Cauldron-Recipe: " + id);
BreweryPlugin.getInstance().errorLog("Missing name for Cauldron-Recipe: " + id);
return null;
}
@ -58,7 +58,7 @@ public class BCauldronRecipe {
recipe.ingredients = BRecipe.loadIngredients(cfg, id);
if (recipe.ingredients == null || recipe.ingredients.isEmpty()) {
P.p.errorLog("No ingredients for Cauldron-Recipe: " + recipe.name);
BreweryPlugin.getInstance().errorLog("No ingredients for Cauldron-Recipe: " + recipe.name);
return null;
}
@ -81,18 +81,18 @@ public class BCauldronRecipe {
if (split.length == 1) {
minute = 10;
} else if (split.length == 2) {
minute = P.p.parseInt(split[1]);
minute = BreweryPlugin.getInstance().parseInt(split[1]);
} else {
P.p.errorLog("cookParticle: '" + entry + "' in: " + recipe.name);
BreweryPlugin.getInstance().errorLog("cookParticle: '" + entry + "' in: " + recipe.name);
return null;
}
if (minute < 1) {
P.p.errorLog("cookParticle: '" + entry + "' in: " + recipe.name);
BreweryPlugin.getInstance().errorLog("cookParticle: '" + entry + "' in: " + recipe.name);
return null;
}
PotionColor partCol = PotionColor.fromString(split[0]);
if (partCol == PotionColor.WATER && !split[0].equals("WATER")) {
P.p.errorLog("Color of cookParticle: '" + entry + "' in: " + recipe.name);
BreweryPlugin.getInstance().errorLog("Color of cookParticle: '" + entry + "' in: " + recipe.name);
return null;
}
recipe.particleColor.add(new Tuple<>(minute, partCol.getColor()));
@ -224,7 +224,7 @@ public class BCauldronRecipe {
double mod = Math.pow(0.1, tooMuch);
match *= mod;
}
P.p.debugLog("Match for Cauldron Recipe " + name + ": " + match);
BreweryPlugin.getInstance().debugLog("Match for Cauldron Recipe " + name + ": " + match);
return match;
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.recipe;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.utility.BUtil;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.PotionMeta;
@ -43,7 +43,7 @@ public class BEffect {
}
type = PotionEffectType.getByName(effect);
if (type == null) {
P.p.errorLog("Effect: " + effect + " does not exist!");
BreweryPlugin.getInstance().errorLog("Effect: " + effect + " does not exist!");
return;
}
@ -75,21 +75,21 @@ public class BEffect {
private void setLvl(String[] range) {
if (range.length == 1) {
maxlvl = (short) P.p.parseInt(range[0]);
maxlvl = (short) BreweryPlugin.getInstance().parseInt(range[0]);
minlvl = 1;
} else {
maxlvl = (short) P.p.parseInt(range[1]);
minlvl = (short) P.p.parseInt(range[0]);
maxlvl = (short) BreweryPlugin.getInstance().parseInt(range[1]);
minlvl = (short) BreweryPlugin.getInstance().parseInt(range[0]);
}
}
private void setDuration(String[] range) {
if (range.length == 1) {
maxduration = (short) P.p.parseInt(range[0]);
maxduration = (short) BreweryPlugin.getInstance().parseInt(range[0]);
minduration = (short) (maxduration / 8);
} else {
maxduration = (short) P.p.parseInt(range[1]);
minduration = (short) P.p.parseInt(range[0]);
maxduration = (short) BreweryPlugin.getInstance().parseInt(range[1]);
minduration = (short) BreweryPlugin.getInstance().parseInt(range[0]);
}
}
@ -102,7 +102,7 @@ public class BEffect {
}
duration *= 20;
if (!P.use1_14) {
if (!BreweryPlugin.use1_14) {
@SuppressWarnings("deprecation")
double modifier = type.getDurationModifier();
duration /= modifier;

View File

@ -2,7 +2,7 @@ package com.dre.brewery.recipe;
import com.dre.brewery.BIngredients;
import com.dre.brewery.Brew;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.filedata.BConfig;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.LegacyUtil;
@ -98,17 +98,17 @@ public class BRecipe {
recipe.name[0] = name[0];
}
} else {
P.p.errorLog(recipeId + ": Recipe Name missing or invalid!");
BreweryPlugin.getInstance().errorLog(recipeId + ": Recipe Name missing or invalid!");
return null;
}
if (recipe.getRecipeName() == null || recipe.getRecipeName().length() < 1) {
P.p.errorLog(recipeId + ": Recipe Name invalid");
BreweryPlugin.getInstance().errorLog(recipeId + ": Recipe Name invalid");
return null;
}
recipe.ingredients = loadIngredients(configSectionRecipes, recipeId);
if (recipe.ingredients == null || recipe.ingredients.isEmpty()) {
P.p.errorLog("No ingredients for: " + recipe.getRecipeName());
BreweryPlugin.getInstance().errorLog("No ingredients for: " + recipe.getRecipeName());
return null;
}
recipe.cookingTime = configSectionRecipes.getInt(recipeId + ".cookingtime", 1);
@ -127,7 +127,7 @@ public class BRecipe {
String col = configSectionRecipes.getString(recipeId + ".color", "BLUE");
recipe.color = PotionColor.fromString(col);
if (recipe.color == PotionColor.WATER && !col.equals("WATER")) {
P.p.errorLog("Invalid Color '" + col + "' in Recipe: " + recipe.getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid Color '" + col + "' in Recipe: " + recipe.getRecipeName());
return null;
}
@ -136,18 +136,18 @@ public class BRecipe {
recipe.servercmds = loadQualityStringList(configSectionRecipes, recipeId + ".servercommands", StringParser.ParseType.CMD);
recipe.playercmds = loadQualityStringList(configSectionRecipes, recipeId + ".playercommands", StringParser.ParseType.CMD);
recipe.drinkMsg = P.p.color(BUtil.loadCfgString(configSectionRecipes, recipeId + ".drinkmessage"));
recipe.drinkTitle = P.p.color(BUtil.loadCfgString(configSectionRecipes, recipeId + ".drinktitle"));
recipe.drinkMsg = BreweryPlugin.getInstance().color(BUtil.loadCfgString(configSectionRecipes, recipeId + ".drinkmessage"));
recipe.drinkTitle = BreweryPlugin.getInstance().color(BUtil.loadCfgString(configSectionRecipes, recipeId + ".drinktitle"));
if (configSectionRecipes.isString(recipeId + ".customModelData")) {
String[] cmdParts = configSectionRecipes.getString(recipeId + ".customModelData", "").split("/");
if (cmdParts.length == 3) {
recipe.cmData = new int[] {P.p.parseInt(cmdParts[0]), P.p.parseInt(cmdParts[1]), P.p.parseInt(cmdParts[2])};
recipe.cmData = new int[] {BreweryPlugin.getInstance().parseInt(cmdParts[0]), BreweryPlugin.getInstance().parseInt(cmdParts[1]), BreweryPlugin.getInstance().parseInt(cmdParts[2])};
if (recipe.cmData[0] == 0 && recipe.cmData[1] == 0 && recipe.cmData[2] == 0) {
P.p.errorLog("Invalid customModelData in Recipe: " + recipe.getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid customModelData in Recipe: " + recipe.getRecipeName());
recipe.cmData = null;
}
} else {
P.p.errorLog("Invalid customModelData in Recipe: " + recipe.getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid customModelData in Recipe: " + recipe.getRecipeName());
}
} else {
int cmd = configSectionRecipes.getInt(recipeId + ".customModelData", 0);
@ -163,7 +163,7 @@ public class BRecipe {
if (effect.isValid()) {
recipe.effects.add(effect);
} else {
P.p.errorLog("Error adding Effect to Recipe: " + recipe.getRecipeName());
BreweryPlugin.getInstance().errorLog("Error adding Effect to Recipe: " + recipe.getRecipeName());
}
}
}
@ -187,9 +187,9 @@ public class BRecipe {
String[] ingredParts = item.split("/");
int amount = 1;
if (ingredParts.length == 2) {
amount = P.p.parseInt(ingredParts[1]);
amount = BreweryPlugin.getInstance().parseInt(ingredParts[1]);
if (amount < 1) {
P.p.errorLog(recipeId + ": Invalid Item Amount: " + ingredParts[1]);
BreweryPlugin.getInstance().errorLog(recipeId + ": Invalid Item Amount: " + ingredParts[1]);
return null;
}
}
@ -202,7 +202,7 @@ public class BRecipe {
matParts = ingredParts[0].split("\\.");
}
if (!P.use1_14 && matParts[0].equalsIgnoreCase("sweet_berries")) {
if (!BreweryPlugin.use1_14 && matParts[0].equalsIgnoreCase("sweet_berries")) {
// Using this in default recipes, but will error on < 1.14
ingredients.add(new SimpleItem(Material.BEDROCK));
continue;
@ -220,7 +220,7 @@ public class BRecipe {
continue;
} else {
// TODO Maybe load later ie on first use of recipe?
P.p.errorLog(recipeId + ": Could not Find Plugin: " + ingredParts[1]);
BreweryPlugin.getInstance().errorLog(recipeId + ": Could not Find Plugin: " + ingredParts[1]);
return null;
}
}
@ -254,7 +254,7 @@ public class BRecipe {
Material mat = Material.matchMaterial(matParts[0]);
short durability = -1;
if (matParts.length == 2) {
durability = (short) P.p.parseInt(matParts[1]);
durability = (short) BreweryPlugin.getInstance().parseInt(matParts[1]);
}
if (mat == null && BConfig.hasVault) {
try {
@ -271,7 +271,7 @@ public class BRecipe {
}
}
} catch (Exception e) {
P.p.errorLog("Could not check vault for Item Name");
BreweryPlugin.getInstance().errorLog("Could not check vault for Item Name");
e.printStackTrace();
}
}
@ -288,7 +288,7 @@ public class BRecipe {
BCauldronRecipe.acceptedMaterials.add(mat);
BCauldronRecipe.acceptedSimple.add(mat);
} else {
P.p.errorLog(recipeId + ": Unknown Material: " + ingredParts[0]);
BreweryPlugin.getInstance().errorLog(recipeId + ": Unknown Material: " + ingredParts[0]);
return null;
}
}
@ -312,31 +312,31 @@ public class BRecipe {
*/
public boolean isValid() {
if (ingredients == null || ingredients.isEmpty()) {
P.p.errorLog("No ingredients could be loaded for Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("No ingredients could be loaded for Recipe: " + getRecipeName());
return false;
}
if (cookingTime < 1) {
P.p.errorLog("Invalid cooking time '" + cookingTime + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid cooking time '" + cookingTime + "' in Recipe: " + getRecipeName());
return false;
}
if (distillruns < 0) {
P.p.errorLog("Invalid distillruns '" + distillruns + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid distillruns '" + distillruns + "' in Recipe: " + getRecipeName());
return false;
}
if (distillTime < 0) {
P.p.errorLog("Invalid distilltime '" + distillTime + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid distilltime '" + distillTime + "' in Recipe: " + getRecipeName());
return false;
}
if (wood < 0 || wood > LegacyUtil.TOTAL_WOOD_TYPES) {
P.p.errorLog("Invalid wood type '" + wood + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid wood type '" + wood + "' in Recipe: " + getRecipeName());
return false;
}
if (age < 0) {
P.p.errorLog("Invalid age time '" + age + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid age time '" + age + "' in Recipe: " + getRecipeName());
return false;
}
if (difficulty < 0 || difficulty > 10) {
P.p.errorLog("Invalid difficulty '" + difficulty + "' in Recipe: " + getRecipeName());
BreweryPlugin.getInstance().errorLog("Invalid difficulty '" + difficulty + "' in Recipe: " + getRecipeName());
return false;
}
return true;
@ -423,7 +423,7 @@ public class BRecipe {
List<String> serverCmdsForQuality = getServercmdsForQuality(quality);
if (serverCmdsForQuality != null) {
for (String cmd : serverCmdsForQuality) {
P.p.getServer().dispatchCommand(P.p.getServer().getConsoleSender(), BUtil.applyPlaceholders(cmd, player.getName(), quality));
BreweryPlugin.getInstance().getServer().dispatchCommand(BreweryPlugin.getInstance().getServer().getConsoleSender(), BUtil.applyPlaceholders(cmd, player.getName(), quality));
}
}
if (drinkMsg != null) {

View File

@ -1,6 +1,6 @@
package com.dre.brewery.recipe;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
@ -24,6 +24,7 @@ public class CustomItem extends RecipeItem implements Ingredient {
private Material mat;
private String name;
private List<String> lore;
private int customModelData = 0;
public CustomItem() {
}
@ -38,6 +39,13 @@ public class CustomItem extends RecipeItem implements Ingredient {
this.lore = lore;
}
public CustomItem(Material mat, String name, List<String> lore, int customModelData) {
this.mat = mat;
this.name = name;
this.lore = lore;
this.customModelData = customModelData;
}
public CustomItem(ItemStack item) {
mat = item.getType();
if (!item.hasItemMeta()) {
@ -66,6 +74,10 @@ public class CustomItem extends RecipeItem implements Ingredient {
return lore != null && !lore.isEmpty();
}
public boolean hasCustomModelData() {
return customModelData != 0;
}
@Override
public List<Material> getMaterials() {
List<Material> l = new ArrayList<>(1);
@ -100,6 +112,14 @@ public class CustomItem extends RecipeItem implements Ingredient {
this.lore = lore;
}
public int getCustomModelData() {
return customModelData;
}
protected void setCustomModelData(int customModelData) {
this.customModelData = customModelData;
}
@NotNull
@Override
public Ingredient toIngredient(ItemStack forItem) {
@ -123,11 +143,13 @@ public class CustomItem extends RecipeItem implements Ingredient {
// If the recipe item is just a simple item, only match if we also only define material
// If this is a custom item with more info, we don't want to match a simple item
return hasMaterials() && !hasLore() && !hasName() && getMaterial() == ((SimpleItem) rItem).getMaterial();
} else if (rItem instanceof CustomItem) {
} else if (rItem instanceof CustomItem other) {
// If the other is a CustomItem as well and not Similar to ours, it might have more data and we still match
CustomItem other = ((CustomItem) rItem);
if (mat == null || mat == other.mat) {
if (mat == null || mat == other.mat) {
if (!hasName() || (other.name != null && name.equalsIgnoreCase(other.name))) {
if (hasCustomModelData() && customModelData != other.customModelData) {
return false;
}
return !hasLore() || lore == other.lore || (other.hasLore() && matchLore(other.lore));
}
}
@ -163,6 +185,10 @@ public class CustomItem extends RecipeItem implements Ingredient {
}
return matchLore(meta.getLore());
}
if (customModelData != 0) {
return meta.hasCustomModelData() && meta.getCustomModelData() == customModelData;
}
return true;
}
@ -204,9 +230,8 @@ public class CustomItem extends RecipeItem implements Ingredient {
if (this == item) {
return true;
}
if (item instanceof CustomItem) {
CustomItem ci = ((CustomItem) item);
return mat == ci.mat && Objects.equals(name, ci.name) && Objects.equals(lore, ci.lore);
if (item instanceof CustomItem ci) {
return mat == ci.mat && Objects.equals(name, ci.name) && Objects.equals(lore, ci.lore) && customModelData == ci.customModelData;
}
return false;
}
@ -222,7 +247,7 @@ public class CustomItem extends RecipeItem implements Ingredient {
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), mat, name, lore);
return Objects.hash(super.hashCode(), mat, name, lore, customModelData);
}
@Override
@ -232,6 +257,7 @@ public class CustomItem extends RecipeItem implements Ingredient {
", mat=" + (mat != null ? mat.name().toLowerCase() : "null") +
", name='" + name + '\'' +
", loresize: " + (lore != null ? lore.size() : 0) +
", modelData=" + customModelData +
'}';
}
@ -259,6 +285,12 @@ public class CustomItem extends RecipeItem implements Ingredient {
} else {
out.writeShort(0);
}
if (customModelData != 0) {
out.writeBoolean(true);
out.writeInt(customModelData);
} else {
out.writeBoolean(false);
}
}
public static CustomItem loadFrom(ItemLoader loader) {
@ -278,6 +310,9 @@ public class CustomItem extends RecipeItem implements Ingredient {
item.lore.add(in.readUTF());
}
}
if (in.readBoolean()) {
item.customModelData = in.readInt();
}
return item;
} catch (IOException e) {
e.printStackTrace();
@ -286,7 +321,7 @@ public class CustomItem extends RecipeItem implements Ingredient {
}
// Needs to be called at Server start
public static void registerItemLoader(P p) {
p.registerForItemLoader("CI", CustomItem::loadFrom);
public static void registerItemLoader(BreweryPlugin breweryPlugin) {
breweryPlugin.registerForItemLoader("CI", CustomItem::loadFrom);
}
}

View File

@ -20,6 +20,7 @@ public class CustomMatchAnyItem extends RecipeItem {
private List<Material> materials;
private List<String> names;
private List<String> lore;
private List<Integer> customModelDatas;
@Override
@ -35,6 +36,10 @@ public class CustomMatchAnyItem extends RecipeItem {
return lore != null && !lore.isEmpty();
}
public boolean hasCustomModelDatas() {
return customModelDatas != null && !customModelDatas.isEmpty();
}
@Override
@Nullable
public List<Material> getMaterials() {
@ -63,6 +68,16 @@ public class CustomMatchAnyItem extends RecipeItem {
this.lore = lore;
}
@Nullable
public List<Integer> getCustomModelDatas() {
return customModelDatas;
}
protected void setCustomModelDatas(List<Integer> customModelDatas) {
this.customModelDatas = customModelDatas;
}
@NotNull
@Override
public Ingredient toIngredient(ItemStack forItem) {
@ -100,6 +115,9 @@ public class CustomMatchAnyItem extends RecipeItem {
l.add(lore.get(0));
return new CustomItem(null, null, l);
}
if (hasCustomModelDatas()) {
return new CustomItem(null, null, null, customModelDatas.get(0));
}
// Shouldnt happen
return new SimpleItem(Material.GOLDEN_HOE);
@ -165,6 +183,29 @@ public class CustomMatchAnyItem extends RecipeItem {
return null;
}
public int getCustomModelDataMatch(ItemStack item) {
if (!item.hasItemMeta() || !hasCustomModelDatas()) {
return 0;
}
ItemMeta meta = item.getItemMeta();
assert meta != null;
if (meta.hasCustomModelData()) {
return getCustomModelDataMatch(meta.getCustomModelData());
}
return 0;
}
public int getCustomModelDataMatch(int usedCustomModelData) {
if (!hasCustomModelDatas()) return 0;
for (int customModelData : this.customModelDatas) {
if (customModelData == usedCustomModelData) {
return customModelData;
}
}
return 0;
}
@Override
public boolean matches(ItemStack item) {
if (getMaterialMatch(item) != null) {
@ -173,7 +214,10 @@ public class CustomMatchAnyItem extends RecipeItem {
if (getNameMatch(item) != null) {
return true;
}
return getLoreMatch(item) != null;
if (getLoreMatch(item) != null) {
return true;
}
return getCustomModelDataMatch(item) != 0;
}
@Override
@ -195,10 +239,12 @@ public class CustomMatchAnyItem extends RecipeItem {
if (hasLore() && ci.hasLore()) {
return getLoreMatch(ci.getLore()) != null;
}
} else if (ingredient instanceof SimpleItem) {
if (hasCustomModelDatas() && ci.hasCustomModelData()) {
return getCustomModelDataMatch(ci.getCustomModelData()) != 0;
}
} else if (ingredient instanceof SimpleItem si) {
// If we contain the Material of the Simple Item, we match
SimpleItem si = (SimpleItem) ingredient;
return hasMaterials() && materials.contains(si.getMaterial());
return hasMaterials() && materials.contains(si.getMaterial());
}
return false;
}
@ -211,12 +257,13 @@ public class CustomMatchAnyItem extends RecipeItem {
CustomMatchAnyItem that = (CustomMatchAnyItem) o;
return Objects.equals(materials, that.materials) &&
Objects.equals(names, that.names) &&
Objects.equals(lore, that.lore);
Objects.equals(lore, that.lore) &&
Objects.equals(customModelDatas, that.customModelDatas);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), materials, names, lore);
return Objects.hash(super.hashCode(), materials, names, lore, customModelDatas);
}
@Override
@ -226,6 +273,7 @@ public class CustomMatchAnyItem extends RecipeItem {
", materials: " + (materials != null ? materials.size() : 0) +
", names:" + (names != null ? names.size() : 0) +
", loresize: " + (lore != null ? lore.size() : 0) +
", customDatas: " + (customModelDatas != null ? customModelDatas.size() : 0) +
'}';
}
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.recipe;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@ -165,8 +165,8 @@ public abstract class PluginItem extends RecipeItem implements Ingredient {
* Registers the chosen SaveID and the loading Method for loading from Brew or BCauldron.
* <p>Needs to be called at Server start.
*/
public static void registerItemLoader(P p) {
p.registerForItemLoader("PI", PluginItem::loadFrom);
public static void registerItemLoader(BreweryPlugin breweryPlugin) {
breweryPlugin.registerForItemLoader("PI", PluginItem::loadFrom);
}

View File

@ -1,6 +1,6 @@
package com.dre.brewery.recipe;
import com.dre.brewery.P;
import com.dre.brewery.BreweryPlugin;
import org.bukkit.Color;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
@ -19,7 +19,7 @@ public class PotionColor {
public static final PotionColor BLACK = new PotionColor(8, PotionType.WEAKNESS, Color.BLACK);
public static final PotionColor RED = new PotionColor(9, PotionType.STRENGTH, Color.fromRGB(196,0,0));
public static final PotionColor GREY = new PotionColor(10, PotionType.SLOWNESS, Color.GRAY);
public static final PotionColor WATER = new PotionColor(11, P.use1_9 ? PotionType.WATER_BREATHING : null, Color.BLUE);
public static final PotionColor WATER = new PotionColor(11, BreweryPlugin.use1_9 ? PotionType.WATER_BREATHING : null, Color.BLUE);
public static final PotionColor DARK_RED = new PotionColor(12, PotionType.INSTANT_DAMAGE, Color.fromRGB(128,0,0));
public static final PotionColor BRIGHT_GREY = new PotionColor(14, PotionType.INVISIBILITY, Color.SILVER);
public static final PotionColor WHITE = new PotionColor(Color.WHITE);
@ -65,10 +65,10 @@ public class PotionColor {
@SuppressWarnings("deprecation")
public void colorBrew(PotionMeta meta, ItemStack potion, boolean destillable) {
if (P.use1_9) {
if (BreweryPlugin.use1_9) {
// We need to Hide Potion Effects even in 1.12, as it would otherwise show "No Effects"
meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS);
if (P.use1_11) {
if (BreweryPlugin.use1_11) {
// BasePotionData was only used for the Color, so starting with 1.12 we can use setColor instead
meta.setColor(getColor());
} else {

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