5 Commits
2.2 ... 2.5

Author SHA1 Message Date
673ed06998 README.md aktualisiert 2026-03-04 09:13:51 +00:00
4d805abebe LICENSE gelöscht 2026-03-01 11:15:29 +00:00
9f06c73591 README.md aktualisiert 2026-03-01 11:15:21 +00:00
aa418921db Upload pom.xml via GUI 2026-02-25 18:02:14 +00:00
62e5c3d7f1 Update from Git Manager GUI 2026-02-25 19:02:12 +01:00
7 changed files with 826 additions and 351 deletions

117
LICENSE
View File

@@ -1,117 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

206
README.md
View File

@@ -16,22 +16,28 @@ Schluss mit unordentlichen Truhen und stundenlangem Sortieren! **AutoSortChest**
## ✨ Features ## ✨ Features
- **Einfache Schild-Steuerung:** Erstelle Input-, Ziel- und Rest-Truhen durch das Platzieren eines Schildes. - **Einfache Schild-Steuerung:** Erstelle Input-, Ziel-, Rest- und Mülltruhen durch das Platzieren eines Schildes.
- **Visuelles Status-System:** Schilder ändern ihre Farbe, wenn eine Truhe voll ist, und senden Warnungen im Chat. - **Visuelles Status-System:** Schilder ändern ihre Farbe, wenn eine Truhe voll ist, und senden Warnungen im Chat.
- **Smart Rest-Truhe (Fallback):** Konfiguriere eine Auffangtruhe für alle Items ohne spezielles Ziel. - **Smart Rest-Truhe (Fallback):** Konfiguriere mehrere Auffangtruhen für alle Items ohne spezielles Ziel.
- **Mülltruhe:** Definiere eine Truhe, die bestimmte oder alle Items automatisch vernichtet mit konfigurierbarer Filter-Liste und optionalem Auto-Clear-Intervall.
- **Dynamic Item Update:** Ändere das sortierte Item einer Truhe jederzeit per Rechtsklick kein Abbauen nötig! - **Dynamic Item Update:** Ändere das sortierte Item einer Truhe jederzeit per Rechtsklick kein Abbauen nötig!
- **Mehrere Zieltruhen pro Item:** Definiere mehrere Zieltruhen für denselben Item-Typ volle Truhen werden automatisch übersprungen.
- **Privatsphäre-Modus:** Schalte Truhen per Shift-Rechtsklick zwischen Öffentlich und Privat um. - **Privatsphäre-Modus:** Schalte Truhen per Shift-Rechtsklick zwischen Öffentlich und Privat um.
- **Hopper-Schutz:** Input- und Rest-Truhen blockieren Hopper automatisch Sortierung läuft ausschließlich über das ASC-System.
- **Clean-Modus:** Optionaler sauberer Schild-Stil ohne sichtbaren Item-Namen übersichtlicheres Aussehen im Lager.
- **Visuelle Effekte:** Optionale Partikel- und Sound-Effekte beim Sortiervorgang.
- **Server-übergreifend (CrossLink):** Mit MySQL können Zieltruhen auf anderen Servern des Netzwerks liegen. Items werden automatisch via Transfer-Tabelle weitergeleitet. - **Server-übergreifend (CrossLink):** Mit MySQL können Zieltruhen auf anderen Servern des Netzwerks liegen. Items werden automatisch via Transfer-Tabelle weitergeleitet.
- **Import & Export:** Daten lassen sich bequem zwischen `players.yml` und MySQL hin- und herwechseln per Admin-Befehl. - **Import & Export:** Daten lassen sich bequem zwischen `players.yml` und MySQL hin- und herwechseln per Admin-Befehl.
- **Update-Checker:** Admins werden beim Login automatisch über neue Versionen informiert.
- **Multiplayer-Optimiert:** Jeder Spieler verwaltet sein eigenes System kein gegenseitiges Stören. - **Multiplayer-Optimiert:** Jeder Spieler verwaltet sein eigenes System kein gegenseitiges Stören.
- **Vollständig Anpassbar:** Alle Nachrichten, Farben und Limits lassen sich in der `config.yml` editieren. - **Vollständig Anpassbar:** Alle Nachrichten, Farben, Titel und Limits lassen sich in der `config.yml` editieren.
--- ---
## 📖 Einrichtung ## 📖 Einrichtung
### 1. Eingangstruhe (Input) ### 1. Eingangstruhe (Input)
Hier wirfst du alle unsortierten Items hinein. Hier wirfst du alle unsortierten Items hinein. Hopper können keine Items direkt einlegen die Sortierung läuft ausschließlich über den eigenen Mechanismus.
Schild an die Truhe platzieren und folgendes schreiben: Schild an die Truhe platzieren und folgendes schreiben:
``` ```
@@ -52,14 +58,33 @@ ziel
``` ```
Danach mit dem gewünschten Item (z. B. Diamant) auf das Schild **Rechtsklicken** der Item-Typ wird automatisch eingetragen. Danach mit dem gewünschten Item (z. B. Diamant) auf das Schild **Rechtsklicken** der Item-Typ wird automatisch eingetragen.
> Sind mehrere Zieltruhen für denselben Item-Typ vorhanden, wird die nächste automatisch befüllt, wenn die erste voll ist.
--- ---
### 3. Rest-Truhe (Fallback) ### 3. Rest-Truhe (Fallback)
Das Auffangbecken für alle Items ohne Zieltruhe. Das Auffangbecken für alle Items ohne Zieltruhe. Hopper können keine Items einlegen.
``` ```
[asc] [asc]
rest rest
``` ```
> Es können mehrere Rest-Truhen registriert werden. Sind alle voll, bleibt das Item in der Eingangstruhe.
---
### 4. Mülltruhe (Trash)
Items, die in diese Truhe gelangen, werden automatisch vernichtet.
```
[asc]
trash
```
Nach dem Platzieren des Schildes erscheint ein **Rechtsklick-Hinweis**. Durch Rechtsklick auf das Schild öffnet sich ein Konfiguration-GUI:
- **Ohne Filter-Liste:** Alle Items in der Truhe werden gelöscht.
- **Mit Filter-Liste:** Nur die eingetragenen Item-Typen werden gelöscht, der Rest bleibt erhalten.
- Items können per Rechtsklick zur Liste hinzugefügt oder entfernt werden.
- Der **Auto-Clear-Intervall** lässt sich in der `config.yml` einstellen (z. B. alle 5 Minuten).
- Auch Items, die per **Hopper** eingeworfen werden, werden sofort verarbeitet.
--- ---
@@ -68,6 +93,8 @@ rest
| Aktion | Beschreibung | | Aktion | Beschreibung |
|--------|-------------| |--------|-------------|
| **Shift + Rechtsklick** (leere Hand) auf Schild/Truhe | Wechselt zwischen Privat und Öffentlich | | **Shift + Rechtsklick** (leere Hand) auf Schild/Truhe | Wechselt zwischen Privat und Öffentlich |
| **Rechtsklick** auf Ziel-Schild (Item in Hand) | Ändert den zugeordneten Item-Typ |
| **Rechtsklick** auf Mülltruhen-Schild | Öffnet das Filter-Konfiguration-GUI |
| **Privat** | Nur der Besitzer kann die Truhe nutzen. Sortierung nur bei Online-Status. | | **Privat** | Nur der Besitzer kann die Truhe nutzen. Sortierung nur bei Online-Status. |
| **Öffentlich** | Alle Spieler dürfen Items einwerfen. Sortierung auch offline. Schild zeigt `[Public]`. | | **Öffentlich** | Alle Spieler dürfen Items einwerfen. Sortierung auch offline. Schild zeigt `[Public]`. |
@@ -76,6 +103,21 @@ rest
--- ---
## 🎨 Clean-Modus
Wenn `sign-style.clean-target: true` in der `config.yml` gesetzt ist, werden Schilder in einem aufgeräumten Format ohne sichtbare `[asc]`-Kennung angezeigt:
| Schild-Typ | Zeile 1 | Zeile 2 | Zeile 3 |
|-----------|---------|---------|---------|
| **Input** | Spielername | „Eingang" / „Input" | Öffentlich / Privat |
| **Target** | Item-Name | Spielername | Öffentlich / Privat |
| **Rest** | Spielername | „Rest" | Öffentlich / Privat |
| **Trash** | Spielername | „Müll" / „Trash" | — |
Die Farben für den Clean-Modus werden separat unter `sign-colors-clean` konfiguriert.
---
## 🌐 Serverübergreifende Sortierung (CrossLink) ## 🌐 Serverübergreifende Sortierung (CrossLink)
Wenn MySQL aktiviert und `server_crosslink: true` gesetzt ist, können Zieltruhen auf **anderen Servern desselben Netzwerks** liegen. Wenn MySQL aktiviert und `server_crosslink: true` gesetzt ist, können Zieltruhen auf **anderen Servern desselben Netzwerks** liegen.
@@ -85,6 +127,14 @@ Wenn MySQL aktiviert und `server_crosslink: true` gesetzt ist, können Zieltruhe
2. Server A schreibt den Transfer in die gemeinsame Datenbank (`asc_transfers`). 2. Server A schreibt den Transfer in die gemeinsame Datenbank (`asc_transfers`).
3. Server B liest die Transfer-Tabelle und befüllt seine lokale Zieltruhe automatisch. 3. Server B liest die Transfer-Tabelle und befüllt seine lokale Zieltruhe automatisch.
**BungeeCord-Setup:**
1. Dieselbe MySQL-Datenbank auf allen Servern eintragen.
2. Auf jedem Server einen **eindeutigen** `server_name` setzen (z. B. `survival`, `creative`).
3. `mysql.enabled: true` und `server_crosslink: true` setzen.
4. Alle Server neu starten das Schema wird automatisch migriert.
> Wird `server_name` leer gelassen, läuft das Plugin im Legacy-Modus (welt-basierte Erkennung, kein BungeeCord).
**Voraussetzung:** Alle Server müssen dieselbe MySQL-Datenbank nutzen. **Voraussetzung:** Alle Server müssen dieselbe MySQL-Datenbank nutzen.
--- ---
@@ -99,6 +149,21 @@ Wenn MySQL aktiviert und `server_crosslink: true` gesetzt ist, können Zieltruhe
| `/asc import` | Importiert Daten aus `players.yml` → MySQL | `autosortchest.import` (OP) | | `/asc import` | Importiert Daten aus `players.yml` → MySQL | `autosortchest.import` (OP) |
| `/asc export` | Exportiert Daten aus MySQL → `players.yml` | `autosortchest.export` (OP) | | `/asc export` | Exportiert Daten aus MySQL → `players.yml` | `autosortchest.export` (OP) |
### Berechtigungen Vollständige Übersicht
| Permission | Beschreibung | Standard |
|-----------|-------------|---------|
| `autosortchest.use` | Erlaubt das Erstellen von ASC-Schildern | `true` |
| `autosortchest.reload` | Erlaubt `/asc reload` | OP |
| `autosortchest.import` | Erlaubt `/asc import` | OP |
| `autosortchest.export` | Erlaubt `/asc export` | OP |
| `autosortchest.bypass` | Schilder ohne Shift abbauen, unabhängig vom Besitzer | OP |
| `autosortchest.limit.bypass` | Umgeht alle Truhen-Limits | OP |
| `autosortchest.admin` | Zugriff auf fremde ASC-Truhen | OP |
| `autosortchest.limit.<gruppe>` | Weist dem Spieler die Limits einer Gruppe zu (z. B. `autosortchest.limit.vip`) | `false` |
> Spieler **ohne** jede `autosortchest.limit.*`-Permission können bei aktivierten Limits **keine** Truhen erstellen. Vergib `autosortchest.limit.default` an alle normalen Spieler (z. B. in LuckPerms).
### Import & Export Details ### Import & Export Details
**`/asc import`** **`/asc import`**
@@ -110,13 +175,17 @@ Exportiert alle Daten aus MySQL zurück in die `players.yml`. Enthält die `play
--- ---
## ⚙️ Konfiguration (config.yml) ## ⚙️ Konfiguration (config.yml)
```yaml ```yaml
# Version der Konfigurationsdatei # Version der Konfigurationsdatei
version: "2.0" version: "2.3"
# Debug-Modus (nur für Entwicklung) # Debug-Modus (nur für Entwicklung)
debug: false debug: false
# Sprache: 'de' oder 'en'
language: "de"
# MySQL/MariaDB für CrossLink und zentralen Datenspeicher # MySQL/MariaDB für CrossLink und zentralen Datenspeicher
mysql: mysql:
enabled: false enabled: false
@@ -129,8 +198,10 @@ mysql:
# Serverübergreifende Sortierung (benötigt MySQL) # Serverübergreifende Sortierung (benötigt MySQL)
server_crosslink: true server_crosslink: true
# Sprache: 'de' oder 'en' # Eindeutiger Servername im BungeeCord-Netzwerk
language: "de" # Leer lassen = Legacy-Modus (welt-basiert, kein BungeeCord)
# Beispiele: lobby | survival | creative
server_name: ""
# Welten, in denen das Plugin deaktiviert ist # Welten, in denen das Plugin deaktiviert ist
world_blacklist: world_blacklist:
@@ -138,24 +209,69 @@ world_blacklist:
- "world_the_end" - "world_the_end"
# Sortier-Intervall in Ticks (1 Tick = 0,05s) # Sortier-Intervall in Ticks (1 Tick = 0,05s)
sort_interval_ticks: 5 # Empfohlen: 10 (= 0,5s)
sort_interval_ticks: 10
# Maximale Anzahl Zieltruhen pro Spielergruppe # Rest-Truhen Nachsortierung (0 = deaktiviert)
rest_resort_interval_ticks: 400 # 400 Ticks = 20 Sekunden
# Mülltruhe
trash:
# 0 = Nur beim Schließen leeren | 300 = alle 5 Min | 3600 = stündlich
auto_clear_interval_seconds: 0
# Visuelle Effekte
effects:
enabled: false # Partikel-Effekte anzeigen?
sound: false # Ton beim Ankommen von Items?
type: "DUST" # Partikel-Typ ('DUST' = bunter Regenbogen-Effekt)
# Schild-Stil
sign-style:
clean-target: false # true = sauberer Modus (kein Item-Name auf dem Schild)
# Maximale Anzahl Truhen pro Spielergruppe
chest_limits: chest_limits:
default: 5 enabled: true
vip: 100
default:
input: 1
rest: 1
target: 50
target_per_item: 1 # Wie viele Zieltruhen pro Item-Typ erlaubt sind
vip:
input: 2
rest: 2
target: 100
target_per_item: 3
# Truhen-Fenstertitel (Platzhalter: %item%)
chest-titles:
input:
de: "&6Eingangstruhe"
en: "&6Input Chest"
target:
de: "&6%item%"
en: "&6%item%"
rest:
de: "&6Rest-Truhe"
en: "&6Rest Chest"
trash:
de: "&4Mülltruhe"
en: "&4Trash Chest"
# Schildfarben (Minecraft-Farbcodes) # Schildfarben (Minecraft-Farbcodes)
sign-colors: sign-colors:
input: input:
line1: "&6" # [asc] line1: "&6"
line2: "&0" # input line2: "&0"
line4: "&1" # Spielername line4: "&1"
target: target:
line1: "&6" # [asc] line1: "&6"
line2: "&0" # ziel line2: "&0"
line3: "&f" # Item-Typ line3: "&f"
line4: "&1" # Spielername line4: "&1"
full: full:
line1: "&c" line1: "&c"
line2: "&4" line2: "&4"
@@ -166,8 +282,34 @@ sign-colors:
line2: "&0" line2: "&0"
line3: "&f" line3: "&f"
line4: "&1" line4: "&1"
trash:
line1: "&6"
line2: "&0"
line4: "&1"
# Nachrichten # Schildfarben im Clean-Modus
sign-colors-clean:
input:
line1: "&1"
line2: "&0"
line3: "&a"
target:
line1: "&f"
line2: "&1"
line3: "&a"
full:
line1: "&e"
line2: "&1"
line3: "&a"
rest:
line1: "&1"
line2: "&0"
line3: "&a"
trash:
line1: "&1"
line2: "&0"
# Nachrichten (Platzhalter: %player%, %item%, %x%, %y%, %z%, %mode%, %max%)
messages: messages:
no-chest-near-sign: "&cKeine Truhe in der Nähe des Schildes!" no-chest-near-sign: "&cKeine Truhe in der Nähe des Schildes!"
no-item-in-hand: "&cDu musst ein Item in der Hand halten!" no-item-in-hand: "&cDu musst ein Item in der Hand halten!"
@@ -175,14 +317,28 @@ messages:
input-chest-set: "&aEingangstruhe erfolgreich gesetzt!" input-chest-set: "&aEingangstruhe erfolgreich gesetzt!"
target-chest-set: "&aZieltruhe erfolgreich für %item% eingerichtet!" target-chest-set: "&aZieltruhe erfolgreich für %item% eingerichtet!"
rest-chest-set: "&aRest-Truhe (Fallback) erfolgreich gesetzt!" rest-chest-set: "&aRest-Truhe (Fallback) erfolgreich gesetzt!"
trash-chest-set: "&aMülltruhe erfolgreich eingerichtet!"
trash-chest-hint: "&7Rechtsklicke das Schild um Items zu konfigurieren."
target-chest-missing: "&cZieltruhe für %item% fehlt!" target-chest-missing: "&cZieltruhe für %item% fehlt!"
target-chest-full: "&cZieltruhe für %item% ist voll! Koordinaten: (%x%, %y%, %z%)" target-chest-full: "&cZieltruhe für %item% ist voll! Koordinaten: (%x%, %y%, %z%)"
sign-break-denied: "&cDu musst Shift gedrückt halten, um dieses Schild oder die Truhe abzubauen!" sign-break-denied: "&cDu musst Shift gedrückt halten, um dieses Schild oder die Truhe abzubauen!"
no-permission: "&cDu hast keine Berechtigung für diesen Befehl!" no-permission: "&cDu hast keine Berechtigung für diesen Befehl!"
world-blacklisted: "&cIn dieser Welt kannst du keine AutoSortChest erstellen!"
reload-success: "&aKonfiguration erfolgreich neu geladen!" reload-success: "&aKonfiguration erfolgreich neu geladen!"
mode-changed: "&aModus gewechselt: &e%mode%" mode-changed: "&aModus gewechselt: &e%mode%"
mode-public: "&aÖffentlich" mode-public: "&aÖffentlich"
mode-private: "&cPrivat" mode-private: "&cPrivat"
limit-input-reached: "&cDu hast das Limit deiner Eingangstruhen erreicht! &7(%max%)"
limit-rest-reached: "&cDu hast das Limit deiner Rest-Truhen erreicht! &7(%max%)"
limit-target-reached: "&cDu hast das Limit deiner Zieltruhen erreicht! &7(%max%)"
limit-target-per-item: "&cDu hast das Limit für %item%-Truhen erreicht! &7(%max%)"
limit-no-permission: "&cDu hast keine Berechtigung um Truhen zu erstellen!"
trash-cleared: "&a✔ Mülltruhe wurde geleert!"
trash-item-added: "&a✔ &e%item% &azur Müll-Liste hinzugefügt."
trash-item-already: "&eDiseses Item ist bereits in der Müll-Liste."
trash-item-removed: "&c✖ &e%item% &caus der Müll-Liste entfernt."
trash-info-empty: "&4Mülltruhe &8(Deaktiviert) &7 Rechtsklick Schild zum Konfigurieren"
trash-info-filter: "&4Müll: &f%items% &8| Schild-Rechtsklick: Konfigurieren"
``` ```
--- ---
@@ -195,8 +351,10 @@ Bei aktiviertem MySQL erstellt das Plugin folgende Tabellen automatisch:
|---------|--------| |---------|--------|
| `asc_players` | Spieler-UUIDs und Namen | | `asc_players` | Spieler-UUIDs und Namen |
| `asc_input_chests` | Registrierte Eingangstruhen | | `asc_input_chests` | Registrierte Eingangstruhen |
| `asc_target_chests` | Zieltruhen mit Item-Zuordnung | | `asc_target_chests` | Zieltruhen mit Item-Zuordnung und Slot-Index |
| `asc_rest_chests` | Rest-/Fallback-Truhen | | `asc_rest_chests` | Rest-/Fallback-Truhen |
| `asc_trash_chests` | Mülltruhen mit Serverzuordnung |
| `asc_trash_items` | Filter-Listen der Mülltruhen |
| `asc_transfers` | Ausstehende CrossLink-Transfers zwischen Servern | | `asc_transfers` | Ausstehende CrossLink-Transfers zwischen Servern |
--- ---
@@ -206,7 +364,7 @@ Bei aktiviertem MySQL erstellt das Plugin folgende Tabellen automatisch:
- **Kompatibilität:** Paper, Spigot, Purpur (1.18.x 1.21.x) - **Kompatibilität:** Paper, Spigot, Purpur (1.18.x 1.21.x)
- **Java:** 17+ - **Java:** 17+
- **Datenbank:** YAML (Standard) oder MySQL/MariaDB (optional) - **Datenbank:** YAML (Standard) oder MySQL/MariaDB (optional)
- **Performance:** Ressourcenschonende Sortier-Algorithmen mit konfigurierbarem Intervall - **Performance:** Asynchrones Speichern der `players.yml`, konfigurierbarer Sortier-Intervall, TTL-Caching für öffentliche Truhen
--- ---
@@ -216,4 +374,6 @@ Bei aktiviertem MySQL erstellt das Plugin folgende Tabellen automatisch:
--- ---
*Viper Plugins © 2026 Effizienz für deinen Server* **Copyright © 2026 - M_Viper - Alle Rechte vorbehalten**
Die unbefugte Vervielfältigung, Verbreitung oder Weitergabe dieses Plugins ist strafbar und wird rechtlich verfolgt.

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.viper</groupId> <groupId>com.viper</groupId>
<artifactId>AutoSortChest</artifactId> <artifactId>AutoSortChest</artifactId>
<version>2.2</version> <version>2.3</version>
<name>AutoSortChest</name> <name>AutoSortChest</name>
<repositories> <repositories>

View File

@@ -222,7 +222,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
private final Map<String, Long> fullChestLocationCache = new HashMap<>(); private final Map<String, Long> fullChestLocationCache = new HashMap<>();
private static final long FULL_CHEST_CACHE_DURATION = 10_000L; // 10 Sekunden private static final long FULL_CHEST_CACHE_DURATION = 10_000L; // 10 Sekunden
private static final String CONFIG_VERSION = "2.1"; // BungeeCord NEU: 2.0 → 2.1 private static final String CONFIG_VERSION = "2.2"; // Multi-Rest: 2.1 → 2.2
private boolean updateAvailable = false; private boolean updateAvailable = false;
private String latestVersion = ""; private String latestVersion = "";
@@ -343,6 +343,20 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
mysqlManager.setTargetChest(uuidString, item, world, x, y, z, isPublic); mysqlManager.setTargetChest(uuidString, item, world, x, y, z, isPublic);
} }
} }
// BUG FIX: Mehrere Rest-Truhen migrieren (neues Format + Legacy)
String restBasePath = "players." + uuidString + ".rest-chests";
if (playerData.contains(restBasePath)) {
for (String slotKey : playerData.getConfigurationSection(restBasePath).getKeys(false)) {
String rPath = restBasePath + "." + slotKey;
String world = playerData.getString(rPath + ".world");
int x = playerData.getInt(rPath + ".x");
int y = playerData.getInt(rPath + ".y");
int z = playerData.getInt(rPath + ".z");
boolean isPublic = playerData.getBoolean(rPath + ".public", false);
mysqlManager.setRestChest(uuidString, world, x, y, z, isPublic);
}
} else {
// Legacy: altes single rest-chest Format
String restPath = "players." + uuidString + ".rest-chest"; String restPath = "players." + uuidString + ".rest-chest";
if (playerData.contains(restPath)) { if (playerData.contains(restPath)) {
String world = playerData.getString(restPath + ".world"); String world = playerData.getString(restPath + ".world");
@@ -353,6 +367,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
mysqlManager.setRestChest(uuidString, world, x, y, z, isPublic); mysqlManager.setRestChest(uuidString, world, x, y, z, isPublic);
} }
} }
}
getLogger().info("Migration der YAML-Daten nach MySQL abgeschlossen."); getLogger().info("Migration der YAML-Daten nach MySQL abgeschlossen.");
} }
@@ -405,9 +420,11 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
exportData.set(path + ".public", chest.get("public")); exportData.set(path + ".public", chest.get("public"));
} }
Map<String, Object> restChest = mysqlManager.getRestChest(uuidString); // BUG FIX: Alle Rest-Truhen exportieren
if (restChest != null) { List<Map<String, Object>> restChests = mysqlManager.getRestChests(uuidString);
String path = "players." + uuidString + ".rest-chest"; for (Map<String, Object> restChest : restChests) {
int restSlot = (int) restChest.get("slot");
String path = "players." + uuidString + ".rest-chests." + restSlot;
exportData.set(path + ".world", restChest.get("world")); exportData.set(path + ".world", restChest.get("world"));
exportData.set(path + ".x", restChest.get("x")); exportData.set(path + ".x", restChest.get("x"));
exportData.set(path + ".y", restChest.get("y")); exportData.set(path + ".y", restChest.get("y"));
@@ -689,10 +706,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (!config.contains("messages.rest-chest-set")) config.set("messages.rest-chest-set", defaultConfig.getString("messages.rest-chest-set", "&aRest-Truhe (Fallback) erfolgreich gesetzt!")); if (!config.contains("messages.rest-chest-set")) config.set("messages.rest-chest-set", defaultConfig.getString("messages.rest-chest-set", "&aRest-Truhe (Fallback) erfolgreich gesetzt!"));
if (!config.contains("messages.target-chest-missing")) config.set("messages.target-chest-missing", defaultConfig.getString("messages.target-chest-missing", "&cZieltruhe für %item% fehlt!")); if (!config.contains("messages.target-chest-missing")) config.set("messages.target-chest-missing", defaultConfig.getString("messages.target-chest-missing", "&cZieltruhe für %item% fehlt!"));
String targetChestFull = config.getString("messages.target-chest-full", ""); if (!config.contains("messages.target-chest-full")) {
String defaultTargetChestFull = defaultConfig.getString("messages.target-chest-full", "&cZieltruhe für %item% ist voll! Koordinaten: (%x%, %y%, %z%)"); config.set("messages.target-chest-full", defaultConfig.getString("messages.target-chest-full", "&cZieltruhe für %item% ist voll! Koordinaten: (%x%, %y%, %z%)"));
if (!config.contains("messages.target-chest-full") || !targetChestFull.equals(defaultTargetChestFull)) {
config.set("messages.target-chest-full", defaultTargetChestFull);
} }
if (!config.contains("messages.mode-changed")) config.set("messages.mode-changed", defaultConfig.getString("messages.mode-changed", "&aModus gewechselt: &e%mode%")); if (!config.contains("messages.mode-changed")) config.set("messages.mode-changed", defaultConfig.getString("messages.mode-changed", "&aModus gewechselt: &e%mode%"));
@@ -825,9 +840,9 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
String restPath = basePath + ".rest-chest"; // BUG FIX: Alle Rest-Truhen iterieren (neues Multi-Format + Legacy)
if (playerData.contains(restPath)) { List<Location> restLocations = getRestChestLocations(playerUUID);
Location chestLocation = getLocationFromPath(restPath); for (Location chestLocation : restLocations) {
if (chestLocation == null) continue; if (chestLocation == null) continue;
Block chestBlock = chestLocation.getBlock(); Block chestBlock = chestLocation.getBlock();
if (!(chestBlock.getState() instanceof Chest)) continue; if (!(chestBlock.getState() instanceof Chest)) continue;
@@ -928,13 +943,27 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
} }
String restPath = "players." + uuid + ".rest-chest"; // BUG FIX: Neues Multi-Format für Rest-Truhen
if (playerData.contains(restPath + ".world")) { String restBasePath = "players." + uuid + ".rest-chests";
if (world.equals(playerData.getString(restPath + ".world")) if (playerData.contains(restBasePath)) {
&& x == playerData.getInt(restPath + ".x") for (String slotKey : playerData.getConfigurationSection(restBasePath).getKeys(false)) {
&& y == playerData.getInt(restPath + ".y") String rPath = restBasePath + "." + slotKey;
&& z == playerData.getInt(restPath + ".z")) { if (world.equals(playerData.getString(rPath + ".world"))
if (playerData.getBoolean(restPath + ".public", false)) return true; && x == playerData.getInt(rPath + ".x")
&& y == playerData.getInt(rPath + ".y")
&& z == playerData.getInt(rPath + ".z")) {
if (playerData.getBoolean(rPath + ".public", false)) return true;
}
}
}
// Legacy
String legacyRestPath = "players." + uuid + ".rest-chest";
if (playerData.contains(legacyRestPath + ".world")) {
if (world.equals(playerData.getString(legacyRestPath + ".world"))
&& x == playerData.getInt(legacyRestPath + ".x")
&& y == playerData.getInt(legacyRestPath + ".y")
&& z == playerData.getInt(legacyRestPath + ".z")) {
if (playerData.getBoolean(legacyRestPath + ".public", false)) return true;
} }
} }
} }
@@ -987,7 +1016,9 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
String chestId = null; String chestId = null;
List<Map<String, Object>> chests = mysqlManager.getInputChests(playerUUID.toString()); List<Map<String, Object>> chests = mysqlManager.getInputChests(playerUUID.toString());
for (Map<String, Object> chest : chests) { for (Map<String, Object> chest : chests) {
if (chest.get("world").equals(location.getWorld().getName()) String chestWorld = (String) chest.get("world");
if (chestWorld == null) continue; // NPE-Schutz: korrupter DB-Eintrag
if (chestWorld.equals(location.getWorld().getName())
&& ((int) chest.get("x")) == location.getBlockX() && ((int) chest.get("x")) == location.getBlockX()
&& ((int) chest.get("y")) == location.getBlockY() && ((int) chest.get("y")) == location.getBlockY()
&& ((int) chest.get("z")) == location.getBlockZ()) { && ((int) chest.get("z")) == location.getBlockZ()) {
@@ -1075,13 +1106,34 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
private void setRestChestLocation(UUID playerUUID, Location location, boolean isPublic) { private void setRestChestLocation(UUID playerUUID, Location location, boolean isPublic) {
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
// ── BungeeCord NEU: serverName mitgeben ─────────────────────────── // ── BungeeCord + Multi-Rest: serverName und auto-slot ─────────────────
mysqlManager.setRestChest(playerUUID.toString(), mysqlManager.setRestChest(playerUUID.toString(),
location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(),
isPublic, serverName); isPublic, serverName);
mysqlManager.savePlayer(playerUUID.toString(), Bukkit.getOfflinePlayer(playerUUID).getName()); mysqlManager.savePlayer(playerUUID.toString(), Bukkit.getOfflinePlayer(playerUUID).getName());
} else { } else {
String path = "players." + playerUUID + ".rest-chest"; // YAML: mehrere Rest-Truhen unter rest-chests.<slot>
String basePath = "players." + playerUUID + ".rest-chests";
// Prüfen ob diese Location schon registriert ist (Update)
if (playerData.contains(basePath)) {
for (String slotKey : playerData.getConfigurationSection(basePath).getKeys(false)) {
String path = basePath + "." + slotKey;
if (location.getWorld().getName().equals(playerData.getString(path + ".world"))
&& location.getBlockX() == playerData.getInt(path + ".x")
&& location.getBlockY() == playerData.getInt(path + ".y")
&& location.getBlockZ() == playerData.getInt(path + ".z")) {
playerData.set(path + ".public", isPublic);
savePlayerData();
return;
}
}
}
// Neuen Slot anlegen
int nextSlot = 0;
if (playerData.contains(basePath)) {
nextSlot = playerData.getConfigurationSection(basePath).getKeys(false).size();
}
String path = basePath + "." + nextSlot;
playerData.set(path + ".world", location.getWorld().getName()); playerData.set(path + ".world", location.getWorld().getName());
playerData.set(path + ".x", location.getBlockX()); playerData.set(path + ".x", location.getBlockX());
playerData.set(path + ".y", location.getBlockY()); playerData.set(path + ".y", location.getBlockY());
@@ -1091,24 +1143,49 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
private Location getRestChestLocation(UUID playerUUID) { /** Gibt alle Rest-Truhen-Locations zurück (für mehrere Rest-Truhen). */
private List<Location> getRestChestLocations(UUID playerUUID) {
List<Location> result = new ArrayList<>();
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
Map<String, Object> map = mysqlManager.getRestChest(playerUUID.toString()); List<Map<String, Object>> maps = mysqlManager.getRestChests(playerUUID.toString());
if (map == null) return null; for (Map<String, Object> map : maps) {
// ── BungeeCord NEU: Remote-Truhen nicht lokal auflösen ───────────── if (isRemoteChest(map)) continue;
if (isRemoteChest(map)) return null;
World w = Bukkit.getWorld((String) map.get("world")); World w = Bukkit.getWorld((String) map.get("world"));
if (w == null) return null; if (w == null) continue;
return new Location(w, (int) map.get("x"), (int) map.get("y"), (int) map.get("z")); result.add(new Location(w, (int) map.get("x"), (int) map.get("y"), (int) map.get("z")));
}
} else { } else {
String path = "players." + playerUUID + ".rest-chest"; // Neues Multi-Format
if (!playerData.contains(path)) return null; String basePath = "players." + playerUUID + ".rest-chests";
if (playerData.contains(basePath)) {
for (String slotKey : playerData.getConfigurationSection(basePath).getKeys(false)) {
String path = basePath + "." + slotKey;
String worldName = playerData.getString(path + ".world"); String worldName = playerData.getString(path + ".world");
World world = getServer().getWorld(worldName); World world = getServer().getWorld(worldName);
if (world == null) return null; if (world == null) continue;
return new Location(world, playerData.getInt(path + ".x"), playerData.getInt(path + ".y"), playerData.getInt(path + ".z")); result.add(new Location(world, playerData.getInt(path + ".x"),
playerData.getInt(path + ".y"), playerData.getInt(path + ".z")));
} }
} }
// Legacy-Fallback: altes single rest-chest Format
String legacyPath = "players." + playerUUID + ".rest-chest";
if (result.isEmpty() && playerData.contains(legacyPath)) {
String worldName = playerData.getString(legacyPath + ".world");
World world = getServer().getWorld(worldName);
if (world != null) {
result.add(new Location(world, playerData.getInt(legacyPath + ".x"),
playerData.getInt(legacyPath + ".y"), playerData.getInt(legacyPath + ".z")));
}
}
}
return result;
}
/** Legacy: Gibt die erste Rest-Truhe zurück (oder null). */
private Location getRestChestLocation(UUID playerUUID) {
List<Location> locs = getRestChestLocations(playerUUID);
return locs.isEmpty() ? null : locs.get(0);
}
private Location getTargetChestLocation(UUID playerUUID, Material itemType) { private Location getTargetChestLocation(UUID playerUUID, Material itemType) {
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
@@ -1171,15 +1248,25 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!command.getName().equalsIgnoreCase("asc")) return false; if (!command.getName().equalsIgnoreCase("asc")) return false;
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "Dieser Befehl ist nur für Spieler!"); String lang = config != null ? config.getString("language", "de") : "de";
return true;
}
Player player = (Player) sender;
String lang = config.getString("language", "de");
if (lang == null) lang = "de"; if (lang == null) lang = "de";
// reload, import und export sind auch von der Konsole erlaubt
boolean isPlayer = sender instanceof Player;
if (!isPlayer) {
if (args.length == 0 || (!args[0].equalsIgnoreCase("reload")
&& !args[0].equalsIgnoreCase("import")
&& !args[0].equalsIgnoreCase("export"))) {
sender.sendMessage(ChatColor.RED + "Dieser Befehl ist nur für Spieler! (Konsole: reload, import, export)");
return true;
}
}
Player player = isPlayer ? (Player) sender : null;
if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
if (player == null) { sender.sendMessage(ChatColor.RED + "Verwendung: /asc [reload|import|export]"); return true; }
String helpMessage = lang.equalsIgnoreCase("en") ? HELP_EN : HELP_DE; String helpMessage = lang.equalsIgnoreCase("en") ? HELP_EN : HELP_DE;
helpMessage = ChatColor.translateAlternateColorCodes('&', helpMessage); helpMessage = ChatColor.translateAlternateColorCodes('&', helpMessage);
player.sendMessage(helpMessage.split("\n")); player.sendMessage(helpMessage.split("\n"));
@@ -1194,13 +1281,13 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
.replace("%server_name%", serverName.isEmpty() ? "(nicht gesetzt)" : serverName) // BungeeCord NEU .replace("%server_name%", serverName.isEmpty() ? "(nicht gesetzt)" : serverName) // BungeeCord NEU
.replace("%author%", String.join(", ", getDescription().getAuthors())); .replace("%author%", String.join(", ", getDescription().getAuthors()));
infoMessage = ChatColor.translateAlternateColorCodes('&', infoMessage); infoMessage = ChatColor.translateAlternateColorCodes('&', infoMessage);
player.sendMessage(infoMessage.split("\n")); sender.sendMessage(infoMessage.split("\n"));
return true; return true;
} }
if (args[0].equalsIgnoreCase("reload")) { if (args[0].equalsIgnoreCase("reload")) {
if (!player.hasPermission("autosortchest.reload")) { if (!sender.hasPermission("autosortchest.reload")) {
player.sendMessage(getMessage("no-permission")); sender.sendMessage(getMessage("no-permission"));
return true; return true;
} }
@@ -1240,8 +1327,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
migrateInputChests(); migrateInputChests();
startTasks(); startTasks();
player.sendMessage(getMessage("reload-success")); sender.sendMessage(getMessage("reload-success"));
getLogger().info("Plugin erfolgreich neu geladen von " + player.getName() getLogger().info("Plugin erfolgreich neu geladen von " + sender.getName()
+ " (sort_interval_ticks=" + sortIntervalTicks + ", server_name=\"" + serverName + "\")"); + " (sort_interval_ticks=" + sortIntervalTicks + ", server_name=\"" + serverName + "\")");
return true; return true;
} }
@@ -1250,22 +1337,22 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
// /asc import YAML → MySQL // /asc import YAML → MySQL
// ------------------------------------------------------- // -------------------------------------------------------
if (args[0].equalsIgnoreCase("import")) { if (args[0].equalsIgnoreCase("import")) {
if (!player.hasPermission("autosortchest.import")) { if (!sender.hasPermission("autosortchest.import")) {
player.sendMessage(getMessage("no-permission")); sender.sendMessage(getMessage("no-permission"));
return true; return true;
} }
if (!mysqlEnabled || mysqlManager == null) { if (!mysqlEnabled || mysqlManager == null) {
player.sendMessage(ChatColor.RED + "MySQL ist nicht aktiviert! Aktiviere MySQL in der config.yml zuerst."); sender.sendMessage(ChatColor.RED + "MySQL ist nicht aktiviert! Aktiviere MySQL in der config.yml zuerst.");
return true; return true;
} }
if (playerData == null || playerData.getConfigurationSection("players") == null if (playerData == null || playerData.getConfigurationSection("players") == null
|| playerData.getConfigurationSection("players").getKeys(false).isEmpty()) { || playerData.getConfigurationSection("players").getKeys(false).isEmpty()) {
player.sendMessage(ChatColor.RED + "Die players.yml ist leer oder enthält keine Spielerdaten!"); sender.sendMessage(ChatColor.RED + "Die players.yml ist leer oder enthält keine Spielerdaten!");
return true; return true;
} }
player.sendMessage(ChatColor.YELLOW + "Importiere Daten aus players.yml nach MySQL..."); sender.sendMessage(ChatColor.YELLOW + "Importiere Daten aus players.yml nach MySQL...");
player.sendMessage(ChatColor.GRAY + "Bestehende MySQL-Daten werden nicht überschrieben (REPLACE INTO)."); sender.sendMessage(ChatColor.GRAY + "Bestehende MySQL-Daten werden nicht überschrieben (REPLACE INTO).");
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
@@ -1311,6 +1398,20 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
// BUG FIX: Mehrere Rest-Truhen importieren (neues Format + Legacy)
String restBasePath2 = "players." + uuidString + ".rest-chests";
if (playerData.contains(restBasePath2)) {
for (String slotKey : playerData.getConfigurationSection(restBasePath2).getKeys(false)) {
String rPath = restBasePath2 + "." + slotKey;
String world = playerData.getString(rPath + ".world");
int x = playerData.getInt(rPath + ".x");
int y = playerData.getInt(rPath + ".y");
int z = playerData.getInt(rPath + ".z");
boolean isPublic = playerData.getBoolean(rPath + ".public", false);
mysqlManager.setRestChest(uuidString, world, x, y, z, isPublic);
restCount++;
}
} else {
String restPath = "players." + uuidString + ".rest-chest"; String restPath = "players." + uuidString + ".rest-chest";
if (playerData.contains(restPath + ".world")) { if (playerData.contains(restPath + ".world")) {
String world = playerData.getString(restPath + ".world"); String world = playerData.getString(restPath + ".world");
@@ -1322,15 +1423,16 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
restCount++; restCount++;
} }
} }
}
final int fp = playerCount, fi = inputCount, ft = targetCount, fr = restCount; final int fp = playerCount, fi = inputCount, ft = targetCount, fr = restCount;
Bukkit.getScheduler().runTask(Main.this, () -> { Bukkit.getScheduler().runTask(Main.this, () -> {
player.sendMessage(ChatColor.GREEN + "Import erfolgreich abgeschlossen!"); sender.sendMessage(ChatColor.GREEN + "Import erfolgreich abgeschlossen!");
player.sendMessage(ChatColor.GRAY + " Spieler: " + ChatColor.WHITE + fp); sender.sendMessage(ChatColor.GRAY + " Spieler: " + ChatColor.WHITE + fp);
player.sendMessage(ChatColor.GRAY + " Eingangstruhen: " + ChatColor.WHITE + fi); sender.sendMessage(ChatColor.GRAY + " Eingangstruhen: " + ChatColor.WHITE + fi);
player.sendMessage(ChatColor.GRAY + " Zieltruhen: " + ChatColor.WHITE + ft); sender.sendMessage(ChatColor.GRAY + " Zieltruhen: " + ChatColor.WHITE + ft);
player.sendMessage(ChatColor.GRAY + " Rest-Truhen: " + ChatColor.WHITE + fr); sender.sendMessage(ChatColor.GRAY + " Rest-Truhen: " + ChatColor.WHITE + fr);
getLogger().info("Import durch " + player.getName() + " abgeschlossen: " getLogger().info("Import durch " + sender.getName() + " abgeschlossen: "
+ fp + " Spieler, " + fi + " Input, " + ft + " Target, " + fr + " Rest."); + fp + " Spieler, " + fi + " Input, " + ft + " Target, " + fr + " Rest.");
}); });
} }
@@ -1342,17 +1444,17 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
// /asc export MySQL → YAML // /asc export MySQL → YAML
// ------------------------------------------------------- // -------------------------------------------------------
if (args[0].equalsIgnoreCase("export")) { if (args[0].equalsIgnoreCase("export")) {
if (!player.hasPermission("autosortchest.export")) { if (!sender.hasPermission("autosortchest.export")) {
player.sendMessage(getMessage("no-permission")); sender.sendMessage(getMessage("no-permission"));
return true; return true;
} }
if (!mysqlEnabled || mysqlManager == null) { if (!mysqlEnabled || mysqlManager == null) {
player.sendMessage(ChatColor.RED + "MySQL ist nicht aktiviert! Der Export benötigt eine aktive MySQL-Verbindung."); sender.sendMessage(ChatColor.RED + "MySQL ist nicht aktiviert! Der Export benötigt eine aktive MySQL-Verbindung.");
return true; return true;
} }
player.sendMessage(ChatColor.YELLOW + "Exportiere Daten aus MySQL nach players.yml..."); sender.sendMessage(ChatColor.YELLOW + "Exportiere Daten aus MySQL nach players.yml...");
player.sendMessage(ChatColor.GRAY + "Ein Backup der aktuellen players.yml wird erstellt."); sender.sendMessage(ChatColor.GRAY + "Ein Backup der aktuellen players.yml wird erstellt.");
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
@@ -1370,7 +1472,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
java.nio.file.Files.copy(playerDataFile.toPath(), backupFile.toPath()); java.nio.file.Files.copy(playerDataFile.toPath(), backupFile.toPath());
} catch (IOException e) { } catch (IOException e) {
Bukkit.getScheduler().runTask(Main.this, () -> Bukkit.getScheduler().runTask(Main.this, () ->
player.sendMessage(ChatColor.RED + "Backup fehlgeschlagen: " + e.getMessage())); sender.sendMessage(ChatColor.RED + "Backup fehlgeschlagen: " + e.getMessage()));
return; return;
} }
} }
@@ -1410,9 +1512,11 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
targetCount++; targetCount++;
} }
Map<String, Object> restChest = mysqlManager.getRestChest(uuidString); // BUG FIX: Alle Rest-Truhen exportieren
if (restChest != null) { List<Map<String, Object>> restChests = mysqlManager.getRestChests(uuidString);
String path = "players." + uuidString + ".rest-chest"; for (Map<String, Object> restChest : restChests) {
int restSlot = (int) restChest.get("slot");
String path = "players." + uuidString + ".rest-chests." + restSlot;
exportData.set(path + ".world", restChest.get("world")); exportData.set(path + ".world", restChest.get("world"));
exportData.set(path + ".x", restChest.get("x")); exportData.set(path + ".x", restChest.get("x"));
exportData.set(path + ".y", restChest.get("y")); exportData.set(path + ".y", restChest.get("y"));
@@ -1430,24 +1534,24 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
Bukkit.getScheduler().runTask(Main.this, () -> { Bukkit.getScheduler().runTask(Main.this, () -> {
playerData = finalExport; playerData = finalExport;
player.sendMessage(ChatColor.GREEN + "Export erfolgreich abgeschlossen!"); sender.sendMessage(ChatColor.GREEN + "Export erfolgreich abgeschlossen!");
if (finalBackupName != null) { if (finalBackupName != null) {
player.sendMessage(ChatColor.GRAY + " Backup: " + ChatColor.WHITE + finalBackupName); sender.sendMessage(ChatColor.GRAY + " Backup: " + ChatColor.WHITE + finalBackupName);
} else { } else {
player.sendMessage(ChatColor.GRAY + " Backup: " + ChatColor.DARK_GRAY + "Übersprungen (players.yml war leer)"); sender.sendMessage(ChatColor.GRAY + " Backup: " + ChatColor.DARK_GRAY + "Übersprungen (players.yml war leer)");
} }
player.sendMessage(ChatColor.GRAY + " Spieler: " + ChatColor.WHITE + fp); sender.sendMessage(ChatColor.GRAY + " Spieler: " + ChatColor.WHITE + fp);
player.sendMessage(ChatColor.GRAY + " Eingangstruhen: " + ChatColor.WHITE + fi); sender.sendMessage(ChatColor.GRAY + " Eingangstruhen: " + ChatColor.WHITE + fi);
player.sendMessage(ChatColor.GRAY + " Zieltruhen: " + ChatColor.WHITE + ft); sender.sendMessage(ChatColor.GRAY + " Zieltruhen: " + ChatColor.WHITE + ft);
player.sendMessage(ChatColor.GRAY + " Rest-Truhen: " + ChatColor.WHITE + fr); sender.sendMessage(ChatColor.GRAY + " Rest-Truhen: " + ChatColor.WHITE + fr);
getLogger().info("Export durch " + player.getName() + " abgeschlossen: " getLogger().info("Export durch " + sender.getName() + " abgeschlossen: "
+ fp + " Spieler, " + fi + " Input, " + ft + " Target, " + fr + " Rest." + fp + " Spieler, " + fi + " Input, " + ft + " Target, " + fr + " Rest."
+ (finalBackupName != null ? " Backup: " + finalBackupName : " Kein Backup.")); + (finalBackupName != null ? " Backup: " + finalBackupName : " Kein Backup."));
}); });
} catch (Exception e) { } catch (Exception e) {
Bukkit.getScheduler().runTask(Main.this, () -> Bukkit.getScheduler().runTask(Main.this, () ->
player.sendMessage(ChatColor.RED + "Export fehlgeschlagen: " + e.getMessage())); sender.sendMessage(ChatColor.RED + "Export fehlgeschlagen: " + e.getMessage()));
getLogger().warning("Export fehlgeschlagen: " + e.getMessage()); getLogger().warning("Export fehlgeschlagen: " + e.getMessage());
} }
} }
@@ -1455,6 +1559,11 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
return true; return true;
} }
// Unbekannter Befehl → Hilfe (nur für Spieler)
if (player == null) {
sender.sendMessage(ChatColor.RED + "Verwendung: /asc [reload|import|export]");
return true;
}
String helpMessage = lang.equalsIgnoreCase("en") ? HELP_EN : HELP_DE; String helpMessage = lang.equalsIgnoreCase("en") ? HELP_EN : HELP_DE;
helpMessage = ChatColor.translateAlternateColorCodes('&', helpMessage); helpMessage = ChatColor.translateAlternateColorCodes('&', helpMessage);
player.sendMessage(helpMessage.split("\n")); player.sendMessage(helpMessage.split("\n"));
@@ -1486,14 +1595,40 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
// ── Limit-Pruefung: Rest-Truhe ───────────────────────────────────── // ── Limit-Pruefung: Rest-Truhe ─────────────────────────────────────
if (chestLimitsEnabled) { if (chestLimitsEnabled) {
int maxRest = getChestLimitForPlayer(player, "rest"); int maxRest = getChestLimitForPlayer(player, "rest");
boolean hasRestAlready = false; int currentRest = 0;
final Block finalChestBlockRest = chestBlock;
boolean alreadyRest = false;
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
hasRestAlready = mysqlManager.getRestChest(playerUUID.toString()) != null; currentRest = mysqlManager.countRestChests(playerUUID.toString());
// Prüfen ob diese Truhe bereits als Rest-Truhe registriert ist (Update erlaubt)
alreadyRest = mysqlManager.getRestSlotForLocation(
playerUUID.toString(),
finalChestBlockRest.getWorld().getName(),
finalChestBlockRest.getX(),
finalChestBlockRest.getY(),
finalChestBlockRest.getZ()) >= 0;
} else { } else {
hasRestAlready = playerData.contains("players." + playerUUID + ".rest-chest"); String basePath = "players." + playerUUID + ".rest-chests";
if (playerData.contains(basePath)) {
for (String slotKey : playerData.getConfigurationSection(basePath).getKeys(false)) {
String rPath = basePath + "." + slotKey;
if (finalChestBlockRest.getWorld().getName().equals(playerData.getString(rPath + ".world"))
&& finalChestBlockRest.getX() == playerData.getInt(rPath + ".x")
&& finalChestBlockRest.getY() == playerData.getInt(rPath + ".y")
&& finalChestBlockRest.getZ() == playerData.getInt(rPath + ".z")) {
alreadyRest = true;
break;
} }
if (hasRestAlready && maxRest <= 1) { }
player.sendMessage(ChatColor.RED + "Du hast bereits eine Rest-Truhe! (Limit: " + maxRest + ")"); if (!alreadyRest) currentRest = playerData.getConfigurationSection(basePath).getKeys(false).size();
}
// Legacy fallback
if (!alreadyRest && currentRest == 0 && playerData.contains("players." + playerUUID + ".rest-chest")) {
currentRest = 1;
}
}
if (!alreadyRest && currentRest >= maxRest) {
player.sendMessage(ChatColor.RED + "Du hast das Limit deiner Rest-Truhen erreicht! (" + maxRest + ")");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@@ -1530,11 +1665,14 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
final Block finalChestBlock = chestBlock; final Block finalChestBlock = chestBlock;
boolean alreadyInput = false; boolean alreadyInput = false;
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
alreadyInput = mysqlManager.getInputChests(playerUUID.toString()).stream().anyMatch(c -> alreadyInput = mysqlManager.getInputChests(playerUUID.toString()).stream().anyMatch(c -> {
c.get("world").equals(finalChestBlock.getWorld().getName()) String cWorld = (String) c.get("world");
return cWorld != null
&& cWorld.equals(finalChestBlock.getWorld().getName())
&& (int)c.get("x") == finalChestBlock.getX() && (int)c.get("x") == finalChestBlock.getX()
&& (int)c.get("y") == finalChestBlock.getY() && (int)c.get("y") == finalChestBlock.getY()
&& (int)c.get("z") == finalChestBlock.getZ()); && (int)c.get("z") == finalChestBlock.getZ();
});
} }
if (!alreadyInput && currentInput >= maxInput) { if (!alreadyInput && currentInput >= maxInput) {
player.sendMessage(ChatColor.RED + "Du hast das Limit deiner Eingangstruhen erreicht! (" + maxInput + ")"); player.sendMessage(ChatColor.RED + "Du hast das Limit deiner Eingangstruhen erreicht! (" + maxInput + ")");
@@ -1564,8 +1702,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (attachedBlock.getState() instanceof Chest) chestBlock = attachedBlock; if (attachedBlock.getState() instanceof Chest) chestBlock = attachedBlock;
} }
if (chestBlock == null) { player.sendMessage(getMessage("no-chest-near-sign")); return; } if (chestBlock == null) { player.sendMessage(getMessage("no-chest-near-sign")); return; }
event.setLine(0, "[asc]"); event.setLine(0, getSignColor("target", "line1") + "[asc]");
event.setLine(1, "ziel"); event.setLine(1, getSignColor("target", "line2") + "ziel");
event.setLine(2, ""); event.setLine(2, "");
event.setLine(3, ""); event.setLine(3, "");
} }
@@ -2017,7 +2155,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (!player.isSneaking() && !isAdmin(player)) { // BUG FIX: autosortchest.bypass erlaubt Abbau ohne Shift-Taste
if (!player.isSneaking() && !isAdmin(player) && !player.hasPermission("autosortchest.bypass")) {
player.sendMessage(getMessage("sign-break-denied")); player.sendMessage(getMessage("sign-break-denied"));
event.setCancelled(true); event.setCancelled(true);
return; return;
@@ -2052,8 +2191,10 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
if (ownerUUID == null) { if (ownerUUID == null) {
Location restLoc = getRestChestLocation(uuid); // BUG FIX: Alle Rest-Truhen des Spielers prüfen (nicht nur erste)
if (chestLoc.equals(restLoc)) ownerUUID = uuid; for (Location restLoc : getRestChestLocations(uuid)) {
if (chestLoc.equals(restLoc)) { ownerUUID = uuid; break; }
}
} }
if (ownerUUID != null) break; if (ownerUUID != null) break;
} }
@@ -2062,9 +2203,33 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
UUID uuidToDelete = (ownerUUID != null) ? ownerUUID : player.getUniqueId(); UUID uuidToDelete = (ownerUUID != null) ? ownerUUID : player.getUniqueId();
if (line1.equalsIgnoreCase("rest")) { if (line1.equalsIgnoreCase("rest")) {
if (mysqlEnabled && mysqlManager != null) {
// BUG FIX: Nur die spezifische Location löschen, nicht alle Rest-Truhen
mysqlManager.removeRestChestByLocation(uuidToDelete.toString(),
chestLoc.getWorld().getName(), chestLoc.getBlockX(), chestLoc.getBlockY(), chestLoc.getBlockZ());
} else {
// YAML: Spezifische Location aus rest-chests entfernen
boolean removedFromNew = false;
String basePath = "players." + uuidToDelete + ".rest-chests";
if (playerData.contains(basePath)) {
for (String slotKey : new ArrayList<>(playerData.getConfigurationSection(basePath).getKeys(false))) {
String rPath = basePath + "." + slotKey;
if (chestLoc.getWorld().getName().equals(playerData.getString(rPath + ".world"))
&& chestLoc.getBlockX() == playerData.getInt(rPath + ".x")
&& chestLoc.getBlockY() == playerData.getInt(rPath + ".y")
&& chestLoc.getBlockZ() == playerData.getInt(rPath + ".z")) {
playerData.set(rPath, null);
removedFromNew = true;
break;
}
}
}
// Legacy-Fallback
if (!removedFromNew) {
playerData.set("players." + uuidToDelete + ".rest-chest", null); playerData.set("players." + uuidToDelete + ".rest-chest", null);
}
savePlayerData(); savePlayerData();
if (mysqlEnabled && mysqlManager != null) mysqlManager.removeRestChest(uuidToDelete.toString()); }
} else if (line1.equalsIgnoreCase("input")) { } else if (line1.equalsIgnoreCase("input")) {
removeInputChestByLocation(uuidToDelete, chestLoc); removeInputChestByLocation(uuidToDelete, chestLoc);
} else if (line1.equalsIgnoreCase("ziel")) { } else if (line1.equalsIgnoreCase("ziel")) {
@@ -2072,11 +2237,24 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (!line2.isEmpty()) { if (!line2.isEmpty()) {
Material mat = Material.matchMaterial(line2); Material mat = Material.matchMaterial(line2);
if (mat != null) { if (mat != null) {
Location savedLoc = getTargetChestLocation(uuidToDelete, mat); if (mysqlEnabled && mysqlManager != null) {
if (savedLoc != null && savedLoc.equals(chestLoc)) { // BUG FIX: Nur bei MySQL → kein playerData-Zugriff nötig
playerData.set("players." + uuidToDelete + ".target-chests." + mat.name(), null); mysqlManager.removeTargetChest(uuidToDelete.toString(), mat.name());
} else {
// YAML: Slot mit passender Location finden und löschen
String basePath = "players." + uuidToDelete + ".target-chests";
if (playerData.contains(basePath)) {
String path = basePath + "." + mat.name();
if (playerData.contains(path)) {
Location savedLoc = getLocationFromPath(path);
if (savedLoc != null && savedLoc.getBlockX() == chestLoc.getBlockX()
&& savedLoc.getBlockY() == chestLoc.getBlockY()
&& savedLoc.getBlockZ() == chestLoc.getBlockZ()) {
playerData.set(path, null);
savePlayerData(); savePlayerData();
if (mysqlEnabled && mysqlManager != null) mysqlManager.removeTargetChest(uuidToDelete.toString(), mat.name()); }
}
}
} }
} }
} }
@@ -2144,16 +2322,36 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
private void removeOldTargetEntry(UUID uuid, Location loc, String newItemType) { private void removeOldTargetEntry(UUID uuid, Location loc, String newItemType) {
if (mysqlEnabled && mysqlManager != null) {
// MySQL: Alle Zieltruhen dieser Location löschen, die ein anderes Item haben
List<Map<String, Object>> existing = mysqlManager.getTargetChests(uuid.toString());
for (Map<String, Object> e : existing) {
String existingItem = (String) e.get("item");
if (existingItem.equalsIgnoreCase(newItemType)) continue;
String w = (String) e.get("world");
if (w.equals(loc.getWorld().getName())
&& (int) e.get("x") == loc.getBlockX()
&& (int) e.get("y") == loc.getBlockY()
&& (int) e.get("z") == loc.getBlockZ()) {
mysqlManager.removeTargetChest(uuid.toString(), existingItem);
}
}
return;
}
// YAML-Modus
String basePath = "players." + uuid + ".target-chests"; String basePath = "players." + uuid + ".target-chests";
if (!playerData.contains(basePath)) return; if (!playerData.contains(basePath)) return;
for (String existingType : playerData.getConfigurationSection(basePath).getKeys(false)) { for (String existingType : playerData.getConfigurationSection(basePath).getKeys(false)) {
if (existingType.equalsIgnoreCase(newItemType)) continue; if (existingType.equalsIgnoreCase(newItemType)) continue;
String path = basePath + "." + existingType; String path = basePath + "." + existingType;
if (playerData.getString(path + ".world").equals(loc.getWorld().getName()) String savedWorld = playerData.getString(path + ".world");
if (savedWorld == null) continue; // NPE-Schutz: korrupter Eintrag überspringen
if (savedWorld.equals(loc.getWorld().getName())
&& playerData.getInt(path + ".x") == loc.getBlockX() && playerData.getInt(path + ".x") == loc.getBlockX()
&& playerData.getInt(path + ".y") == loc.getBlockY() && playerData.getInt(path + ".y") == loc.getBlockY()
&& playerData.getInt(path + ".z") == loc.getBlockZ()) { && playerData.getInt(path + ".z") == loc.getBlockZ()) {
playerData.set(path, null); playerData.set(path, null);
savePlayerData(); // Änderung direkt auf Disk schreiben
break; break;
} }
} }
@@ -2352,7 +2550,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
}); });
// Preload Zieltruhen+Rest nur wenn es lokale Input-Truhen gibt // Preload Zieltruhen+Rest nur wenn es lokale Input-Truhen gibt
List<Map<String, Object>> preTargets = anyLocal ? mysqlManager.getTargetChests(uuidString) : new ArrayList<>(); List<Map<String, Object>> preTargets = anyLocal ? mysqlManager.getTargetChests(uuidString) : new ArrayList<>();
Map<String, Object> preRest = anyLocal ? mysqlManager.getRestChest(uuidString) : null; // BUG FIX: Alle Rest-Truhen vorladen (nicht nur eine)
List<Map<String, Object>> preRests = anyLocal ? mysqlManager.getRestChests(uuidString) : new ArrayList<>();
for (Map<String, Object> chest : chests) { for (Map<String, Object> chest : chests) {
if (crosslink) { if (crosslink) {
@@ -2361,7 +2560,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
String worldName = (String) chest.get("world"); String worldName = (String) chest.get("world");
boolean isLocal = Bukkit.getWorld(worldName) != null; boolean isLocal = Bukkit.getWorld(worldName) != null;
jobs.add(new Object[]{ ownerUUID, chest, isLocal, preTargets, preRest }); jobs.add(new Object[]{ ownerUUID, chest, isLocal, preTargets, preRests });
} }
} }
} catch (Exception e) { } catch (Exception e) {
@@ -2383,7 +2582,8 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Map<String, Object>> preTargets = (List<Map<String, Object>>) job[3]; List<Map<String, Object>> preTargets = (List<Map<String, Object>>) job[3];
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> preRest = (Map<String, Object>) job[4]; // BUG FIX: preRests ist jetzt eine Liste
List<Map<String, Object>> preRests = (List<Map<String, Object>>) job[4];
if (isLocal) { if (isLocal) {
World world = Bukkit.getWorld((String) chest.get("world")); World world = Bukkit.getWorld((String) chest.get("world"));
@@ -2400,14 +2600,17 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
targetLocs.computeIfAbsent((String) tc.get("item"), k -> new ArrayList<>()) targetLocs.computeIfAbsent((String) tc.get("item"), k -> new ArrayList<>())
.add(new Location(w, (int) tc.get("x"), (int) tc.get("y"), (int) tc.get("z"))); .add(new Location(w, (int) tc.get("x"), (int) tc.get("y"), (int) tc.get("z")));
} }
Location restLoc = null; // BUG FIX: Alle Rest-Truhen als Liste konvertieren
List<Location> restLocs = new ArrayList<>();
for (Map<String, Object> preRest : preRests) {
if (preRest != null && !isRemoteChest(preRest)) { if (preRest != null && !isRemoteChest(preRest)) {
World w = Bukkit.getWorld((String) preRest.get("world")); World w = Bukkit.getWorld((String) preRest.get("world"));
if (w != null) restLoc = new Location(w, if (w != null) restLocs.add(new Location(w,
(int) preRest.get("x"), (int) preRest.get("y"), (int) preRest.get("z")); (int) preRest.get("x"), (int) preRest.get("y"), (int) preRest.get("z")));
}
} }
checkSingleInputChest(ownerUUID, loc, (String) chest.get("chest_id"), false, targetLocs, restLoc); checkSingleInputChest(ownerUUID, loc, (String) chest.get("chest_id"), false, targetLocs, restLocs);
} else if (crosslink) { } else if (crosslink) {
checkRemoteInputChest(ownerUUID, chest); checkRemoteInputChest(ownerUUID, chest);
} }
@@ -2457,20 +2660,21 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
.add(new Location(world, (int) tc.get("x"), (int) tc.get("y"), (int) tc.get("z"))); .add(new Location(world, (int) tc.get("x"), (int) tc.get("y"), (int) tc.get("z")));
} }
Location localRestChest = getRestChestLocation(ownerUUID); // BUG FIX: Alle lokalen Rest-Truhen laden
List<Location> localRestChests = getRestChestLocations(ownerUUID);
if (localTargets.isEmpty() && localRestChest == null) return; if (localTargets.isEmpty() && localRestChests.isEmpty()) return;
OfflinePlayer op = Bukkit.getOfflinePlayer(ownerUUID); OfflinePlayer op = Bukkit.getOfflinePlayer(ownerUUID);
String ownerName = op.getName() != null ? op.getName() : ownerUUID.toString(); String ownerName = op.getName() != null ? op.getName() : ownerUUID.toString();
distributeFromRemoteInputChest(ownerUUID, ownerName, inputChestData, localTargets, localRestChest); distributeFromRemoteInputChest(ownerUUID, ownerName, inputChestData, localTargets, localRestChests);
} }
private void distributeFromRemoteInputChest(UUID ownerUUID, String ownerName, private void distributeFromRemoteInputChest(UUID ownerUUID, String ownerName,
Map<String, Object> inputChestData, Map<String, Object> inputChestData,
Map<String, List<Location>> localTargets, Map<String, List<Location>> localTargets,
Location localRestChest) { List<Location> localRestChests) {
if (!mysqlEnabled || mysqlManager == null) return; if (!mysqlEnabled || mysqlManager == null) return;
@@ -2495,7 +2699,12 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
for (Location l : slots) { for (Location l : slots) {
if (l != null && !isChestCachedFull(l)) { targetLoc = l; break; } if (l != null && !isChestCachedFull(l)) { targetLoc = l; break; }
} }
if (targetLoc == null) targetLoc = localRestChest; // BUG FIX: Alle lokalen Rest-Truhen als Fallback versuchen
if (targetLoc == null) {
for (Location restLoc : localRestChests) {
if (restLoc != null && !isChestCachedFull(restLoc)) { targetLoc = restLoc; break; }
}
}
if (targetLoc == null) continue; if (targetLoc == null) continue;
if (!(targetLoc.getBlock().getState() instanceof Chest)) continue; if (!(targetLoc.getBlock().getState() instanceof Chest)) continue;
@@ -2523,7 +2732,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
/** Legacy-Ueberladung: laedt Truhen-Locations synchron (nur fuer InventoryMoveItemEvent). */ /** Legacy-Ueberladung: laedt Truhen-Locations synchron (nur fuer InventoryMoveItemEvent). */
private void distributeItemsForOwner(UUID ownerUUID, Player ownerPlayer, Inventory sourceInventory, private void distributeItemsForOwner(UUID ownerUUID, Player ownerPlayer, Inventory sourceInventory,
String ownerNameOverride, Location sourceLocation) { String ownerNameOverride, Location sourceLocation) {
Location restLoc = getRestChestLocation(ownerUUID); List<Location> restLocs = getRestChestLocations(ownerUUID);
Map<String, List<Location>> targets = new HashMap<>(); Map<String, List<Location>> targets = new HashMap<>();
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
for (Map<String, Object> tc : mysqlManager.getTargetChests(ownerUUID.toString())) { for (Map<String, Object> tc : mysqlManager.getTargetChests(ownerUUID.toString())) {
@@ -2546,7 +2755,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
} }
distributeItemsForOwner(ownerUUID, ownerPlayer, sourceInventory, ownerNameOverride, sourceLocation, targets, restLoc); distributeItemsForOwner(ownerUUID, ownerPlayer, sourceInventory, ownerNameOverride, sourceLocation, targets, restLocs);
} }
private boolean checkSingleInputChest(UUID ownerUUID, Location location, String debugId, boolean crosslinkMode) { private boolean checkSingleInputChest(UUID ownerUUID, Location location, String debugId, boolean crosslinkMode) {
@@ -2554,7 +2763,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
private boolean checkSingleInputChest(UUID ownerUUID, Location location, String debugId, boolean crosslinkMode, private boolean checkSingleInputChest(UUID ownerUUID, Location location, String debugId, boolean crosslinkMode,
Map<String, List<Location>> preloadedTargets, Location preloadedRest) { Map<String, List<Location>> preloadedTargets, List<Location> preloadedRests) {
if (isWorldBlacklisted(location.getWorld())) return true; if (isWorldBlacklisted(location.getWorld())) return true;
if (!(location.getBlock().getState() instanceof Chest)) return false; if (!(location.getBlock().getState() instanceof Chest)) return false;
@@ -2599,7 +2808,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
// Wenn preloadedTargets null: synchron laden (Fallback) // Wenn preloadedTargets null: synchron laden (Fallback)
Map<String, List<Location>> effectiveTargets = preloadedTargets; Map<String, List<Location>> effectiveTargets = preloadedTargets;
Location effectiveRest = preloadedRest; List<Location> effectiveRests = preloadedRests;
if (effectiveTargets == null) { if (effectiveTargets == null) {
effectiveTargets = new HashMap<>(); effectiveTargets = new HashMap<>();
if (mysqlEnabled && mysqlManager != null) { if (mysqlEnabled && mysqlManager != null) {
@@ -2625,22 +2834,23 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
} }
if (effectiveRest == null && preloadedTargets == null) { // BUG FIX: Rest-Truhen als Liste laden wenn nicht vorgeladen
effectiveRest = getRestChestLocation(ownerUUID); if (effectiveRests == null) {
effectiveRests = getRestChestLocations(ownerUUID);
} }
distributeItemsForOwner(ownerUUID, ownerPlayer, chest.getInventory(), ownerName, location, effectiveTargets, effectiveRest); distributeItemsForOwner(ownerUUID, ownerPlayer, chest.getInventory(), ownerName, location, effectiveTargets, effectiveRests);
return true; return true;
} }
/** /**
* Oeffentliche Variante mit vorgeladenen Truhen-Locations (kein DB-Hit im Main Thread). * Oeffentliche Variante mit vorgeladenen Truhen-Locations (kein DB-Hit im Main Thread).
* targetChestMap: Material-Name → Location (lokale Zieltruhen) * targetChestMap: Material-Name → Location (lokale Zieltruhen)
* restChestLoc: lokale Rest-Truhe oder null * restChestLocs: lokale Rest-Truhen oder leere Liste
*/ */
private void distributeItemsForOwner(UUID ownerUUID, Player ownerPlayer, Inventory sourceInventory, private void distributeItemsForOwner(UUID ownerUUID, Player ownerPlayer, Inventory sourceInventory,
String ownerNameOverride, Location sourceLocation, String ownerNameOverride, Location sourceLocation,
Map<String, List<Location>> targetChestMap, Location restChestLoc) { Map<String, List<Location>> targetChestMap, List<Location> restChestLocs) {
boolean hasItems = false; boolean hasItems = false;
for (ItemStack item : sourceInventory.getContents()) { for (ItemStack item : sourceInventory.getContents()) {
@@ -2658,8 +2868,11 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (offlinePlayer.hasPlayedBefore()) ownerName = offlinePlayer.getName(); if (offlinePlayer.hasPlayedBefore()) ownerName = offlinePlayer.getName();
} }
Location restChestLocation = restChestLoc; // BUG FIX: Rest-Truhen als Liste verwalten
boolean restChestKnownFull = (restChestLocation != null) && isChestCachedFull(restChestLocation); List<Location> restChestLocations = (restChestLocs != null) ? restChestLocs : new ArrayList<>();
// Alle vollen Rest-Truhen ermitteln
boolean allRestChestsFull = !restChestLocations.isEmpty()
&& restChestLocations.stream().allMatch(l -> l != null && isChestCachedFull(l));
for (int slot = 0; slot < sourceInventory.getSize(); slot++) { for (int slot = 0; slot < sourceInventory.getSize(); slot++) {
ItemStack item = sourceInventory.getItem(slot); ItemStack item = sourceInventory.getItem(slot);
@@ -2676,12 +2889,16 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
boolean isRestChest = false; boolean isRestChest = false;
boolean isCrosslink = false; boolean isCrosslink = false;
// Aktive Rest-Truhe für dieses Item (erste nicht-volle)
Location activeRestChestLocation = null;
for (Location loc : restChestLocations) {
if (loc != null && !isChestCachedFull(loc)) { activeRestChestLocation = loc; break; }
}
if (targetChestLocation == null) { if (targetChestLocation == null) {
if (serverCrosslink && mysqlEnabled && mysqlManager != null) { if (serverCrosslink && mysqlEnabled && mysqlManager != null) {
Map<String, Object> raw = mysqlManager.getTargetChest(ownerUUID.toString(), item.getType().name()); Map<String, Object> raw = mysqlManager.getTargetChest(ownerUUID.toString(), item.getType().name());
if (raw != null && isRemoteChest(raw)) { if (raw != null && isRemoteChest(raw)) {
// ── BungeeCord NEU: expliziten Ziel-Server mitgeben ───────────
String targetServerName = getChestServer(raw); String targetServerName = getChestServer(raw);
isCrosslink = true; isCrosslink = true;
mysqlManager.setupTransferTable(); mysqlManager.setupTransferTable();
@@ -2698,15 +2915,16 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
if (!isCrosslink) { if (!isCrosslink) {
if (restChestKnownFull) continue; // BUG FIX: Alle Rest-Truhen prüfen, nicht nur eine
if (allRestChestsFull) continue;
if (restChestLocation != null) { if (activeRestChestLocation != null) {
targetChestLocation = restChestLocation; targetChestLocation = activeRestChestLocation;
isRestChest = true; isRestChest = true;
} else if (serverCrosslink && mysqlEnabled && mysqlManager != null) { } else if (serverCrosslink && mysqlEnabled && mysqlManager != null) {
Map<String, Object> raw = mysqlManager.getRestChest(ownerUUID.toString()); // Crosslink: Remote Rest-Truhe suchen
for (Map<String, Object> raw : mysqlManager.getRestChests(ownerUUID.toString())) {
if (raw != null && isRemoteChest(raw)) { if (raw != null && isRemoteChest(raw)) {
// ── BungeeCord NEU: expliziten Ziel-Server mitgeben ─────
String targetServerName = getChestServer(raw); String targetServerName = getChestServer(raw);
mysqlManager.setupTransferTable(); mysqlManager.setupTransferTable();
mysqlManager.addTransfer(ownerUUID.toString(), item.getType().name(), item.getAmount(), mysqlManager.addTransfer(ownerUUID.toString(), item.getType().name(), item.getAmount(),
@@ -2717,9 +2935,12 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
+ " → Server:'" + (targetServerName.isEmpty() ? "?" : targetServerName) + " → Server:'" + (targetServerName.isEmpty() ? "?" : targetServerName)
+ "' Welt:'" + raw.get("world") + "' (Rest-Transfer-DB)"); + "' Welt:'" + raw.get("world") + "' (Rest-Transfer-DB)");
} }
continue; isCrosslink = true;
break;
} }
} }
if (isCrosslink) continue;
}
} }
} else { } else {
// Bei voller Truhe: nächsten Slot in der Liste versuchen // Bei voller Truhe: nächsten Slot in der Liste versuchen
@@ -2741,9 +2962,36 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (ownerPlayer != null && canSendFullChestMessage(ownerUUID, item.getType())) { if (ownerPlayer != null && canSendFullChestMessage(ownerUUID, item.getType())) {
ownerPlayer.sendMessage(getMessage("target-chest-missing").replace("%item%", isRestChest ? "Rest-Truhe" : item.getType().name())); ownerPlayer.sendMessage(getMessage("target-chest-missing").replace("%item%", isRestChest ? "Rest-Truhe" : item.getType().name()));
} }
if (isRestChest) playerData.set("players." + ownerUUID + ".rest-chest", null); // BUG FIX: Beim MySQL-Modus playerData nicht anfassen; bei YAML korrekte Pfade
else playerData.set("players." + ownerUUID + ".target-chests." + item.getType().name(), null); if (isRestChest) {
if (mysqlEnabled && mysqlManager != null) {
mysqlManager.removeRestChestByLocation(ownerUUID.toString(),
targetChestLocation.getWorld().getName(),
targetChestLocation.getBlockX(), targetChestLocation.getBlockY(), targetChestLocation.getBlockZ());
} else {
String basePath = "players." + ownerUUID + ".rest-chests";
if (playerData.contains(basePath)) {
for (String slotKey : new ArrayList<>(playerData.getConfigurationSection(basePath).getKeys(false))) {
String rPath = basePath + "." + slotKey;
if (targetChestLocation.getWorld().getName().equals(playerData.getString(rPath + ".world"))
&& targetChestLocation.getBlockX() == playerData.getInt(rPath + ".x")
&& targetChestLocation.getBlockY() == playerData.getInt(rPath + ".y")
&& targetChestLocation.getBlockZ() == playerData.getInt(rPath + ".z")) {
playerData.set(rPath, null);
break;
}
}
}
// Legacy
playerData.set("players." + ownerUUID + ".rest-chest", null);
savePlayerData(); savePlayerData();
}
} else {
if (!mysqlEnabled) {
playerData.set("players." + ownerUUID + ".target-chests." + item.getType().name(), null);
savePlayerData();
}
}
continue; continue;
} }
@@ -2782,7 +3030,6 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
if (isFull) { if (isFull) {
markChestFull(targetChestLocation); markChestFull(targetChestLocation);
if (isRestChest) restChestKnownFull = true;
} }
if (signBlock != null) { if (signBlock != null) {
@@ -2829,6 +3076,27 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
if (isFull && isRestChest) { if (isFull && isRestChest) {
// BUG FIX: Nächste Rest-Truhe versuchen
Location nextRestLoc = null;
for (Location loc : restChestLocations) {
if (loc != null && !isChestCachedFull(loc) && !loc.equals(targetChestLocation)) {
nextRestLoc = loc; break;
}
}
if (nextRestLoc != null && nextRestLoc.getBlock().getState() instanceof Chest) {
Chest nextRestChest = (Chest) nextRestLoc.getBlock().getState();
Map<Integer, ItemStack> leftover2 = nextRestChest.getInventory().addItem(
leftover.isEmpty() ? new ItemStack(item.getType(), 0) : leftover.get(0).clone());
if (leftover2.isEmpty()) {
sourceInventory.setItem(slot, null);
spawnTransferParticles(null, nextRestLoc);
continue;
} else {
item.setAmount(leftover2.get(0).getAmount());
sourceInventory.setItem(slot, item);
}
} else {
// Alle Rest-Truhen voll: Nachricht senden
if (ownerPlayer != null && canSendFullChestMessage(ownerUUID, item.getType())) { if (ownerPlayer != null && canSendFullChestMessage(ownerUUID, item.getType())) {
String message = getMessage("target-chest-full") String message = getMessage("target-chest-full")
.replace("%item%", item.getType().name()) .replace("%item%", item.getType().name())
@@ -2847,6 +3115,7 @@ public class Main extends JavaPlugin implements Listener, CommandExecutor {
} }
} }
} }
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryMoveItem(InventoryMoveItemEvent event) { public void onInventoryMoveItem(InventoryMoveItemEvent event) {

View File

@@ -36,6 +36,39 @@ public class MySQLManager {
} }
} }
/**
* Migriert den PRIMARY KEY der asc_rest_chests von (uuid) auf (uuid, slot) falls nötig.
* Ermöglicht mehrere Rest-Truhen pro Spieler.
*/
private void migrateRestChestPrimaryKey(Statement st) {
try {
// Slot-Spalte zuerst sicherstellen
if (!columnExists("asc_rest_chests", "slot")) {
st.execute("ALTER TABLE asc_rest_chests ADD COLUMN slot INT NOT NULL DEFAULT 0;");
}
// Prüfen ob slot bereits im PRIMARY KEY ist
try (PreparedStatement ps = connection.prepareStatement(
"SELECT COUNT(*) FROM information_schema.KEY_COLUMN_USAGE " +
"WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'asc_rest_chests' " +
"AND CONSTRAINT_NAME = 'PRIMARY' AND COLUMN_NAME = 'slot';")) {
ResultSet rs = ps.executeQuery();
if (rs.next() && rs.getInt(1) > 0) {
rs.close();
return; // Bereits migriert
}
rs.close();
}
// Alten PK droppen und neuen mit slot anlegen
st.execute("ALTER TABLE asc_rest_chests DROP PRIMARY KEY, ADD PRIMARY KEY(uuid, slot);");
} catch (SQLException e) {
if (!e.getMessage().toLowerCase().contains("primary")) {
e.printStackTrace();
}
}
}
/** /**
* Migriert den PRIMARY KEY von (uuid, item) auf (uuid, item, slot) falls nötig. * Migriert den PRIMARY KEY von (uuid, item) auf (uuid, item, slot) falls nötig.
* Nutzt DATABASE() um nur die aktuelle DB zu prüfen (kein Cross-DB-Problem). * Nutzt DATABASE() um nur die aktuelle DB zu prüfen (kein Cross-DB-Problem).
@@ -88,7 +121,7 @@ public class MySQLManager {
*/ */
private void tryAlterColumn(Statement st, String table, String column, String definition) { private void tryAlterColumn(Statement st, String table, String column, String definition) {
try { try {
ResultSet rs = st.getConnection().getMetaData().getColumns(null, null, table, column); ResultSet rs = st.getConnection().getMetaData().getColumns(connection.getCatalog(), null, table, column);
if (!rs.next()) { if (!rs.next()) {
st.execute("ALTER TABLE " + table + " ADD COLUMN " + column + " " + definition + ";"); st.execute("ALTER TABLE " + table + " ADD COLUMN " + column + " " + definition + ";");
} }
@@ -105,7 +138,7 @@ public class MySQLManager {
*/ */
private boolean columnExists(String table, String column) { private boolean columnExists(String table, String column) {
try { try {
ResultSet rs = connection.getMetaData().getColumns(null, null, table, column); ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), null, table, column);
boolean exists = rs.next(); boolean exists = rs.next();
rs.close(); rs.close();
return exists; return exists;
@@ -168,9 +201,10 @@ public class MySQLManager {
");"); ");");
st.execute("CREATE TABLE IF NOT EXISTS asc_rest_chests (" + st.execute("CREATE TABLE IF NOT EXISTS asc_rest_chests (" +
"uuid VARCHAR(36), world VARCHAR(32)," + "uuid VARCHAR(36), slot INT NOT NULL DEFAULT 0," +
"world VARCHAR(32)," +
"x INT, y INT, z INT, `public` BOOLEAN DEFAULT FALSE," + "x INT, y INT, z INT, `public` BOOLEAN DEFAULT FALSE," +
"PRIMARY KEY(uuid)" + "PRIMARY KEY(uuid, slot)" +
");"); ");");
// ── asc_transfers: immer beim Start sicherstellen ───────────────────── // ── asc_transfers: immer beim Start sicherstellen ─────────────────────
@@ -207,6 +241,9 @@ public class MySQLManager {
// v2 → v3 (Multi-Target): slot-Spalte + PRIMARY KEY Migration // v2 → v3 (Multi-Target): slot-Spalte + PRIMARY KEY Migration
migrateTargetChestPrimaryKey(st); migrateTargetChestPrimaryKey(st);
// v2 → v3 (Multi-Rest): slot-Spalte + PRIMARY KEY Migration fuer Rest-Truhen
migrateRestChestPrimaryKey(st);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -593,32 +630,93 @@ public class MySQLManager {
setRestChest(uuid, world, x, y, z, isPublic, ""); setRestChest(uuid, world, x, y, z, isPublic, "");
} }
/** BungeeCord-Überladung mit serverName. */ /** BungeeCord-Überladung mit serverName ermittelt automatisch den nächsten freien Slot. */
public void setRestChest(String uuid, String world, int x, int y, int z, public void setRestChest(String uuid, String world, int x, int y, int z,
boolean isPublic, String serverName) { boolean isPublic, String serverName) {
// Prüfen ob diese exakte Location bereits als Rest-Truhe registriert ist (Update)
int slot = getRestSlotForLocation(uuid, world, x, y, z);
if (slot < 0) {
// Neue Truhe: nächsten freien Slot ermitteln
slot = getNextRestSlot(uuid);
}
setRestChest(uuid, slot, world, x, y, z, isPublic, serverName);
}
/** Vollständige Überladung mit explizitem slot. */
public void setRestChest(String uuid, int slot, String world, int x, int y, int z,
boolean isPublic, String serverName) {
try (PreparedStatement ps = connection.prepareStatement( try (PreparedStatement ps = connection.prepareStatement(
"REPLACE INTO asc_rest_chests (uuid, world, x, y, z, `public`, server) " + "REPLACE INTO asc_rest_chests (uuid, slot, world, x, y, z, `public`, server) " +
"VALUES (?, ?, ?, ?, ?, ?, ?);")) { "VALUES (?, ?, ?, ?, ?, ?, ?, ?);")) {
ps.setString(1, uuid); ps.setString(1, uuid);
ps.setString(2, world); ps.setInt(2, slot);
ps.setInt(3, x); ps.setString(3, world);
ps.setInt(4, y); ps.setInt(4, x);
ps.setInt(5, z); ps.setInt(5, y);
ps.setBoolean(6, isPublic); ps.setInt(6, z);
ps.setString(7, serverName != null ? serverName : ""); ps.setBoolean(7, isPublic);
ps.setString(8, serverName != null ? serverName : "");
ps.executeUpdate(); ps.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public Map<String, Object> getRestChest(String uuid) { /** Gibt den nächsten freien Slot für Rest-Truhen zurück. */
public int getNextRestSlot(String uuid) {
try (PreparedStatement ps = connection.prepareStatement( try (PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM asc_rest_chests WHERE uuid=?;")) { "SELECT COALESCE(MAX(slot)+1, 0) AS next_slot FROM asc_rest_chests WHERE uuid=?;")) {
ps.setString(1, uuid); ps.setString(1, uuid);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if (rs.next()) { if (rs.next()) return rs.getInt("next_slot");
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gibt den Slot zurück, den diese Location bereits belegt, oder -1 wenn nicht gefunden.
*/
public int getRestSlotForLocation(String uuid, String world, int x, int y, int z) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT slot FROM asc_rest_chests WHERE uuid=? AND world=? AND x=? AND y=? AND z=?;")) {
ps.setString(1, uuid);
ps.setString(2, world);
ps.setInt(3, x);
ps.setInt(4, y);
ps.setInt(5, z);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt("slot");
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/** Zählt wie viele Rest-Truhen ein Spieler hat. */
public int countRestChests(String uuid) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT COUNT(*) FROM asc_rest_chests WHERE uuid=?;")) {
ps.setString(1, uuid);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/** Gibt ALLE Rest-Truhen eines Spielers zurück, sortiert nach slot. */
public List<Map<String, Object>> getRestChests(String uuid) {
List<Map<String, Object>> list = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM asc_rest_chests WHERE uuid=? ORDER BY slot ASC;")) {
ps.setString(1, uuid);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("slot", rs.getInt("slot"));
map.put("world", rs.getString("world")); map.put("world", rs.getString("world"));
map.put("x", rs.getInt("x")); map.put("x", rs.getInt("x"));
map.put("y", rs.getInt("y")); map.put("y", rs.getInt("y"));
@@ -626,14 +724,72 @@ public class MySQLManager {
map.put("public", rs.getBoolean("public")); map.put("public", rs.getBoolean("public"));
try { map.put("server", rs.getString("server")); } try { map.put("server", rs.getString("server")); }
catch (SQLException ignored) { map.put("server", ""); } catch (SQLException ignored) { map.put("server", ""); }
return map; list.add(map);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return list;
} }
/** Gibt die erste Rest-Truhe (slot=0) zurück Legacy-Kompatibilität. */
public Map<String, Object> getRestChest(String uuid) {
List<Map<String, Object>> all = getRestChests(uuid);
return all.isEmpty() ? null : all.get(0);
}
/** Löscht eine spezifische Rest-Truhe anhand ihrer Location. */
public void removeRestChestByLocation(String uuid, String world, int x, int y, int z) {
try (PreparedStatement ps = connection.prepareStatement(
"DELETE FROM asc_rest_chests WHERE uuid=? AND world=? AND x=? AND y=? AND z=?;")) {
ps.setString(1, uuid);
ps.setString(2, world);
ps.setInt(3, x);
ps.setInt(4, y);
ps.setInt(5, z);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
// Slots nach dem gelöschten nach unten schieben um Lücken zu vermeiden
compactRestSlots(uuid);
}
/** Löscht eine spezifische Rest-Truhe anhand des Slots. */
public void removeRestChestSlot(String uuid, int slot) {
try (PreparedStatement ps = connection.prepareStatement(
"DELETE FROM asc_rest_chests WHERE uuid=? AND slot=?;")) {
ps.setString(1, uuid);
ps.setInt(2, slot);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
compactRestSlots(uuid);
}
/** Schiebt Rest-Slots nach dem gelöschten nach unten (keine Lücken). */
private void compactRestSlots(String uuid) {
try {
List<Map<String, Object>> remaining = getRestChests(uuid);
for (int i = 0; i < remaining.size(); i++) {
int currentSlot = (int) remaining.get(i).get("slot");
if (currentSlot != i) {
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE asc_rest_chests SET slot=? WHERE uuid=? AND slot=?;")) {
ps.setInt(1, i);
ps.setString(2, uuid);
ps.setInt(3, currentSlot);
ps.executeUpdate();
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/** Löscht ALLE Rest-Truhen eines Spielers. */
public void removeRestChest(String uuid) { public void removeRestChest(String uuid) {
try (PreparedStatement ps = connection.prepareStatement( try (PreparedStatement ps = connection.prepareStatement(
"DELETE FROM asc_rest_chests WHERE uuid=?;")) { "DELETE FROM asc_rest_chests WHERE uuid=?;")) {
@@ -694,11 +850,12 @@ public class MySQLManager {
public Map<String, Object> getAnyRestChest() { public Map<String, Object> getAnyRestChest() {
try (PreparedStatement ps = connection.prepareStatement( try (PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM asc_rest_chests WHERE public=1 LIMIT 1;")) { "SELECT * FROM asc_rest_chests WHERE `public`=1 ORDER BY uuid, slot LIMIT 1;")) {
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if (rs.next()) { if (rs.next()) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("uuid", rs.getString("uuid")); map.put("uuid", rs.getString("uuid"));
map.put("slot", rs.getInt("slot"));
map.put("world", rs.getString("world")); map.put("world", rs.getString("world"));
map.put("x", rs.getInt("x")); map.put("x", rs.getInt("x"));
map.put("y", rs.getInt("y")); map.put("y", rs.getInt("y"));

View File

@@ -10,7 +10,7 @@
# --- GRUNDLEGUNG --- # --- GRUNDLEGUNG ---
# Version der Konfigurationsdatei. Nicht ändern, um Fehler zu vermeiden! # Version der Konfigurationsdatei. Nicht ändern, um Fehler zu vermeiden!
version: "2.0" version: "2.2"
# Debug-Modus (true = Ausführliche Logs in der Server-Konsole, nur zum Entwickeln nutzen) # Debug-Modus (true = Ausführliche Logs in der Server-Konsole, nur zum Entwickeln nutzen)

View File

@@ -1,5 +1,5 @@
name: AutoSortChest name: AutoSortChest
version: 2.2 version: 2.3
main: com.viper.autosortchest.Main main: com.viper.autosortchest.Main
api-version: 1.21 api-version: 1.21
authors: [M_Viper] authors: [M_Viper]
@@ -25,3 +25,9 @@ permissions:
autosortchest.admin: autosortchest.admin:
description: Erlaubt OPs/Admins Zugriff auf fremde AutoSortChest-Truhen (Öffnen, Entnehmen, Abbauen) description: Erlaubt OPs/Admins Zugriff auf fremde AutoSortChest-Truhen (Öffnen, Entnehmen, Abbauen)
default: op default: op
autosortchest.limit.<gruppe>:
description: >
Limits fuer eine benutzerdefinierte Gruppe aus der config.yml.
Ersetze <gruppe> durch den Gruppennamen (z.B. autosortchest.limit.vip).
Die Gruppen und ihre Limits werden ausschliesslich in der config.yml definiert.
default: false