Compare commits

...
128 Commits
Author SHA1 Message Date
Edson Passos af8edd0a24 AddAlly, Coords, LanguageSelector, Leaderboard, Permissions 2025-03-16 21:07:57 -03:00
Edson Passos 2480bf47bc Check for enabled in drawer 2025-03-12 21:31:20 -03:00
Edson Passos f9de9966ec AlliesFrame, AddAllyFrame, AddRivalFrame, InviteFrame and other changes 2025-03-10 23:07:32 -03:00
Edson Passos f7304c00a7 LeaderboardFrame config and other changes 2025-03-09 16:45:16 -03:00
Edson Passos cd451a2f1f Merge branch 'master' into customizable-gui
# Conflicts:
#	SimpleClans.iml
#	dependency-reduced-pom.xml
#	pom.xml
#	src/main/java/net/sacredlabyrinth/phaed/simpleclans/managers/SettingsManager.java
#	src/main/java/net/sacredlabyrinth/phaed/simpleclans/ui/SCFrame.java
2025-03-08 23:06:22 -03:00
Edson Passos f7081499b2 fix: placeholders being parsed in clan chat 2025-03-08 21:30:35 -03:00
Edson Passos 0f50d498cb build: downgraded to JDK 8 (#459)
Removed built-in support for WorldGuard7 (https://github.com/RoinujNosde/SimpleClans-WorldGuard7)
2025-03-08 21:09:33 -03:00
Edson PassosandTomut0 da8d343897 feat: only send bungee messages to allowed servers (#455)
Co-authored-by: Tomut0 <minat0_@outlook.com>
2025-03-06 20:09:33 -03:00
Minat0_ ee1feb4276 fix: created_at migration should use prefixed table (#456) 2025-03-06 20:07:11 -03:00
Edson Passos 24af2c03d0 fix: missing import for charset 2025-03-05 20:07:50 -03:00
Edson PassosandTomut0 6b2a3f85ac feat: adds completions to clan create command (#452)
Co-authored-by: Tomut0 <minat0_@outlook.com>
2025-03-05 19:54:32 -03:00
Edson PassosandTomut0 57076fb033 fix: uuid bulk fetching over Mojang and minetools APIs (#451)
Co-authored-by: Tomut0 <minat0_@outlook.com>
2025-03-05 19:45:36 -03:00
RoinujNosde 52ff77e6c1 fix: no need to create ClanPlayer on placeholder request 2025-02-17 20:04:30 -03:00
Tomut0 146713fd48 fix: player can change locale even if selector is disabled 2025-02-08 20:40:50 -03:00
RoinujNosde c8e67cfd4f fix: Bukkit#getOfflinePlayers causing the server to hang 2025-02-08 20:31:08 -03:00
Tomut0 f4f47b2060 fix: clan disband should require a confirmation in gui 2025-01-30 21:12:59 -03:00
Minat0_ 13cf348084 feat: compile under Java 21 LTS (#446) 2025-01-19 19:07:44 -03:00
RoinujNosde b37512be7d fix: RequestManager requesting data from Mojang servers 2024-12-26 19:19:35 -03:00
RoinujNosde 9097fa02fa fix: getAnyClanPlayer(String) requesting data from Mojang servers 2024-12-21 20:34:17 -03:00
Minat0_ a759884b8d fix(discord): use fresh reference for guild and role objects and non-cached channels (#438) 2024-11-11 16:26:40 -03:00
Minat0_ f5e1387246 feat(db): add datetime column to sc_kills (#432)
Co-authored-by: Minat0_ <minat0_@outlook.com>
2024-11-08 22:53:24 -03:00
Edson PassosandMinat0_ cddde547b1 fix: missed name in /clan stats command
Co-authored-by: Minat0_ <minat0_@outlook.com>
2024-11-08 17:29:14 -03:00
Lucas f466a86309 feat: added reload event for better plugin integration (#441) 2024-09-24 19:02:20 -03:00
Edson Passos 9f4f39a420 feat(lang): new crowdin updates (#332) 2024-08-18 22:52:11 -03:00
Edson Passos 46702f90ab feat: added config for the db table prefix (#408) 2024-08-15 07:46:27 -03:00
Minat0_ 5a490b11a3 fix(discord): more debug messages for DiscordHook (#437) 2024-08-08 18:36:57 +03:00
Edson Passos 3b51299dd6 docs: added mikasa's banner 2024-06-12 16:08:19 -03:00
Edson Passos 5212296d62 fix: NPE while setting owner of skull 2024-05-12 12:35:27 -03:00
Edson Passos 67d3e70f58 fix: fire FrameOpenEvent sync 2024-04-25 16:25:14 -03:00
Edson Passos 8cd0b2e454 fix: order of FrameOpenEvent 2024-04-25 16:17:31 -03:00
RoinujNosde da9ec6c917 fix: players not getting removed from clans on purge 2024-04-19 20:17:25 -03:00
Nishikiyama cb314dbe7b feat: limit unverified clan members (#422) 2024-03-19 17:55:33 +03:00
ThiagoROX 01c79862b9 feat: add %simpleclans_is_invite_enabled% placeholder (#424) 2024-03-07 15:03:11 -03:00
Nishikiyama c9df6acb13 feat: possibility to set a default rank for new clans (#418) 2024-02-01 17:12:57 +03:00
Minat0_ ad910e9c30 fix(discord): bump DiscordSRV to 1.27.0 (#414)
Possibly fixes IncompatibleClassChangeError for newest DiscordSRV version.
2024-01-09 20:29:25 +03:00
Minat0_ d4d144fe36 fix: update the Mojang API endpoint (#413)
As of 23w42a, the "Usernames to UUIDs" endpoint moved to:
POST https://api.minecraftservices.com/minecraft/profile/lookup/bulk/byname
2024-01-08 15:27:08 +03:00
Minat0_ 1375679df8 fix(discord): revoke discord leader role on events (#411) 2024-01-06 14:49:02 +03:00
ThiagoROXandRoinujNosde b2c7d12b60 feat: added price and date formatters (#401)
Co-authored-by: RoinujNosde <edsonpassosjr@outlook.com>
2023-11-13 10:39:26 -03:00
Edson Passos b363efe530 fix: more fixes for RequestManager (#405) 2023-10-25 10:29:19 -03:00
RoinujNosde 876b5ac50e fix: rename command not checking length 2023-10-22 19:17:32 -03:00
Edson Passos d2825df01b fix: wrong request key in requestAllLeaders 2023-10-04 07:13:36 -03:00
RoinujNosde bc85864134 fix: players not able to vote on some requests
PROMOTE, RENAME and DISBAND

Also fixed the requester's name placeholder
2023-10-03 19:23:21 -03:00
WolfBot 4808addaa5 chore(master): release 2.19.3-SNAPSHOT (#399) 2023-08-03 19:38:27 -03:00
WolfBot 05e7abccbd chore(master): release 2.19.2 (#398) 2023-08-03 19:30:23 -03:00
WolfBot cfd1ff851d chore(master): release 2.19.2-SNAPSHOT (#395) 2023-08-03 19:24:05 -03:00
Minat0_ f29bc746af fix: cause check should return true on granting (#397) 2023-08-03 19:21:35 -03:00
WolfBot e12ee8aaed chore(master): release 2.19.1 (#393) 2023-08-03 13:22:44 -03:00
Edson Passos fe60b25f61 fix: charge money on deposit (#394) 2023-08-03 13:12:07 -03:00
Minat0_ 503d67903e fix: consider uppercase when checking for disallowed colors (#391) 2023-08-02 09:03:59 -03:00
Minat0_ e1625d38c8 ci: ensure running on maven 3.9.3 (#390)
* ci: Upgrade JDK to 16 at modrinth workflow

* ci: Upgrade JDK to 16 at curseforge workflow

* ci: ensure running on maven 3.9.3

* ci: ensure running on maven 3.9.3 (#389)

* Set executable permission for mvnw

* using newer release option for compiler plugin
2023-07-27 19:58:04 -03:00
WolfBot 4fa1aeaccc chore(master): release 2.19.1-SNAPSHOT (#387) 2023-07-27 16:55:43 -03:00
WolfBot 1b44edeec5 chore(master): release 2.19.0 (#340) 2023-07-27 16:54:35 -03:00
d21dc02dff feat: EconomyTransactionEvent creation (#384)
Co-authored-by: Anony <contacto@anderhurtado.com>
Co-authored-by: Tomut0 <minat0_@outlook.com>
2023-07-27 16:53:11 -03:00
Minat0_ ad6bb7b13b feat: hide reset kdr in main frame if perm denied (#385) 2023-07-23 20:56:42 +03:00
Minat0_ 8269d80831 fix: resets error message when validating a clan tag (#383) 2023-06-23 19:44:32 +03:00
Minat0_ 57b9987e9b fix: tnt explosion doesn't count a kill (#381) 2023-06-20 00:02:47 +03:00
ThiagoROX f8ce0f415f feat: add %simpleclans_has_rank% placeholder (#379) 2023-06-20 00:01:04 +03:00
3ef3169942 feat: validating tag by regex (#363)
* Special Characters

* Changed default value from True to False

* Apparently useless in the PR

* Changed cleanTag.toLowerCase() to cleanTag
replaced string cleanTag = ChatUtils.stripColors(this.tag) with string cleanTag = Helper.cleanTag(tag);

* added simpleclans.iml back to fix any errors

* Added SimpleClans.iml to .gitignore; correct me if i'm wrong, but I believe this is for the better.

* Added 'SimpleClans.iml' to .gitignore :)

~ Side note: Shoot me a message if this should be undone.

* Added original SimpleClans.iml

I have no idea what went wrong last time.

* fix: bb migration settings save

* feat: tag regex implement

* refactor tag length set

* delete auto-generated files from git

* optimize imports

* speed up tag validation process by creating one TagValidator per plugin reload

rollback accept-other-alphabets-letters-on-tag

* we don't need to save config twice on bb migration

* don't create new instance of tagValidator on plugin reload

* fix even if regex matches it checks the alphabet

---------

Co-authored-by: BuildTools <unconfigured@null.spigotmc.org>
Co-authored-by: Tomut0 <minat0_@outlook.com>
2023-06-17 18:52:55 +03:00
Minat0_ 5cf64a672d feat: add a command to set player's locale (#378) 2023-06-17 00:28:22 +03:00
Minat0_ c49b2d9dc2 Merge pull request #375 from Tomut0/dev 2023-05-12 17:53:59 +03:00
Tomut0 8801e8e855 build: add surface plugin, upgrade tests to JUnit 5 2023-05-12 17:41:07 +03:00
Tomut0 bc4775c293 build: upgrade javadoc plugin, suppress warnings on build 2023-05-12 17:40:32 +03:00
Tomut0 74e39c2666 I don't think we need META-INF file anymore
It's a maven task to create it, I believe
2023-05-12 17:40:32 +03:00
Tomut0 f73e798e65 ci: upload artifact with jdk 16 2023-05-12 17:40:32 +03:00
Tomut0 f101ea4768 build: delete dependency-reduced-pom.xml from git 2023-05-12 17:40:32 +03:00
Tomut0 f5d547ab27 docs: author tag isn't available at methods 2023-05-12 17:40:31 +03:00
Minat0_ 7fcb964f41 fix: prevent clan name renaming with colors (#374) 2023-05-12 16:15:08 +03:00
ThiagoROX d4f1a74dee feat: add confirmation before reset kdr (#371) 2023-05-10 21:03:29 +03:00
Edson Passos 3e192a70da build: update junit 2023-05-09 19:55:18 -03:00
Edson Passos 103f1e56c7 ci: update Reposilite workflow 2023-05-07 18:06:14 -03:00
Edson Passos 103b4055f3 ci: update CI workflow 2023-05-07 17:52:28 -03:00
RoinujNosde c91442cd1e Merge remote-tracking branch 'origin/master' 2023-05-07 17:47:49 -03:00
RoinujNosde e368ead04a fix: bump JDK to 16 2023-05-07 17:47:23 -03:00
ThiagoROX d68ec28f8e feat: add PlayerResetKdrEvent (#370) 2023-05-03 12:16:22 +03:00
RoinujNosde 2f4ad00f1c fix: migrates land permissions on GP claim resize 2023-04-30 18:40:23 -03:00
RoinujNosde 524e407620 fix: NPE on EntityDamageByEntityEvent listener (LandProtection) 2023-04-30 18:14:21 -03:00
ThiagoROX 992166de66 ci: update checkout and setup-java actions (#369) 2023-04-28 00:18:07 +03:00
ThiagoROX 0b74355467 fix: display hex message on bulletin board (#365) 2023-04-26 20:30:53 +03:00
ThiagoROX 105a8cad51 feat: add subcommand /clan mod bb display (#367) 2023-04-26 19:26:15 +03:00
Minat0_ 0f693329ca feat: adds the possibility to rename a clan (#360) 2023-03-26 18:45:29 -03:00
Minat0_ 263d129325 feat: bb message language key (#358) 2023-03-21 22:37:24 -03:00
ThiagoROX 442096e9da fix: added clan suggestion in staff bb commands (#359) 2023-03-19 21:32:59 -03:00
Minat0_ 36084dbfa3 perf(discord): remove discord channels from creation (#353) 2023-02-13 08:53:31 -03:00
RoinujNosde 8a05dbbf00 fix: possibly fixes CME on SpyChatHandler 2023-01-31 18:47:08 -03:00
Minat0_ 8a3529377f fix(discord): permission overrides reset only existing members (#349) 2023-01-28 21:26:28 -03:00
Minat0_ 5f519c477a fix: remove abandoned channels before validating (#348) 2023-01-27 23:30:32 -03:00
Minat0_ 7eb748bb9a fix: async permission reset & category deletion (#347) 2023-01-27 20:46:12 -03:00
Minat0_ 18507016a8 fix: view permission applies only to cached channels (#346) 2023-01-20 16:53:02 -03:00
Edson Passos ed243f72ec fix(bungee): updates kills count immediately 2023-01-08 20:42:29 -03:00
RoinujNosde 5021b8ad7b fix: players not able to strip logs/fertilize blocks 2023-01-03 19:37:17 -03:00
Edson Passos f98868c776 fix: invalid colors being used in tags, pt. 2
* Added test for another invalid variant
* Updated patterns
2023-01-03 16:29:48 -03:00
RoinujNosde 2850e59d37 fix: invalid colors being used in tags 2023-01-02 19:35:42 -03:00
RoinujNosde 86d4fac938 fix: players not able to break vehicles/exit horses 2022-12-28 20:12:00 -03:00
RoinujNosde 707a6bfb66 Refactored processLang 2022-12-27 19:09:57 -03:00
Edson Passos 0258a75c81 fix(bungee): removes players from clan on delete 2022-12-27 09:56:34 -03:00
RoinujNosde f5ae7e23c3 Fixed error when config was missing 2022-12-25 17:44:38 -03:00
RoinujNosde 61dcb3d440 fix: players unable to interact with armor stands, paintings, etc 2022-12-24 17:26:50 -03:00
RoinujNosde bf1033af76 fix: default username-regex 2022-12-23 20:28:04 -03:00
RoinujNosde 807d39afeb fix: players not able to use water buckets (WorldGuard) 2022-12-23 20:27:37 -03:00
RoinujNosde bc046d4b2a refactor: code cleanup on LandProtection 2022-12-22 22:20:18 -03:00
RoinujNosde 91845abea3 Some refactoring 2022-12-22 18:24:10 -03:00
RoinujNosde 545dd1652f Merge remote-tracking branch 'origin/master' 2022-12-21 21:29:57 -03:00
RoinujNosde e9ec283ace fix: players not able to sleep on beds (WorldGuard) 2022-12-21 21:29:19 -03:00
RoinujNosde 7cb55f6177 Move getConfig() to SettingsManager 2022-12-20 22:03:10 -03:00
RoinujNosde 949943fb5e Decorations 2022-12-18 17:02:25 -03:00
RoinujNosde 56b4b64d21 Enabled state for Components, XMaterial updated 2022-12-17 18:55:47 -03:00
RoinujNosde b3324574da Refactored AddPermissionFrame 2022-12-14 19:51:47 -03:00
RoinujNosde edd4c46a9e Generified Paginator, added PageableFrame 2022-12-11 19:56:07 -03:00
RoinujNosde 91c701a729 Merge branch 'master' into customizable-gui 2022-12-11 16:43:37 -03:00
RoinujNosde 45ef2ce219 Added ArrayBuilder - WIP 2022-12-10 20:52:18 -03:00
RoinujNosde dd676565e2 Made realistic changes to GUI config 2022-12-08 19:39:26 -03:00
Minat0_ 718868b2d9 docs: updated version in README (#343) 2022-12-08 08:41:10 -03:00
Edson Passos 2a139aba03 feat(chat): adds permissions to use colors and formats (#341) 2022-12-04 13:06:15 -03:00
RoinujNosde 046aa1d96d fix: sets duplicate names to something unique 2022-11-30 20:01:40 -03:00
WolfBot e44775e994 chore(master): release 2.18.2-SNAPSHOT (#339) 2022-11-29 19:54:00 -03:00
WolfBot 43da5bd1f1 chore(master): release 2.18.1 (#335) 2022-11-29 19:53:16 -03:00
Minat0_ 8fa465da38 fix: missing getHandlerList on HomeRegroupEvent (#338) 2022-11-29 14:48:31 -03:00
RoinujNosde 56c7908c33 fix(bungee): error deserializing clan banners 2022-11-23 20:14:14 -03:00
RoinujNosde fc81e76521 fix: added check for clan_member on land commands 2022-11-18 19:21:01 -03:00
RoinujNosde f7fe5c4ad4 refactor: ignore unknown subchannels 2022-11-08 20:19:57 -03:00
RoinujNosde 8f4f763c37 refactor: added debug messages to BungeeManager 2022-11-04 23:15:09 -03:00
RoinujNosde 7a37382264 fix: default ranks were getting re-added on config load 2022-11-03 20:37:29 -03:00
RoinujNosde 7f9d133051 fix: channel auto creation setting not respected on join/link 2022-11-02 14:55:00 -03:00
RoinujNosde 26ba9f7329 fix: attempt at fixing NPE on getAllClanPlayers 2022-11-01 21:43:31 -03:00
Minat0_ d8cb61b0fc fix: money was not given back when channel creation failed (#336) 2022-10-31 18:39:26 -03:00
Minat0_ 3f1b06dcf9 fix: wrong path of discord economy section (#334) 2022-10-31 17:14:10 -03:00
WolfBot b043eb0742 chore(master): release 2.18.1-SNAPSHOT (#331) 2022-10-14 18:15:11 -03:00
RoinujNosde 6a570cf003 Added example config and readConfig() method 2022-09-25 19:07:40 -03:00
166 changed files with 8117 additions and 2989 deletions

No files matched your search

+7 -7
View File
@@ -15,23 +15,23 @@ jobs:
fail-fast: true
max-parallel: 4
matrix:
java-version: [ 8, 11, 16, 17 ]
java-version: [ 16, 21, 23]
runs-on: ubuntu-latest
name: Java ${{ matrix.java-version }}
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: "Set up JDK ${{ matrix.java-version }}"
uses: actions/setup-java@v2
uses: actions/setup-java@v4
with:
java-version: "${{ matrix.java-version }}"
distribution: 'adopt'
distribution: 'temurin'
cache: 'maven'
- name: Build with Maven
run: mvn -B -U package --file pom.xml
run: ./mvnw -B -U package --file pom.xml
- name: Upload Build Artifact
if: "${{ matrix.java-version == 8 }}"
uses: actions/upload-artifact@v2
if: "${{ matrix.java-version == 16 }}"
uses: actions/upload-artifact@v4
with:
name: SimpleClans
path: target/SimpleClans.jar
+8 -8
View File
@@ -7,15 +7,15 @@ jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v2
- uses: actions/checkout@v4
- name: Set up JDK 16
uses: actions/setup-java@v4
with:
java-version: 8
java-version: 16
cache: 'maven'
distribution: 'adopt'
distribution: 'temurin'
- name: Build with Maven
run: mvn -B package --file pom.xml
run: ./mvnw -B package --file pom.xml
- name: Upload artifact
uses: itsmeow/curseforge-upload@v3
with:
@@ -26,6 +26,6 @@ jobs:
changelog: ${{ github.event.release.body }}
changelog_type: markdown
display_name: ${{ github.event.release.tag_name }}
game_versions: 8849,8503,7915,7667,7330,7105,6588,630,591,585,531
game_versions: 11515,9974,9190,8849,8503,7915,7667,7330,7105,6588,630,591,585,531
release_type: release
relations: vault:optionalDependency,worldguard:optionalDependency,grief-prevention:optionalDependency
relations: vault:optionalDependency,worldguard:optionalDependency,grief-prevention:optionalDependency,plotsquared:optionalDependency
+7 -7
View File
@@ -7,15 +7,15 @@ jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v2
- uses: actions/checkout@v4
- name: Set up JDK 16
uses: actions/setup-java@v4
with:
java-version: 8
java-version: 16
cache: 'maven'
distribution: 'adopt'
distribution: 'temurin'
- name: Build with Maven
run: mvn -B package --file pom.xml
run: ./mvnw -B package --file pom.xml
- name: Upload artifact
uses: RubixDev/modrinth-upload@v1.0.0
with:
@@ -25,7 +25,7 @@ jobs:
changelog: ${{ github.event.release.body }}
name: ${{ github.event.release.tag_name }}
version: ${{ github.event.release.tag_name }}
game_versions: 1.19,1.18,1.17,1.16,1.15,1.14,1.13,1.12,1.11,1.10,1.9,1.8
game_versions: 1.21,1.20,1.19,1.18,1.17,1.16,1.15,1.14,1.13,1.12,1.11,1.10,1.9,1.8
release_type: release
loaders: spigot
featured: true
+7 -7
View File
@@ -10,20 +10,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v2
- uses: actions/checkout@v4
- name: Set up JDK 16
uses: actions/setup-java@v4
with:
java-version: 8
java-version: 16
server-id: reposilite # Value of the distributionManagement/repository/id field of the pom.xml
server-username: MAVEN_USERNAME
server-password: MAVEN_PASSWORD
cache: 'maven'
distribution: 'adopt'
distribution: 'temurin'
- name: Build with Maven
run: mvn -B package --file pom.xml
run: ./mvnw -B package --file pom.xml
- name: Publish to Reposilite
run: mvn -B deploy
run: ./mvnw -B deploy
env:
MAVEN_USERNAME: simpleclans
MAVEN_PASSWORD: ${{ secrets.REPOSILITE_TOKEN }}
+2 -1
View File
@@ -3,7 +3,8 @@
/bin/
/.classpath
/.project
/dependency-reduced-pom.xml
*.jar
.settings
.factorypath
SimpleClans.iml
dependency-reduced-pom.xml
+19
View File
@@ -0,0 +1,19 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
+85
View File
@@ -1,5 +1,90 @@
# Changelog
## [2.19.2](https://github.com/RoinujNosde/SimpleClans/compare/v2.19.1...v2.19.2) (2023-08-03)
### Bug Fixes
* cause check should return true on granting ([#397](https://github.com/RoinujNosde/SimpleClans/issues/397)) ([f29bc74](https://github.com/RoinujNosde/SimpleClans/commit/f29bc746af4940b493ebc43b1e25ff0fc00ab8d0))
## [2.19.1](https://github.com/RoinujNosde/SimpleClans/compare/v2.19.0...v2.19.1) (2023-08-03)
### Bug Fixes
* charge money on deposit ([#394](https://github.com/RoinujNosde/SimpleClans/issues/394)) ([fe60b25](https://github.com/RoinujNosde/SimpleClans/commit/fe60b25f6107281a9771f6498400c3f8ce81c916))
* consider uppercase when checking for disallowed colors ([#391](https://github.com/RoinujNosde/SimpleClans/issues/391)) ([503d679](https://github.com/RoinujNosde/SimpleClans/commit/503d67903e386b1c4b6eb7903a1addbfd42a684a))
## [2.19.0](https://github.com/RoinujNosde/SimpleClans/compare/v2.18.1...v2.19.0) (2023-07-27)
### Features
* add %simpleclans_has_rank% placeholder ([#379](https://github.com/RoinujNosde/SimpleClans/issues/379)) ([f8ce0f4](https://github.com/RoinujNosde/SimpleClans/commit/f8ce0f415f17748f8b4382e028dd1f5f93cae06a))
* add a command to set player's locale ([#378](https://github.com/RoinujNosde/SimpleClans/issues/378)) ([5cf64a6](https://github.com/RoinujNosde/SimpleClans/commit/5cf64a672d0a25a62d3abd6720082bb3b4cf056f))
* add confirmation before reset kdr ([#371](https://github.com/RoinujNosde/SimpleClans/issues/371)) ([d4f1a74](https://github.com/RoinujNosde/SimpleClans/commit/d4f1a74dee9cdeeb458ff6975715a817bfe30fa1))
* add PlayerResetKdrEvent ([#370](https://github.com/RoinujNosde/SimpleClans/issues/370)) ([d68ec28](https://github.com/RoinujNosde/SimpleClans/commit/d68ec28f8e14926cbe9d13c09a61735e5304a97d))
* add subcommand /clan mod bb display ([#367](https://github.com/RoinujNosde/SimpleClans/issues/367)) ([105a8ca](https://github.com/RoinujNosde/SimpleClans/commit/105a8cad51b12bf6f487cf6c2b81eb85d966a3cc))
* adds the possibility to rename a clan ([#360](https://github.com/RoinujNosde/SimpleClans/issues/360)) ([0f69332](https://github.com/RoinujNosde/SimpleClans/commit/0f693329cae81036bfe1423344ed41cf3d535f64))
* bb message language key ([#358](https://github.com/RoinujNosde/SimpleClans/issues/358)) ([263d129](https://github.com/RoinujNosde/SimpleClans/commit/263d129325888fb1303dda549986ab43ca93ed13))
* **chat:** adds permissions to use colors and formats ([#341](https://github.com/RoinujNosde/SimpleClans/issues/341)) ([2a139ab](https://github.com/RoinujNosde/SimpleClans/commit/2a139aba03be174086dfb3603007312d0c7a6c33))
* EconomyTransactionEvent creation ([#384](https://github.com/RoinujNosde/SimpleClans/issues/384)) ([d21dc02](https://github.com/RoinujNosde/SimpleClans/commit/d21dc02dff45f4f20a40303cd26215a71de7dddb))
* hide reset kdr in main frame if perm denied ([#385](https://github.com/RoinujNosde/SimpleClans/issues/385)) ([ad6bb7b](https://github.com/RoinujNosde/SimpleClans/commit/ad6bb7b13b347be71789fbfb4b8a82f6c5481c96))
* validating tag by regex ([#363](https://github.com/RoinujNosde/SimpleClans/issues/363)) ([3ef3169](https://github.com/RoinujNosde/SimpleClans/commit/3ef3169942f897280af15040f1243d955df001ab))
### Bug Fixes
* added clan suggestion in staff bb commands ([#359](https://github.com/RoinujNosde/SimpleClans/issues/359)) ([442096e](https://github.com/RoinujNosde/SimpleClans/commit/442096e9da98410682c2cd09e0e930454fe0364f))
* async permission reset & category deletion ([#347](https://github.com/RoinujNosde/SimpleClans/issues/347)) ([7eb748b](https://github.com/RoinujNosde/SimpleClans/commit/7eb748bb9a31a826f53fd7ac6b1eeac64e330467))
* bump JDK to 16 ([e368ead](https://github.com/RoinujNosde/SimpleClans/commit/e368ead04aa2735f5525d88d5dcb63b78286f80e))
* **bungee:** removes players from clan on delete ([0258a75](https://github.com/RoinujNosde/SimpleClans/commit/0258a75c819f12e5dbbaf383a572682717f34c59))
* **bungee:** updates kills count immediately ([ed243f7](https://github.com/RoinujNosde/SimpleClans/commit/ed243f72ecc58a3af11d053d73b315bce9e20e94))
* default username-regex ([bf1033a](https://github.com/RoinujNosde/SimpleClans/commit/bf1033af769bacbca9a790d2184ec77eeb519485))
* **discord:** permission overrides reset only existing members ([#349](https://github.com/RoinujNosde/SimpleClans/issues/349)) ([8a35293](https://github.com/RoinujNosde/SimpleClans/commit/8a3529377f5b4a482b530e474e4921b311197a04))
* display hex message on bulletin board ([#365](https://github.com/RoinujNosde/SimpleClans/issues/365)) ([0b74355](https://github.com/RoinujNosde/SimpleClans/commit/0b74355467625a4901944c72feb84d8de91a4283))
* invalid colors being used in tags ([2850e59](https://github.com/RoinujNosde/SimpleClans/commit/2850e59d370da34c643de198de85d91744610467))
* invalid colors being used in tags, pt. 2 ([f98868c](https://github.com/RoinujNosde/SimpleClans/commit/f98868c776a2e275dc7c1647748a0231e935f43e))
* migrates land permissions on GP claim resize ([2f4ad00](https://github.com/RoinujNosde/SimpleClans/commit/2f4ad00f1c72ee7e3948267965c3a075ec4ef728))
* NPE on EntityDamageByEntityEvent listener (LandProtection) ([524e407](https://github.com/RoinujNosde/SimpleClans/commit/524e40762011dd500a407286b72b51acf6c357f3))
* players not able to break vehicles/exit horses ([86d4fac](https://github.com/RoinujNosde/SimpleClans/commit/86d4fac938e353f94c288c39b884027027972bba))
* players not able to sleep on beds (WorldGuard) ([e9ec283](https://github.com/RoinujNosde/SimpleClans/commit/e9ec283ace55af10abdeb6f937d31d4c2dc198dc))
* players not able to strip logs/fertilize blocks ([5021b8a](https://github.com/RoinujNosde/SimpleClans/commit/5021b8ad7b5633769bd87af96a0226a53a8b24b4))
* players not able to use water buckets (WorldGuard) ([807d39a](https://github.com/RoinujNosde/SimpleClans/commit/807d39afeb51d99a96fb793099393b44e2c43b04))
* players unable to interact with armor stands, paintings, etc ([61dcb3d](https://github.com/RoinujNosde/SimpleClans/commit/61dcb3d440e2eedfb717afcc69687194311a8973))
* possibly fixes CME on SpyChatHandler ([8a05dbb](https://github.com/RoinujNosde/SimpleClans/commit/8a05dbbf00df97afa7df71a500e2626aaa46ed37))
* prevent clan name renaming with colors ([#374](https://github.com/RoinujNosde/SimpleClans/issues/374)) ([7fcb964](https://github.com/RoinujNosde/SimpleClans/commit/7fcb964f41118e7d8746e87d5770cc329730834c))
* remove abandoned channels before validating ([#348](https://github.com/RoinujNosde/SimpleClans/issues/348)) ([5f519c4](https://github.com/RoinujNosde/SimpleClans/commit/5f519c477af3e759596017010d51ddd06e26157e))
* resets error message when validating a clan tag ([#383](https://github.com/RoinujNosde/SimpleClans/issues/383)) ([8269d80](https://github.com/RoinujNosde/SimpleClans/commit/8269d80831533e517ed2ebd94bec18021de7b0e3))
* sets duplicate names to something unique ([046aa1d](https://github.com/RoinujNosde/SimpleClans/commit/046aa1d96d58e21496a3361c7d072f3943595304))
* tnt explosion doesn't count a kill ([#381](https://github.com/RoinujNosde/SimpleClans/issues/381)) ([57b9987](https://github.com/RoinujNosde/SimpleClans/commit/57b9987e9b9dade59c52c88dbfd3b12fdf5eee94))
* view permission applies only to cached channels ([#346](https://github.com/RoinujNosde/SimpleClans/issues/346)) ([1850701](https://github.com/RoinujNosde/SimpleClans/commit/18507016a843c28efc6d8109f2bb5a5106531f47))
### Performance Improvements
* **discord:** remove discord channels from creation ([#353](https://github.com/RoinujNosde/SimpleClans/issues/353)) ([36084db](https://github.com/RoinujNosde/SimpleClans/commit/36084dbfa3e73aedccb156e49af5062e40639927))
### Documentation
* author tag isn't available at methods ([f5d547a](https://github.com/RoinujNosde/SimpleClans/commit/f5d547ab27fac7cfe1abd9c819e4f1bb3dd7c624))
* updated version in README ([#343](https://github.com/RoinujNosde/SimpleClans/issues/343)) ([718868b](https://github.com/RoinujNosde/SimpleClans/commit/718868b2d9eea2aeb6fcfd734e85d16a2cefaa36))
## [2.18.1](https://github.com/RoinujNosde/SimpleClans/compare/v2.18.0...v2.18.1) (2022-11-29)
### Bug Fixes
* added check for clan_member on land commands ([fc81e76](https://github.com/RoinujNosde/SimpleClans/commit/fc81e765211bebe22a7a6aa5d5158754580bbdc5))
* attempt at fixing NPE on getAllClanPlayers ([26ba9f7](https://github.com/RoinujNosde/SimpleClans/commit/26ba9f73296a772eaa698d2ede6fbc3831da850c))
* **bungee:** error deserializing clan banners ([56c7908](https://github.com/RoinujNosde/SimpleClans/commit/56c7908c332167cec9cca6a4ea054977d0d68b9f))
* channel auto creation setting not respected on join/link ([7f9d133](https://github.com/RoinujNosde/SimpleClans/commit/7f9d133051b9011837d0a5114abc6c3637a3f02c))
* default ranks were getting re-added on config load ([7a37382](https://github.com/RoinujNosde/SimpleClans/commit/7a37382264ff4dd5456f6930045b5102bf491897))
* missing getHandlerList on HomeRegroupEvent ([#338](https://github.com/RoinujNosde/SimpleClans/issues/338)) ([8fa465d](https://github.com/RoinujNosde/SimpleClans/commit/8fa465da385f36b1fb075031c375ef94df78ea52))
* money was not given back when channel creation failed ([#336](https://github.com/RoinujNosde/SimpleClans/issues/336)) ([d8cb61b](https://github.com/RoinujNosde/SimpleClans/commit/d8cb61b0fc9584bb58f421faf98596816621053f))
* wrong path of discord economy section ([#334](https://github.com/RoinujNosde/SimpleClans/issues/334)) ([3f1b06d](https://github.com/RoinujNosde/SimpleClans/commit/3f1b06dcf996e51a878b7fc281069e236ebcbfce))
## [2.18.0](https://github.com/RoinujNosde/SimpleClans/compare/v2.17.0...v2.18.0) (2022-10-14)
+5 -2
View File
@@ -60,7 +60,7 @@ Including SimpleClans with Maven:
<dependency>
<groupId>net.sacredlabyrinth.phaed.simpleclans</groupId>
<artifactId>SimpleClans</artifactId>
<version>2.17.0</version> <!-- You can find the latest version at the bottom -->
<version>2.18.1</version> <!-- You can find the latest version at the bottom -->
<scope>provided</scope>
</dependency>
</dependencies>
@@ -74,7 +74,7 @@ repositories {
}
}
dependencies {
compileOnly "net.sacredlabyrinth.phaed.simpleclans:SimpleClans:2.17.0"
compileOnly "net.sacredlabyrinth.phaed.simpleclans:SimpleClans:2.18.1"
}
```
@@ -83,3 +83,6 @@ Feel free to learn our [Javadoc](https://ci.roinujnosde.me/job/SimpleClans/Javad
[![Maven metadata URL](https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Frepo.roinujnosde.me%2Freleases%2Fnet%2Fsacredlabyrinth%2Fphaed%2Fsimpleclans%2FSimpleClans%2Fmaven-metadata.xml)](https://repo.roinujnosde.me/#/releases/net/sacredlabyrinth/phaed/simpleclans/SimpleClans)
##### API Examples
* [Examples of how to use the API](https://simpleclans.gitbook.io/simpleclans/other/simpleclans-api)
[![Mikasa Host](https://mikasa.host/images/partners/banners/SimpleClans.gif)](https://mikasa.host/ref/6)
-145
View File
@@ -1,145 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot-api:1.16.4-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.guava:guava:21.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.md-5:bungeecord-chat:1.16-R0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.yaml:snakeyaml:1.26" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.MilkBowl:VaultAPI:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.bukkit:bukkit:1.13.1-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" name="Maven: org.bstats:bstats-bukkit:2.2.1" level="project" />
<orderEntry type="library" name="Maven: org.bstats:bstats-base:2.2.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: me.clip:placeholderapi:2.10.9" level="project" />
<orderEntry type="library" name="Maven: org.jetbrains:annotations:22.0.0" level="project" />
<orderEntry type="library" name="Maven: io.papermc:paperlib:1.0.8-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: co.aikar:acf-paper:0.5.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: com.github.cryptomorin:XSeries:8.3.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.7.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.7.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldguard:worldguard-bukkit:7.0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldedit:worldedit-bukkit:7.2.0-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldguard:worldguard-core:7.0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldguard.worldguard-libs:core:7.0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldedit:worldedit-core:7.2.0-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q.worldedit.worldedit-libs:core:7.2.0-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: de.schlichtherle:truezip:6.8.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-profile-default_2.13:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.scala-lang:scala-library:2.13.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-http:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-kernel-spec:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-annotations:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.code.findbugs:annotations:3.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-cio:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-io:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-services:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-logging:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.httpcomponents:httpclient:4.5.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.httpcomponents:httpcore:4.4.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-odf:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-comp-zipdriver:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-comp-zip:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.bouncycastle:bcprov-jdk15on:1.63" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-tar:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-comp-tardriver:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.commons:commons-compress:1.19" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-tar-bzip2:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-tar-gzip:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-tar-xz:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.tukaani:xz:1.8" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-zip-raes:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-profile-base_2.13:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-access-swing:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-access:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-file:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-jar:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-driver-zip:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-comp-ibm437:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truevfs:truevfs-kernel-impl_2.13:0.12.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-key-console:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-key-default:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-key-swing:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-key-macosx:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-key-spec:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.truecommons:truecommons-shed:2.5.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.dev.jna:jna:4.1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.mozilla:rhino-runtime:1.7.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: it.unimi.dsi:fastutil:8.2.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.antlr:antlr4-runtime:4.7.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.flywaydb:flyway-core:3.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sk89q:commandbook:2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.TechFortress:GriefPrevention:16.17.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.discordsrv:discordsrv:1.24.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.dv8tion:JDA:4.3.0_349" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.code.findbugs:jsr305:3.0.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.squareup.okhttp3:okhttp:3.13.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.squareup.okio:okio:1.17.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.commons:commons-collections4:4.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.10.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.10.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.fasterxml.jackson.core:jackson-core:2.10.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.neovisionaries:nv-websocket-client:2.14" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.sf.trove4j:trove4j:3.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: github.scarsz:configuralize:1.3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.alexheretic:dynamics:4.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.alexheretic:fluent:2.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.slf4j:slf4j-jdk14:1.7.25" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.slf4j:jcl-over-slf4j:1.7.25" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:2.8.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-collections:commons-collections:3.2.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.commons:commons-lang3:3.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-codec:commons-codec:1.11" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.vdurmont:emoji-java:5.1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.json:json:20170516" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.zafarkhaja:java-semver:0.9.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.kevinsawicki:http-request:6.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.minidns:minidns-hla:1.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.minidns:minidns-dnssec:1.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.minidns:minidns-client:1.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.minidns:minidns-core:1.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.minidns:minidns-iterative-resolver:1.0.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-expression:5.2.7.RELEASE" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-core:5.2.7.RELEASE" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: dev.vankka:MCDiscordReserializer:4.2.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: dev.vankka:SimpleAST:2.2.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-api:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-key:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:examination-api:1.3.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:examination-string:1.3.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-serializer-legacy:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-serializer-gson:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-serializer-plain:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-platform-bukkit:4.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-platform-api:4.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-serializer-bungeecord:4.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-nbt:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-serializer-gson-legacy-impl:4.9.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-platform-facet:4.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-platform-viaversion:4.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.kyori:adventure-text-minimessage:4.1.0-20210316.192746" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: biz.princeps:landlord-latest:4.351" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: biz.princeps:landlord-core:4.351" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: biz.princeps:landlord-api:4.351" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.zaxxer:HikariCP:4.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: io.github.bananapuncher714:nbteditor:7.16.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: de.eldoria:eldo-util:1.9.1" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.9.1" level="project" />
</component>
</module>
-412
View File
@@ -1,412 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.sacredlabyrinth.phaed.simpleclans</groupId>
<artifactId>SimpleClans</artifactId>
<name>SimpleClans</name>
<version>2.17.1-SNAPSHOT</version>
<url>https://www.spigotmc.org/resources/simpleclans.71242/</url>
<build>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>*.properties</include>
</includes>
</resource>
</resources>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.metrics</shadedPattern>
</relocation>
<relocation>
<pattern>io.papermc.lib</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.paperlib</shadedPattern>
</relocation>
<relocation>
<pattern>co.aikar.commands</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.acf</shadedPattern>
</relocation>
<relocation>
<pattern>co.aikar.locales</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.locales</shadedPattern>
</relocation>
<relocation>
<pattern>com.cryptomorin.xseries</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.xseries</shadedPattern>
</relocation>
<relocation>
<pattern>com.google.gson</pattern>
<shadedPattern>net.sacredlabyrinth.phaed.simpleclans.gson</shadedPattern>
</relocation>
</relocations>
<artifactSet>
<excludes>
<exclude>org.jetbrains:annotations</exclude>
</excludes>
</artifactSet>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-installed</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<type>${project.packaging}</type>
</artifactItem>
</artifactItems>
<outputDirectory>${env.TEST_SERVER}\plugins</outputDirectory>
<silent>true</silent>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>javadoc</goal>
</goals>
</execution>
</executions>
<configuration>
<source>8</source>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>placeholderapi-repo</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>bstats-repo</id>
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>Scarsz-Nexus</id>
<url>https://nexus.scarsz.me/content/groups/public/</url>
</repository>
<repository>
<id>eldonexus</id>
<url>https://eldonexus.de/repository/maven-public</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>bukkit</artifactId>
<groupId>org.bukkit</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>22.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>apiguardian-api</artifactId>
<groupId>org.apiguardian</groupId>
</exclusion>
<exclusion>
<artifactId>opentest4j</artifactId>
<groupId>org.opentest4j</groupId>
</exclusion>
<exclusion>
<artifactId>junit-platform-commons</artifactId>
<groupId>org.junit.platform</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.4</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>worldedit-bukkit</artifactId>
<groupId>com.sk89q.worldedit</groupId>
</exclusion>
<exclusion>
<artifactId>worldguard-core</artifactId>
<groupId>com.sk89q.worldguard</groupId>
</exclusion>
<exclusion>
<artifactId>commandbook</artifactId>
<groupId>com.sk89q</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.TechFortress</groupId>
<artifactId>GriefPrevention</artifactId>
<version>16.17.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.discordsrv</groupId>
<artifactId>discordsrv</artifactId>
<version>1.24.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>JDA</artifactId>
<groupId>net.dv8tion</groupId>
</exclusion>
<exclusion>
<artifactId>nv-websocket-client</artifactId>
<groupId>com.neovisionaries</groupId>
</exclusion>
<exclusion>
<artifactId>trove4j</artifactId>
<groupId>net.sf.trove4j</groupId>
</exclusion>
<exclusion>
<artifactId>configuralize</artifactId>
<groupId>github.scarsz</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-jdk14</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jcl-over-slf4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>commons-io</artifactId>
<groupId>commons-io</groupId>
</exclusion>
<exclusion>
<artifactId>commons-collections</artifactId>
<groupId>commons-collections</groupId>
</exclusion>
<exclusion>
<artifactId>commons-lang3</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
<exclusion>
<artifactId>emoji-java</artifactId>
<groupId>com.vdurmont</groupId>
</exclusion>
<exclusion>
<artifactId>java-semver</artifactId>
<groupId>com.github.zafarkhaja</groupId>
</exclusion>
<exclusion>
<artifactId>http-request</artifactId>
<groupId>com.github.kevinsawicki</groupId>
</exclusion>
<exclusion>
<artifactId>minidns-hla</artifactId>
<groupId>org.minidns</groupId>
</exclusion>
<exclusion>
<artifactId>spring-expression</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>MCDiscordReserializer</artifactId>
<groupId>dev.vankka</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-api</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-text-serializer-legacy</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-text-serializer-gson</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-text-serializer-plain</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-platform-bukkit</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-text-minimessage</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>biz.princeps</groupId>
<artifactId>landlord-latest</artifactId>
<version>4.351</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>landlord-core</artifactId>
<groupId>biz.princeps</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>reposilite</id>
<url>https://repo.roinujnosde.me/releases/</url>
</repository>
<snapshotRepository>
<id>reposilite</id>
<url>https://repo.roinujnosde.me/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Vendored Executable
+259
View File
@@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
Vendored
+149
View File
@@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+61 -35
View File
@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>net.sacredlabyrinth.phaed.simpleclans</groupId>
<artifactId>SimpleClans</artifactId>
<version>2.18.0</version>
<version>2.19.3-SNAPSHOT</version>
<name>SimpleClans</name>
<url>https://www.spigotmc.org/resources/simpleclans.71242/</url>
@@ -16,8 +16,7 @@
<filtering>true</filtering>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>**/*.yml</include>
<include>*.properties</include>
</includes>
</resource>
@@ -29,10 +28,9 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<version>3.13.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<release>8</release>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
<compilerArgs>
@@ -45,21 +43,21 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<version>3.4.2</version>
</plugin>
<!-- Release plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.3.2</version>
<version>3.1.1</version>
</plugin>
<!-- Shade plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<version>3.6.0</version>
<configuration>
<relocations>
<relocation>
@@ -92,6 +90,13 @@
<exclude>org.jetbrains:annotations</exclude>
</excludes>
</artifactSet>
<transformers>
<!-- Avoid overlapping MANIFEST.MF file -->
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>MANIFEST.MF</resource>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
@@ -107,7 +112,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<version>3.7.1</version>
<executions>
<execution>
<id>copy-installed</id>
@@ -132,9 +137,9 @@
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>3.0.0</version>
<groupId>io.github.git-commit-id</groupId>
<artifactId>git-commit-id-maven-plugin</artifactId>
<version>9.0.1</version>
<executions>
<execution>
<goals>
@@ -151,7 +156,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.2</version>
<version>3.10.1</version>
<executions>
<execution>
<goals>
@@ -161,9 +166,15 @@
</execution>
</executions>
<configuration>
<source>8</source>
<release>8</release>
<doclint>all,-missing</doclint>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
<!-- Dependencies -->
@@ -179,23 +190,30 @@
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
<exclusions>
<!-- No idea why, but it fails JUnit 5 tests -->
<exclusion>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>2.2.1</version>
<version>3.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<version>2.11.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>22.0.0</version>
<version>24.0.1</version>
</dependency>
<dependency>
<groupId>io.papermc</groupId>
@@ -211,42 +229,50 @@
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>XSeries</artifactId>
<version>8.3.0</version>
<version>11.2.0.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.4</version>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.1.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.TechFortress</groupId>
<artifactId>GriefPrevention</artifactId>
<version>16.17.1</version>
<version>17.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.discordsrv</groupId>
<artifactId>discordsrv</artifactId>
<version>1.24.1-SNAPSHOT</version>
<version>1.28.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>biz.princeps</groupId>
<artifactId>landlord-latest</artifactId>
<version>4.351</version>
<version>4.363</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.1</version>
<version>2.10.1</version>
</dependency>
<!-- Test frameworks -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -266,7 +292,7 @@
</repository>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<repository>
<id>aikar</id>
@@ -306,4 +332,4 @@
<url>https://repo.roinujnosde.me/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
</project>
-3
View File
@@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: net.sacredlabyrinth.phaed.simpleclans.SimpleClans
@@ -524,7 +524,7 @@ public class ChatBlock {
* Outputs a single line out, crops overflow
*
* @param receiver the receiver
* @param msg the message
* @param msg the message
*/
public static void saySingle(CommandSender receiver, String msg) {
if (receiver == null) {
@@ -538,7 +538,7 @@ public class ChatBlock {
* Outputs a message to a user
*
* @param receiver the receiver
* @param msg the message
* @param msg the message
*/
public static void sendMessage(@Nullable CommandSender receiver, @NotNull String msg) {
if (receiver == null) {
@@ -561,6 +561,10 @@ public class ChatBlock {
sendMessage(receiver, lang(key, receiver, args));
}
public static void sendMessageKey(@NotNull ClanPlayer clanPlayer, @NotNull String key, @NotNull Object... args) {
sendMessageKey(clanPlayer.toPlayer(), key, args);
}
@Deprecated
public void startColor(String color) {
this.color = color;
@@ -1,5 +1,6 @@
package net.sacredlabyrinth.phaed.simpleclans;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.sacredlabyrinth.phaed.simpleclans.events.*;
@@ -9,6 +10,8 @@ import net.sacredlabyrinth.phaed.simpleclans.loggers.BankLogger;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.DateFormat;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
@@ -112,13 +115,13 @@ public class Clan implements Serializable, Comparable<Clan> {
@Deprecated
public void deposit(double amount, Player player) {
if (SimpleClans.getInstance().getPermissionsManager().playerHasMoney(player, amount)) {
if (SimpleClans.getInstance().getPermissionsManager().playerChargeMoney(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.deposit", player, amount));
addBb(player.getName(), AQUA + lang("bb.clan.deposit", amount));
if (SimpleClans.getInstance().getPermissionsManager().chargePlayer(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.deposit", player, CurrencyFormat.format(amount)));
addBb(player.getName(), lang("bb.clan.deposit", CurrencyFormat.format(amount)));
setBalance(getBalance() + amount);
SimpleClans.getInstance().getStorageManager().updateClan(this);
} else {
player.sendMessage(AQUA + lang("not.sufficient.money", player, amount));
player.sendMessage(AQUA + lang("not.sufficient.money", player, CurrencyFormat.format(amount)));
}
} else {
player.sendMessage(AQUA + lang("not.sufficient.money", player, amount));
@@ -149,9 +152,9 @@ public class Clan implements Serializable, Comparable<Clan> {
@Deprecated
public void withdraw(double amount, Player player) {
if (getBalance() >= amount) {
if (SimpleClans.getInstance().getPermissionsManager().playerGrantMoney(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.withdraw", player, amount));
addBb(player.getName(), AQUA + lang("bb.clan.withdraw", amount));
if (SimpleClans.getInstance().getPermissionsManager().grantPlayer(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.withdraw", player, CurrencyFormat.format(amount)));
addBb(player.getName(), lang("bb.clan.withdraw", CurrencyFormat.format(amount)));
setBalance(getBalance() - amount);
}
} else {
@@ -245,6 +248,16 @@ public class Clan implements Serializable, Comparable<Clan> {
return balance;
}
/**
* Returns the clan's balance formatted
*
* @return the balance formatted
*/
@Placeholder("balance_formatted")
public String getBalanceFormatted() {
return CurrencyFormat.format(balance);
}
/**
* (used internally)
*
@@ -292,7 +305,6 @@ public class Clan implements Serializable, Comparable<Clan> {
public void setTag(String tag) {
this.tag = tag;
}
/**
* Returns the first color in the clan's tag
*
@@ -453,7 +465,7 @@ public class Clan implements Serializable, Comparable<Clan> {
*/
@Placeholder("founded")
public String getFoundedString() {
return new java.text.SimpleDateFormat("MMM dd, ''yy h:mm a").format(new Date(this.founded));
return DateFormat.formatDateTime(founded);
}
/**
@@ -492,6 +504,9 @@ public class Clan implements Serializable, Comparable<Clan> {
SimpleClans.getInstance().getStorageManager().updateClan(this);
}
public void setBb(List<String> bb) {
this.bb = new ArrayList<>(bb);
}
/**
* Adds a bulletin board message without saving it to the database
@@ -1277,8 +1292,8 @@ public class Clan implements Serializable, Comparable<Clan> {
*/
public void addBb(String announcerName, String msg) {
if (isVerified()) {
addBb(SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR) + msg);
clanAnnounce(announcerName, SimpleClans.getInstance().getSettingsManager().getColored(BB_ACCENT_COLOR) + "* " + SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR) + ChatUtils.parseColors(msg));
addBb(msg);
clanAnnounce(announcerName, SimpleClans.getInstance().getSettingsManager().getColored(BB_PREFIX) + ChatUtils.parseColors(msg));
}
}
@@ -1287,8 +1302,8 @@ public class Clan implements Serializable, Comparable<Clan> {
*/
public void addBb(String announcerName, String msg, boolean updateLastUsed) {
if (isVerified()) {
addBb(SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR) + msg, updateLastUsed);
clanAnnounce(announcerName, SimpleClans.getInstance().getSettingsManager().getColored(BB_ACCENT_COLOR) + "* " + SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR) + ChatUtils.parseColors(msg));
addBb(msg, updateLastUsed);
clanAnnounce(announcerName, SimpleClans.getInstance().getSettingsManager().getColored(BB_PREFIX) + ChatUtils.parseColors(msg));
}
}
@@ -1305,31 +1320,35 @@ public class Clan implements Serializable, Comparable<Clan> {
* @param maxSize amount of lines to display
*/
public void displayBb(Player player, int maxSize) {
if (isVerified()) {
ChatBlock.sendBlank(player);
String bbAccentColor = SimpleClans.getInstance().getSettingsManager().getColored(BB_ACCENT_COLOR);
String pageHeadingsColor = SimpleClans.getInstance().getSettingsManager().getColored(PAGE_HEADINGS_COLOR);
ChatBlock.saySingle(player, lang("bulletin.board.header", bbAccentColor, pageHeadingsColor, getName()));
List<String> localBb;
if (maxSize == -1) {
localBb = bb;
maxSize = SimpleClans.getInstance().getSettingsManager().getInt(BB_SIZE);
} else {
localBb = new ArrayList<>(bb);
}
while (localBb.size() > maxSize) {
localBb.remove(0);
}
for (String msg : localBb) {
if (!sendBbTime(player, msg)) {
String bbColor = SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR);
ChatBlock.sendMessage(player, bbAccentColor + "* " + bbColor + ChatUtils.parseColors(msg));
}
}
ChatBlock.sendBlank(player);
if (!isVerified()) {
return;
}
SettingsManager settings = SimpleClans.getInstance().getSettingsManager();
ChatBlock.sendBlank(player);
ChatBlock.saySingle(player, lang("bulletin.board.header", getName()));
List<String> localBb;
if (maxSize == -1) {
localBb = bb;
maxSize = settings.getInt(BB_SIZE);
} else {
localBb = new ArrayList<>(bb);
}
while (localBb.size() > maxSize) {
localBb.remove(0);
}
for (String msg : localBb) {
if (!sendBbTime(player, msg)) {
String bbPrefix = settings.getColored(BB_PREFIX);
ChatBlock.sendMessage(player, bbPrefix + ChatUtils.parseColors(msg));
}
}
ChatBlock.sendBlank(player);
}
/**
@@ -1345,16 +1364,19 @@ public class Clan implements Serializable, Comparable<Clan> {
if (index < 1) {
return false;
}
String bbPrefix = SimpleClans.getInstance().getSettingsManager().getColored(BB_PREFIX);
long time = (System.currentTimeMillis() - Long.parseLong(msg.substring(0, index))) / 1000L;
String bbAccentColor = SimpleClans.getInstance().getSettingsManager().getColored(BB_ACCENT_COLOR);
String bbColor = SimpleClans.getInstance().getSettingsManager().getColored(BB_COLOR);
msg = ChatUtils.parseColors(bbAccentColor + "* " + bbColor + msg.substring(++index));
TextComponent textComponent = new TextComponent(msg);
textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(
msg = ChatUtils.parseColors(bbPrefix + msg.substring(++index));
BaseComponent[] baseComponent = TextComponent.fromLegacyText(msg);
TextComponent textMessage = new TextComponent(baseComponent);
textMessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(
Dates.formatTime(time, 1) + lang("bb.ago"))));
player.spigot().sendMessage(textComponent);
player.spigot().sendMessage(textMessage);
return true;
} catch (Throwable rock) {
} catch (Exception rock) {
return false;
}
}
@@ -1371,7 +1393,7 @@ public class Clan implements Serializable, Comparable<Clan> {
List<Clan> clans = SimpleClans.getInstance().getClanManager().getClans();
if (isPermanent() && !force) {
ChatBlock.sendMessage(sender, RED + lang("cannot.disband.permanent"));
ChatBlock.sendMessage(sender, RED + lang("cannot.disband.permanent", sender));
return;
}
@@ -1404,17 +1426,18 @@ public class Clan implements Serializable, Comparable<Clan> {
String disbanded = lang("clan.disbanded");
if (c.removeWarringClan(this)) {
c.addBb(disbanded, AQUA + lang("you.are.no.longer.at.war", c.getName(), getColorTag()));
c.addBb(disbanded, lang("you.are.no.longer.at.war", c.getName(), getColorTag()));
}
if (c.removeRival(getTag())) {
c.addBb(disbanded, AQUA + lang("has.been.disbanded.rivalry.ended", getName()));
c.addBb(disbanded, lang("has.been.disbanded.rivalry.ended", getName()));
}
if (c.removeAlly(getTag())) {
c.addBb(disbanded, AQUA + lang("has.been.disbanded.alliance.ended", getName()));
c.addBb(disbanded, lang("has.been.disbanded.alliance.ended", getName()));
}
}
SimpleClans.getInstance().getRequestManager().removeRequest(getTag());
SimpleClans.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(SimpleClans.getInstance(), () -> {
@@ -1462,7 +1485,7 @@ public class Clan implements Serializable, Comparable<Clan> {
warring.add(targetClan.getTag());
flags.put(WARRING_KEY, warring);
if (requestPlayer != null) {
addBb(requestPlayer.getName(), AQUA + lang("you.are.at.war",
addBb(requestPlayer.getName(), lang("you.are.at.war",
getName(), targetClan.getColorTag()));
}
SimpleClans.getInstance().getStorageManager().updateClan(this);
@@ -3,6 +3,7 @@ package net.sacredlabyrinth.phaed.simpleclans;
import net.sacredlabyrinth.phaed.simpleclans.hooks.papi.Placeholder;
import net.sacredlabyrinth.phaed.simpleclans.managers.ProtectionManager.Action;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.DateFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.VanishUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -487,8 +488,7 @@ public class ClanPlayer implements Serializable, Comparable<ClanPlayer> {
if (joinDate == 0) {
return "";
}
return new java.text.SimpleDateFormat("MMM dd, ''yy h:mm a").format(new Date(joinDate));
return DateFormat.formatDateTime(joinDate);
}
/**
@@ -512,7 +512,7 @@ public class ClanPlayer implements Serializable, Comparable<ClanPlayer> {
if (!VanishUtils.isVanished(sender, this)) {
return lang("online", sender);
}
return new java.text.SimpleDateFormat("MMM dd, ''yy h:mm a").format(new Date(lastSeen));
return DateFormat.formatDateTime(lastSeen);
}
/**
@@ -777,6 +777,7 @@ public class ClanPlayer implements Serializable, Comparable<ClanPlayer> {
SimpleClans.getInstance().getStorageManager().updateClanPlayer(this);
}
@Placeholder("is_invite_enabled")
public boolean isInviteEnabled() {
return flags.getBoolean("invite", true);
}
@@ -823,6 +824,11 @@ public class ClanPlayer implements Serializable, Comparable<ClanPlayer> {
return "";
}
@Placeholder("has_rank")
public boolean hasRank() {
return !getRankId().isEmpty();
}
@Placeholder("rank")
public @NotNull String getRankId() {
return flags.getString("rank", "");
@@ -6,5 +6,5 @@ package net.sacredlabyrinth.phaed.simpleclans;
*/
public enum ClanRequest
{
DEMOTE, PROMOTE, DISBAND, INVITE, CREATE_ALLY, BREAK_RIVALRY, START_WAR, END_WAR
DEMOTE, PROMOTE, DISBAND, INVITE, CREATE_ALLY, BREAK_RIVALRY, START_WAR, END_WAR, RENAME
}
@@ -75,7 +75,9 @@ public class Dates {
}
/**
* @author RoboMWM, LaxWasHere
* <p>
* authors: RoboMWM, LaxWasHere
* </p>
* @param seconds the time in seconds
* @param depth Max amount of detail (e.g. only display days and hours if set to 1 and seconds {@literal >} 1 day)
* @return the string representation of the amount of time labeled as days, hours, minutes, seconds
@@ -20,8 +20,7 @@ public final class Request {
private ClanPlayer requester;
private int askCount;
public Request(SimpleClans plugin,
ClanRequest type,
public Request(ClanRequest type,
@Nullable List<ClanPlayer> acceptors,
ClanPlayer requester,
String target,
@@ -3,18 +3,20 @@ package net.sacredlabyrinth.phaed.simpleclans;
import co.aikar.commands.BukkitCommandIssuer;
import net.sacredlabyrinth.phaed.simpleclans.commands.SCCommandManager;
import net.sacredlabyrinth.phaed.simpleclans.hooks.papi.SimpleClansExpansion;
import net.sacredlabyrinth.phaed.simpleclans.language.LanguageMigration;
import net.sacredlabyrinth.phaed.simpleclans.language.LanguageResource;
import net.sacredlabyrinth.phaed.simpleclans.listeners.*;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankLogger;
import net.sacredlabyrinth.phaed.simpleclans.loggers.CSVBankLogger;
import net.sacredlabyrinth.phaed.simpleclans.managers.*;
import net.sacredlabyrinth.phaed.simpleclans.migrations.BbMigration;
import net.sacredlabyrinth.phaed.simpleclans.migrations.ChatFormatMigration;
import net.sacredlabyrinth.phaed.simpleclans.migrations.LanguageMigration;
import net.sacredlabyrinth.phaed.simpleclans.proxy.BungeeManager;
import net.sacredlabyrinth.phaed.simpleclans.proxy.ProxyManager;
import net.sacredlabyrinth.phaed.simpleclans.tasks.*;
import net.sacredlabyrinth.phaed.simpleclans.ui.InventoryController;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatFormatMigration;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.TagValidator;
import net.sacredlabyrinth.phaed.simpleclans.utils.UpdateChecker;
import net.sacredlabyrinth.phaed.simpleclans.uuid.UUIDMigration;
import org.bstats.bukkit.Metrics;
@@ -62,6 +64,7 @@ public class SimpleClans extends JavaPlugin {
private static final Pattern ACF_PLACEHOLDER_PATTERN = Pattern.compile("\\{(?<key>[a-zA-Z]+?)}");
private BankLogger bankLogger;
private TagValidator tagValidator;
/**
* @return the logger
@@ -98,6 +101,8 @@ public class SimpleClans extends JavaPlugin {
instance = this;
new LanguageMigration(this).migrate();
settingsManager = new SettingsManager(this);
new BbMigration(settingsManager);
new ChatFormatMigration(settingsManager);
languageResource = new LanguageResource();
this.hasUUID = UUIDMigration.canReturnUUID();
@@ -110,12 +115,13 @@ public class SimpleClans extends JavaPlugin {
protectionManager = new ProtectionManager();
protectionManager.registerListeners();
chatManager = new ChatManager(this);
migrateChatFormat();
registerEvents();
permissionsManager.loadPermissions();
commandManager = new SCCommandManager(this);
bankLogger = new CSVBankLogger(this);
tagValidator = new TagValidator(settingsManager, permissionsManager);
logStatus();
startTasks();
startMetrics();
@@ -141,12 +147,6 @@ public class SimpleClans extends JavaPlugin {
pm.registerEvents(new FriendlyFire(this), this);
}
private void migrateChatFormat() {
ChatFormatMigration chatFormatMigration = new ChatFormatMigration();
chatFormatMigration.migrateAllyChat();
chatFormatMigration.migrateClanChat();
}
private void hookIntoPAPI() {
if (getPluginManager().getPlugin("PlaceholderAPI") != null) {
getLogger().info("PlaceholderAPI found. Registering hook...");
@@ -176,6 +176,7 @@ public class SimpleClans extends JavaPlugin {
metrics.addCustomChart(new SimplePie("threads", () -> sm.is(PERFORMANCE_USE_THREADS) ? on : off));
metrics.addCustomChart(new SimplePie("bungeecord", () -> sm.is(PERFORMANCE_USE_BUNGEECORD) ? on : off));
metrics.addCustomChart(new SimplePie("discord_chat", () -> sm.is(DISCORDCHAT_ENABLE) ? on : off));
metrics.addCustomChart(new SimplePie("default_rank", () -> sm.getString(CLAN_DEFAULT_RANK).isEmpty() ? off : on));
}
private void startTasks() {
@@ -354,4 +355,8 @@ public class SimpleClans extends JavaPlugin {
public void setUUID(boolean trueOrFalse) {
this.hasUUID = trueOrFalse;
}
public TagValidator getTagValidator() {
return tagValidator;
}
}
@@ -2,7 +2,10 @@ package net.sacredlabyrinth.phaed.simpleclans;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class War {
private final Map<Clan, Integer> clans = new HashMap<>();
@@ -2,15 +2,15 @@ package net.sacredlabyrinth.phaed.simpleclans.chat;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.ChatManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.PermissionsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
public interface ChatHandler {
SimpleClans plugin = SimpleClans.getInstance();
SettingsManager settingsManager = plugin.getSettingsManager();
ChatManager chatManager = plugin.getChatManager();
PermissionsManager permissionsManager = plugin.getPermissionsManager();
void sendMessage(SCMessage message);
@@ -13,6 +13,7 @@ import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.Con
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.PERFORMANCE_USE_BUNGEECORD;
import static org.bukkit.Bukkit.getPluginManager;
@SuppressWarnings("unused")
public class SpigotChatHandler implements ChatHandler {
@Override
@@ -30,7 +31,7 @@ public class SpigotChatHandler implements ChatHandler {
if (event.isCancelled()) {
return;
}
message.setContent(event.getMessage());
message.setContent(stripColorsAndFormatsPerPermission(message.getSender(),event.getMessage()));
ConfigField configField = ConfigField.valueOf(String.format("%sCHAT_FORMAT",
message.getSource() == DISCORD ? "DISCORD" : message.getChannel()));
@@ -47,6 +48,24 @@ public class SpigotChatHandler implements ChatHandler {
}.runTask(plugin);
}
private String stripColorsAndFormatsPerPermission(ClanPlayer sender, String message) {
if (!permissionsManager.has(sender.toPlayer(), "simpleclans.member.chat.color")) {
message = stripColors(message);
}
if (!permissionsManager.has(sender.toPlayer(), "simpleclans.member.chat.format")) {
message = stripFormats(message);
}
return message;
}
private String stripColors(String message) {
return message.replaceAll("[§&][0-9a-fA-FxX]", "");
}
private String stripFormats(String message) {
return message.replaceAll("[§&][k-orK-OR]", "");
}
@Override
public boolean canHandle(SCMessage.Source source) {
return source == SPIGOT || (source == PROXY && settingsManager.is(PERFORMANCE_USE_BUNGEECORD))
@@ -7,6 +7,7 @@ import net.sacredlabyrinth.phaed.simpleclans.chat.SCMessage;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import org.bukkit.Bukkit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -43,9 +44,9 @@ public class SpyChatHandler implements ChatHandler {
}
private List<ClanPlayer> getOnlineSpies() {
return Bukkit.getOnlinePlayers().stream().
return new ArrayList<>(Bukkit.getOnlinePlayers()).stream().
filter(Objects::nonNull).
filter(player -> plugin.getPermissionsManager().has(player, "simpleclans.admin.all-seeing-eye")).
filter(player -> permissionsManager.has(player, "simpleclans.admin.all-seeing-eye")).
map(player -> plugin.getClanManager().getCreateClanPlayer(player.getUniqueId())).
filter(Objects::nonNull).
filter(clanPlayer -> !clanPlayer.isMuted()).
@@ -38,17 +38,18 @@ import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.Con
public class SCCommandManager extends PaperCommandManager {
private final SimpleClans plugin;
private static final List<String> SUBCOMMANDS;
private static final List<String> COMPLETIONS;
public SCCommandManager(@NotNull SimpleClans plugin) {
super(plugin);
this.plugin = plugin;
configure();
}
private void configure() {
enableUnstableAPI("help");
registerDependencies();
addCommandReplacements();
addReplacements();
registerContexts();
registerCommands();
registerConditions();
@@ -107,11 +108,11 @@ public class SCCommandManager extends PaperCommandManager {
AbstractCondition obj = c.getConstructor(SimpleClans.class).newInstance(plugin);
if (obj instanceof AbstractParameterCondition) {
@SuppressWarnings("rawtypes")
AbstractParameterCondition condition = (AbstractParameterCondition) obj;
AbstractParameterCondition condition = ((AbstractParameterCondition<?>) obj);
getCommandConditions().addCondition(condition.getType(), condition.getId(), condition);
}
if (obj instanceof AbstractCommandCondition) {
AbstractCommandCondition condition = (AbstractCommandCondition) obj;
AbstractCommandCondition condition = ((AbstractCommandCondition) obj);
getCommandConditions().addCondition(condition.getId(), condition);
}
} catch (Exception ex) {
@@ -162,7 +163,7 @@ public class SCCommandManager extends PaperCommandManager {
}
}
private void addCommandReplacements() {
private void addReplacements() {
SettingsManager sm = plugin.getSettingsManager();
getCommandReplacements().addReplacements(
"basic_conditions", "not_blacklisted|not_banned",
@@ -174,17 +175,10 @@ public class SCCommandManager extends PaperCommandManager {
"clan_chat", sm.getString(COMMANDS_CLAN_CHAT)
);
SUBCOMMANDS.forEach(s -> {
String command = optionalLang(s + ".command", (ClanPlayer) null);
if (command == null) {
command = s;
}
command = command.replace(" ", "");
String replacement = command.equals(s) ? s : command + "|" + s;
getCommandReplacements().addReplacement(s, replacement);
});
SUBCOMMANDS.forEach(s -> processReplacement(s, "", ".command", true));
COMPLETIONS.forEach(s -> processReplacement(s, "compl:", ".completion", false));
}
@Override
public BukkitLocales getLocales() {
if (this.locales == null) {
@@ -215,15 +209,31 @@ public class SCCommandManager extends PaperCommandManager {
return this.locales;
}
private void processReplacement(String key, String prefix, String suffix, boolean hasFallback) {
String replacement = optionalLang(key + suffix, (ClanPlayer) null);
if (replacement == null) {
replacement = key;
}
replacement = replacement.replace(" ", "");
if (hasFallback) {
replacement = replacement + "|" + key;
}
getCommandReplacements().addReplacement(prefix + key, replacement);
}
static {
SUBCOMMANDS = Arrays.asList("setbanner", "resetkdr", "place", "rank", "home", "war", "regroup",
"mostkilled", "kills", "globalff", "reload", "unban", "ban", "verify", "disband", "resign", "ff",
"clanff", "demote", "promote", "untrust", "trust", "purge", "fee", "bank", "kick", "invite", "toggle",
"modtag", "bb", "clear", "rival", "ally", "add", "remove", "stats", "coords", "vitals", "rivalries",
"modtag", "bb", "display", "clear", "rival", "ally", "add", "remove", "stats", "coords", "vitals", "rivalries",
"alliances", "leaderboard", "allow", "block", "auto", "check", "assign", "unassign", "delete", "me",
"setdisplayname", "permissions", "tag", "deposit", "withdraw", "set", "status", "tp", "all", "everyone",
"lookup", "roster", "profile", "list", "create", "description", "start", "end", "admin", "help", "mod",
"setdefault", "removedefault", "land", "break", "interact", "place_block", "damage", "interact_entity",
"container", "permanent", "take", "give", "join", "leave", "mute", "confirm", "balance", "discord");
"container", "permanent", "take", "give", "join", "leave", "mute", "confirm", "balance", "discord", "rename", "locale");
COMPLETIONS = Arrays.asList("tag", "name");
}
}
@@ -10,12 +10,13 @@ import net.sacredlabyrinth.phaed.simpleclans.events.BankWithdrawEvent;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankLogger;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.managers.PermissionsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent.Cause.REVERT;
import static net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent.Cause.COMMAND;
import static net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent.Cause.REVERT;
import static org.bukkit.ChatColor.AQUA;
import static org.bukkit.ChatColor.RED;
@@ -31,7 +32,7 @@ public class BankCommand extends BaseCommand {
@Conditions("rank:name=BANK_BALANCE")
@Description("{@@command.description.bank.status}")
public void bankStatus(Player player, Clan clan) {
player.sendMessage(AQUA + lang("clan.balance", player, clan.getBalance()));
player.sendMessage(AQUA + lang("clan.balance", player, clan.getBalanceFormatted()));
}
@Subcommand("%withdraw %all")
@@ -72,16 +73,14 @@ public class BankCommand extends BaseCommand {
BankOperator operator = new BankOperator(player, permissions.playerGetMoney(player));
switch (clan.withdraw(operator, COMMAND, amount)) {
case SUCCESS:
if (permissions.playerGrantMoney(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.withdraw", player, amount));
clan.addBb(player.getName(), AQUA + lang("bb.clan.withdraw", amount, player.getName()));
if (permissions.grantPlayer(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.withdraw", player, CurrencyFormat.format(amount)));
clan.addBb(player.getName(), lang("bb.clan.withdraw", CurrencyFormat.format(amount), player.getName()));
} else {
clan.setBalance(operator, REVERT, BankLogger.Operation.WITHDRAW, clan.getBalance() + amount);
}
break;
case NOT_ENOUGH_BALANCE:
player.sendMessage(lang("clan.bank.not.enough.money", player));
break;
}
}
@@ -119,19 +118,19 @@ public class BankCommand extends BaseCommand {
return;
}
/*
* ——————————————————————————————————
*/
* ——————————————————————————————————
*/
if (!permissions.playerHasMoney(player, amount)) {
player.sendMessage(AQUA + lang("not.sufficient.money", player, amount));
player.sendMessage(AQUA + lang("not.sufficient.money", player, CurrencyFormat.format(amount)));
return;
}
BankOperator operator = new BankOperator(player, permissions.playerGetMoney(player));
EconomyResponse response = clan.deposit(operator, COMMAND, amount);
if (response == EconomyResponse.SUCCESS) {
if (permissions.playerChargeMoney(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.deposit", player, amount));
clan.addBb(player.getName(), AQUA + lang("bb.clan.deposit", amount, player.getName()));
if (permissions.chargePlayer(player, amount)) {
player.sendMessage(AQUA + lang("player.clan.deposit", player, CurrencyFormat.format(amount)));
clan.addBb(player.getName(), lang("bb.clan.deposit", CurrencyFormat.format(amount), player.getName()));
} else {
//Reverts the deposit if something went wrong with Vault
clan.setBalance(operator, REVERT, BankLogger.Operation.DEPOSIT, clan.getBalance() - amount);
@@ -5,13 +5,14 @@ import co.aikar.commands.annotation.*;
import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.StorageManager;
import org.bukkit.entity.Player;
import java.util.Objects;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static org.bukkit.ChatColor.*;
import static org.bukkit.ChatColor.RED;
@CommandAlias("%clan")
@Conditions("%basic_conditions|verified")
@@ -21,6 +22,8 @@ public class BbCommand extends BaseCommand {
private ClanManager cm;
@Dependency
private StorageManager storage;
@Dependency
private SettingsManager settings;
@Subcommand("%bb")
@CommandPermission("simpleclans.member.bb")
@@ -46,7 +49,8 @@ public class BbCommand extends BaseCommand {
@Description("{@@command.description.bb.post}")
public void postMessage(Player player, @Name("message") String msg) {
Clan clan = Objects.requireNonNull(cm.getClanByPlayerUniqueId(player.getUniqueId()));
clan.addBb(player.getName(), AQUA + player.getName() + ": " + WHITE + msg);
clan.addBb(lang("bulletin.board.message", player.getName(), msg));
clan.displayBb(player);
storage.updateClan(clan);
}
}
@@ -5,7 +5,6 @@ import co.aikar.commands.annotation.*;
import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.managers.ChatManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.StorageManager;
import static net.sacredlabyrinth.phaed.simpleclans.ClanPlayer.Channel.CLAN;
@@ -10,12 +10,13 @@ import net.sacredlabyrinth.phaed.simpleclans.conversation.SCConversation;
import net.sacredlabyrinth.phaed.simpleclans.events.TagChangeEvent;
import net.sacredlabyrinth.phaed.simpleclans.managers.*;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.TagValidator;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
@@ -91,9 +92,9 @@ public class ClanCommands extends BaseCommand {
tag = event.getNewTag();
String cleanTag = Helper.cleanTag(tag);
TagValidator validator = new TagValidator(plugin, player, tag);
if (validator.getErrorMessage() != null) {
ChatBlock.sendMessage(player, validator.getErrorMessage());
Optional<String> validationError = plugin.getTagValidator().validate(player, tag);
if (validationError.isPresent()) {
ChatBlock.sendMessage(player, validationError.get());
return;
}
@@ -103,7 +104,7 @@ public class ClanCommands extends BaseCommand {
return;
}
clan.addBb(player.getName(), AQUA + lang("tag.changed.to.0", ChatUtils.parseColors(tag)));
clan.addBb(player.getName(), lang("tag.changed.to.0", ChatUtils.parseColors(tag)));
clan.changeClanTag(tag);
cm.updateDisplayName(player);
}
@@ -132,7 +133,7 @@ public class ClanCommands extends BaseCommand {
@Description("{@@command.description.invite}")
public void invite(Player sender, ClanPlayer cp, Clan clan,
@Conditions("not_banned|not_in_clan|online:ignore_vanished") @Name("player") ClanPlayerInput invited) {
if (!invited.getClanPlayer().isInviteEnabled()){
if (!invited.getClanPlayer().isInviteEnabled()) {
ChatBlock.sendMessage(sender, RED + lang("invitedplayer.invite.off", sender));
return;
}
@@ -188,12 +189,12 @@ public class ClanCommands extends BaseCommand {
double maxFee = settings.getDouble(ECONOMY_MAX_MEMBER_FEE);
if (fee > maxFee) {
ChatBlock.sendMessage(player, RED
+ lang("max.fee.allowed.is.0", player, maxFee));
+ lang("max.fee.allowed.is.0", player, CurrencyFormat.format(maxFee)));
return;
}
if (cm.purchaseMemberFeeSet(player)) {
clan.setMemberFee(fee);
clan.addBb(player.getName(), AQUA + lang("bb.fee.set", fee));
clan.addBb(player.getName(), lang("bb.fee.set", CurrencyFormat.format(fee)));
ChatBlock.sendMessage(player, AQUA + lang("fee.set", player));
storage.updateClan(clan);
}
@@ -204,7 +205,7 @@ public class ClanCommands extends BaseCommand {
@Conditions("rank:name=FRIENDLYFIRE")
@Description("{@@command.description.clanff.allow}")
public void allowClanFf(Player player, Clan clan) {
clan.addBb(player.getName(), AQUA + lang("clan.wide.friendly.fire.is.allowed"));
clan.addBb(player.getName(), lang("clan.wide.friendly.fire.is.allowed"));
clan.setFriendlyFire(true);
storage.updateClan(clan);
}
@@ -213,7 +214,7 @@ public class ClanCommands extends BaseCommand {
@CommandPermission("simpleclans.leader.ff")
@Description("{@@command.description.clanff.block}")
public void blockClanFf(Player player, Clan clan) {
clan.addBb(player.getName(), AQUA + lang("clan.wide.friendly.fire.blocked"));
clan.addBb(player.getName(), lang("clan.wide.friendly.fire.blocked"));
clan.setFriendlyFire(false);
storage.updateClan(clan);
}
@@ -252,9 +253,9 @@ public class ClanCommands extends BaseCommand {
if (!issuerClan.reachedRivalLimit()) {
if (!issuerClan.isRival(rivalInput.getTag())) {
issuerClan.addRival(rivalInput);
rivalInput.addBb(player.getName(), AQUA + lang("has.initiated.a.rivalry", issuerClan.getName(),
rivalInput.addBb(player.getName(), lang("has.initiated.a.rivalry", issuerClan.getName(),
rivalInput.getName()), false);
issuerClan.addBb(player.getName(), AQUA + lang("has.initiated.a.rivalry", player.getName(),
issuerClan.addBb(player.getName(), lang("has.initiated.a.rivalry", player.getName(),
rivalInput.getName()));
} else {
ChatBlock.sendMessage(player, RED + lang("your.clans.are.already.rivals", player));
@@ -329,9 +330,9 @@ public class ClanCommands extends BaseCommand {
public void removeAlly(Player player, Clan issuerClan, @Conditions("different|allied_clan") @Name("clan") ClanInput ally) {
Clan allyInput = ally.getClan();
issuerClan.removeAlly(allyInput);
allyInput.addBb(player.getName(), AQUA + lang("has.broken.the.alliance", issuerClan.getName(),
allyInput.addBb(player.getName(), lang("has.broken.the.alliance", issuerClan.getName(),
allyInput.getName()), false);
issuerClan.addBb(player.getName(), AQUA + lang("has.broken.the.alliance", player.getName(),
issuerClan.addBb(player.getName(), lang("has.broken.the.alliance", player.getName(),
allyInput.getName()));
}
@@ -354,7 +355,7 @@ public class ClanCommands extends BaseCommand {
return;
}
clan.addBb(sender.getName(), AQUA + lang("has.been.kicked.by", clanPlayer.getName(),
clan.addBb(sender.getName(), lang("has.been.kicked.by", clanPlayer.getName(),
sender.getName(), sender));
clan.removePlayerFromClan(clanPlayer.getUniqueId());
}
@@ -365,11 +366,11 @@ public class ClanCommands extends BaseCommand {
@HelpSearchTags("leave")
public void resignConfirm(Player player, ClanPlayer cp, Clan clan) {
if (clan.isPermanent() || !clan.isLeader(player) || clan.getLeaders().size() > 1) {
clan.addBb(player.getName(), AQUA + lang("0.has.resigned", player.getName()));
clan.addBb(player.getName(), lang("0.has.resigned", player.getName()));
cp.addResignTime(clan.getTag());
clan.removePlayerFromClan(player.getUniqueId());
ChatBlock.sendMessage(cp,AQUA + lang("resign.success", player));
ChatBlock.sendMessage(cp, AQUA + lang("resign.success", player));
} else if (clan.isLeader(player) && clan.getLeaders().size() == 1) {
clan.disband(player, true, false);
ChatBlock.sendMessage(cp, RED + lang("clan.has.been.disbanded", player, clan.getName()));
@@ -18,7 +18,7 @@ import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.Con
@CommandAlias("%clan")
@Subcommand("%land")
@Conditions("%basic_conditions|land_sharing|own_land")
@Conditions("%basic_conditions|clan_member|land_sharing|own_land")
@CommandPermission("simpleclans.member.land")
public class LandCommand extends BaseCommand {
@@ -49,7 +49,7 @@ public class LandCommand extends BaseCommand {
cp.allow(action, land.getId());
}
if (notify) {
ChatBlock.sendMessageKey(cp.toPlayer(), "land.allowed.action");
ChatBlock.sendMessageKey(cp, "land.allowed.action");
}
}
@@ -118,7 +118,7 @@ public class LandCommand extends BaseCommand {
cp.disallow(action, land.getId());
}
if (notify) {
ChatBlock.sendMessageKey(cp.toPlayer(), "land.blocked.action");
ChatBlock.sendMessageKey(cp, "land.blocked.action");
}
}
@@ -2,24 +2,25 @@ package net.sacredlabyrinth.phaed.simpleclans.commands.clan;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanPlayerInput;
import net.sacredlabyrinth.phaed.simpleclans.conversation.DisbandPrompt;
import net.sacredlabyrinth.phaed.simpleclans.conversation.SCConversation;
import net.sacredlabyrinth.phaed.simpleclans.hooks.discord.DiscordHook;
import net.sacredlabyrinth.phaed.simpleclans.hooks.discord.exceptions.DiscordHookException;
import net.sacredlabyrinth.phaed.simpleclans.managers.*;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.util.Objects;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.events.EconomyTransactionEvent.Cause.DISCORD_CREATION;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static org.bukkit.ChatColor.*;
import static org.bukkit.ChatColor.AQUA;
import static org.bukkit.ChatColor.RED;
@CommandAlias("%clan")
@Conditions("%basic_conditions|leader")
@@ -63,7 +64,7 @@ public class LeaderCommands extends BaseCommand {
player));
return;
}
clan.addBb(player.getName(), AQUA + lang("demoted.back.to.member", otherCp.getName()));
clan.addBb(player.getName(), lang("demoted.back.to.member", otherCp.getName()));
clan.demote(otherCp.getUniqueId());
}
@@ -90,13 +91,14 @@ public class LeaderCommands extends BaseCommand {
return;
}
if (settings.is(CLAN_CONFIRMATION_FOR_PROMOTE) && clan.getLeaders().size() > 1) {
requestManager.addPromoteRequest(cp, otherPl.getName(), clan);
requestManager.requestAllLeaders(cp, ClanRequest.PROMOTE, otherPl.getName(), "asking.for.the.promotion",
player.getName(), otherPl.getName());
ChatBlock.sendMessage(player, AQUA + lang("promotion.vote.has.been.requested.from.all.leaders",
player));
return;
}
clan.addBb(player.getName(), AQUA + lang("promoted.to.leader", otherPl.getName()));
clan.addBb(player.getName(), lang("promoted.to.leader", otherPl.getName()));
clan.promote(otherPl.getUniqueId());
}
@@ -105,7 +107,8 @@ public class LeaderCommands extends BaseCommand {
@Description("{@@command.description.disband}")
public void disband(Player player, ClanPlayer cp, Clan clan) {
if (clan.getLeaders().size() != 1) {
requestManager.addDisbandRequest(cp, clan);
requestManager.requestAllLeaders(cp, ClanRequest.DISBAND, clan.getTag(), "asking.to.disband",
player.getName());
ChatBlock.sendMessage(player, AQUA +
lang("clan.disband.vote.has.been.requested.from.all.leaders", player));
return;
@@ -133,7 +136,7 @@ public class LeaderCommands extends BaseCommand {
}
if (cm.purchaseVerification(player)) {
clan.verifyClan();
clan.addBb(player.getName(), AQUA + lang("clan.0.has.been.verified", clan.getName()));
clan.addBb(player.getName(), lang("clan.0.has.been.verified", clan.getName()));
ChatBlock.sendMessage(player, AQUA + lang("the.clan.has.been.verified", player));
}
}
@@ -156,7 +159,7 @@ public class LeaderCommands extends BaseCommand {
ChatBlock.sendMessage(player, ChatColor.RED + lang("this.player.is.already.trusted", player));
return;
}
clan.addBb(player.getName(), AQUA + lang("has.been.given.trusted.status.by", trustedInput.getName(),
clan.addBb(player.getName(), lang("has.been.given.trusted.status.by", trustedInput.getName(),
player.getName()));
trustedInput.setTrusted(true);
storage.updateClanPlayer(trustedInput);
@@ -181,12 +184,47 @@ public class LeaderCommands extends BaseCommand {
return;
}
clan.addBb(player.getName(), AQUA + lang("has.been.given.untrusted.status.by", trustedInput.getName(),
clan.addBb(player.getName(), lang("has.been.given.untrusted.status.by", trustedInput.getName(),
player.getName()));
trustedInput.setTrusted(false);
storage.updateClanPlayer(trustedInput);
}
@Subcommand("%rename")
@CommandPermission("simpleclans.leader.rename")
@CommandCompletion("@nothing")
@Description("{@@command.description.rename}")
public void rename(Player player, ClanPlayer cp, Clan clan, @Name("name") String clanName) {
if (clanName.contains("&")) {
ChatBlock.sendMessageKey(cp, "your.clan.name.cannot.contain.color.codes");
return;
}
boolean bypass = plugin.getPermissionsManager().has(player, "simpleclans.mod.bypass");
if (!bypass) {
if (ChatUtils.stripColors(clanName).length() > plugin.getSettingsManager().getInt(CLAN_MAX_LENGTH)) {
ChatBlock.sendMessage(player, RED + lang("your.clan.name.cannot.be.longer.than.characters",
player, plugin.getSettingsManager().getInt(CLAN_MAX_LENGTH)));
return;
}
if (ChatUtils.stripColors(clanName).length() <= plugin.getSettingsManager().getInt(CLAN_MIN_LENGTH)) {
ChatBlock.sendMessage(player, RED + lang("your.clan.name.must.be.longer.than.characters",
player, plugin.getSettingsManager().getInt(CLAN_MIN_LENGTH)));
return;
}
}
if (clan.getLeaders().size() != 1) {
requestManager.requestAllLeaders(cp, ClanRequest.RENAME, clanName, "asking.to.rename", cp.getName(), clanName);
ChatBlock.sendMessageKey(cp, "rename.vote.has.been.requested.from.all.leaders");
return;
}
clan.setName(clanName);
storage.updateClan(clan);
ChatBlock.sendMessageKey(cp, "you.have.successfully.renamed.your.clan", clanName);
}
@Subcommand("%discord %create")
@CommandPermission("simpleclans.leader.discord.create")
@Description("{@@command.description.discord.create}")
@@ -198,14 +236,14 @@ public class LeaderCommands extends BaseCommand {
return;
}
double amount = settings.getDouble(ECONOMY_DISCORD_CREATION_PRICE);
if (settings.is(ECONOMY_PURCHASE_DISCORD_CREATE)) {
double amount = settings.getDouble(ECONOMY_DISCORD_CREATION_PRICE);
if (!permissions.playerHasMoney(player, amount)) {
player.sendMessage(AQUA + lang("not.sufficient.money", player, amount));
player.sendMessage(AQUA + lang("not.sufficient.money", player, CurrencyFormat.format(amount)));
return;
}
if (!permissions.playerChargeMoney(player, amount)) {
if (!permissions.chargePlayer(player, amount, DISCORD_CREATION)) {
return;
}
}
@@ -214,6 +252,10 @@ public class LeaderCommands extends BaseCommand {
discordHook.createChannel(clan.getTag());
ChatBlock.sendMessageKey(player, "discord.created.successfully");
} catch (DiscordHookException ex) {
// Return player's money if clan creation went wrong
if (settings.is(ECONOMY_PURCHASE_DISCORD_CREATE)) {
permissions.grantPlayer(player, amount, DISCORD_CREATION);
}
String messageKey = ex.getMessageKey();
if (messageKey != null) {
ChatBlock.sendMessage(player, RED + lang(messageKey));
@@ -0,0 +1,31 @@
package net.sacredlabyrinth.phaed.simpleclans.commands.completions;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.language.LanguageResource;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class LocaleCompletion extends AbstractStaticCompletion {
private final List<String> availableLocales;
public LocaleCompletion(@NotNull SimpleClans plugin) {
super(plugin);
availableLocales = LanguageResource.getAvailableLocales().stream().
map(locale -> locale.toLanguageTag().replace("-", "_")).collect(Collectors.toList());
}
@Override
public @NotNull Collection<String> getCompletions() {
return availableLocales;
}
@Override
public @NotNull String getId() {
return "locales";
}
}
@@ -1,6 +1,9 @@
package net.sacredlabyrinth.phaed.simpleclans.commands.conditions;
import co.aikar.commands.*;
import co.aikar.commands.BukkitCommandIssuer;
import co.aikar.commands.ConditionContext;
import co.aikar.commands.ConditionFailedException;
import co.aikar.commands.InvalidCommandArgument;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
@@ -56,16 +56,24 @@ public class ClanStats extends Sendable {
}
private void addRows(List<ClanPlayer> clanPlayers) {
for (ClanPlayer cpm : clanPlayers) {
String name = (cpm.isLeader() ? sm.getColored(PAGE_LEADER_COLOR) : (cpm.isTrusted() ? sm.getColored(PAGE_TRUSTED_COLOR) :
sm.getColored(PAGE_UNTRUSTED_COLOR)) + cpm.getName());
String rival = NumberFormat.getInstance().format(cpm.getRivalKills());
String neutral = NumberFormat.getInstance().format(cpm.getNeutralKills());
String civilian = NumberFormat.getInstance().format(cpm.getCivilianKills());
String deaths = NumberFormat.getInstance().format(cpm.getDeaths());
String kdr = KDRFormat.format(cpm.getKDR());
for (ClanPlayer cp : clanPlayers) {
String color;
if (cp.isLeader()) {
color = sm.getColored(PAGE_LEADER_COLOR);
} else if (cp.isTrusted()) {
color = sm.getColored(PAGE_TRUSTED_COLOR);
} else {
color = sm.getColored(PAGE_UNTRUSTED_COLOR);
}
chatBlock.addRow(" " + name, YELLOW + kdr, WHITE + rival, GRAY + neutral, DARK_GRAY + civilian,
NumberFormat formatter = NumberFormat.getInstance(cp.getLocale());
String rival = formatter.format(cp.getRivalKills());
String neutral = formatter.format(cp.getNeutralKills());
String civilian = formatter.format(cp.getCivilianKills());
String deaths = formatter.format(cp.getDeaths());
String kdr = KDRFormat.format(cp.getKDR());
chatBlock.addRow(color + cp.getName(), YELLOW + kdr, WHITE + rival, GRAY + neutral, DARK_GRAY + civilian,
DARK_RED + deaths);
}
}
@@ -5,22 +5,22 @@ import co.aikar.commands.CommandHelp;
import co.aikar.commands.CommandParameter;
import co.aikar.commands.HelpEntry;
import co.aikar.commands.annotation.*;
import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanInput;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanPlayerInput;
import net.sacredlabyrinth.phaed.simpleclans.commands.data.*;
import net.sacredlabyrinth.phaed.simpleclans.conversation.CreateClanTagPrompt;
import net.sacredlabyrinth.phaed.simpleclans.conversation.RequestCanceller;
import net.sacredlabyrinth.phaed.simpleclans.conversation.ResetKdrPrompt;
import net.sacredlabyrinth.phaed.simpleclans.conversation.SCConversation;
import net.sacredlabyrinth.phaed.simpleclans.events.PlayerResetKdrEvent;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.RequestManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.StorageManager;
import net.sacredlabyrinth.phaed.simpleclans.ui.InventoryDrawer;
import net.sacredlabyrinth.phaed.simpleclans.ui.frames.MainFrame;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -62,8 +62,25 @@ public class GeneralCommands extends BaseCommand {
}
}
@Subcommand("%locale")
@CommandPermission("simpleclans.anyone.locale")
@Description("{@@command.description.locale}")
@CommandCompletion("@locales")
public void locale(ClanPlayer cp, @Values("@locales") @Name("locale") @Single String locale) {
if (!settings.is(LANGUAGE_SELECTOR)) {
ChatBlock.sendMessageKey(cp, "locale.is.prohibited");
return;
}
cp.setLocale(Helper.forLanguageTag(locale.replace("_", "-")));
plugin.getStorageManager().updateClanPlayer(cp);
ChatBlock.sendMessageKey(cp, "locale.has.been.changed");
}
@Subcommand("%create")
@CommandPermission("simpleclans.leader.create")
@CommandCompletion("%compl:tag %compl:name")
@Description("{@@command.description.create}")
public void create(Player player, @Optional @Name("tag") String tag, @Optional @Name("name") String name) {
ClanPlayer cp = cm.getAnyClanPlayer(player.getUniqueId());
@@ -156,17 +173,30 @@ public class GeneralCommands extends BaseCommand {
ChatBlock.sendMessage(player, AQUA + lang("friendy.fire.is.now.managed.by.your.clan", player));
}
@Subcommand("%resetkdr %confirm")
@CommandPermission("simpleclans.vip.resetkdr")
@Description("{@@command.description.resetkdr}")
public void resetKdrConfirm(Player player, ClanPlayer cp) {
if (!settings.is(ALLOW_RESET_KDR)) {
ChatBlock.sendMessage(player, RED + lang("disabled.command", player));
return;
}
PlayerResetKdrEvent event = new PlayerResetKdrEvent(cp);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && cm.purchaseResetKdr(player)) {
cm.resetKdr(cp);
ChatBlock.sendMessage(player, RED + lang("you.have.reseted.your.kdr", player));
}
}
@Subcommand("%resetkdr")
@CommandPermission("simpleclans.vip.resetkdr")
@Description("{@@command.description.resetkdr}")
public void resetKdr(Player player, ClanPlayer cp) {
if (!settings.is(ALLOW_RESET_KDR)) {
ChatBlock.sendMessage(player, RED + lang("disabled.command", player));
return;
}
if (cm.purchaseResetKdr(player)) {
cm.resetKdr(cp);
ChatBlock.sendMessage(player, RED + lang("you.have.reseted.your.kdr", player));
} else {
new SCConversation(plugin, player, new ResetKdrPrompt(cm), 60).begin();
}
}
@@ -256,7 +286,7 @@ public class GeneralCommands extends BaseCommand {
Clan clan = clans.get(i);
String name = " " + (clan.isVerified() ? settings.getColored(PAGE_CLAN_NAME_COLOR) : GRAY) + clan.getName();
String line = MessageFormat.format(lineFormat, i + 1, leftBracket, clan.getColorTag(),
rightBracket, name, clan.getBalance());
rightBracket, name, clan.getBalanceFormatted());
sender.sendMessage(line);
}
}
@@ -10,6 +10,7 @@ import net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankLogger;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.managers.PermissionsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -31,7 +32,7 @@ public class BankCommand extends BaseCommand {
@Description("{@@command.description.bank.admin.status}")
public void status(CommandSender sender, @Name("clan") ClanInput clanInput) {
Clan clan = clanInput.getClan();
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.balance", sender, clan.getName(), clan.getBalance()));
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.balance", sender, clan.getName(), clan.getBalanceFormatted()));
}
@Subcommand("%take")
@@ -46,8 +47,8 @@ public class BankCommand extends BaseCommand {
EconomyResponse economyResponse = clan.withdraw(operator, ClanBalanceUpdateEvent.Cause.COMMAND, amount);
switch (economyResponse) {
case SUCCESS:
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.take", sender, amount, clan.getName()));
clan.addBb(sender.getName(), AQUA + lang("bb.clan.take", sender, amount, sender.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.take", sender, CurrencyFormat.format(amount), clan.getName()));
clan.addBb(sender.getName(), lang("bb.clan.take", sender, CurrencyFormat.format(amount), sender.getName()));
break;
case NOT_ENOUGH_BALANCE:
sender.sendMessage(RED + lang("clan.admin.bank.not.enough.money", sender, clan.getName()));
@@ -66,8 +67,8 @@ public class BankCommand extends BaseCommand {
EconomyResponse economyResponse = clan.deposit(operator, ClanBalanceUpdateEvent.Cause.COMMAND, amount);
if (economyResponse == EconomyResponse.SUCCESS) {
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.give", sender, amount, clan.getName()));
clan.addBb(sender.getName(), AQUA + lang("bb.clan.give", sender, amount, sender.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.give", sender, CurrencyFormat.format(amount), clan.getName()));
clan.addBb(sender.getName(), lang("bb.clan.give", sender, CurrencyFormat.format(amount), sender.getName()));
}
}
@@ -82,8 +83,8 @@ public class BankCommand extends BaseCommand {
EconomyResponse response = clan.setBalance(operator, ClanBalanceUpdateEvent.Cause.COMMAND, BankLogger.Operation.SET, amount);
if (response == EconomyResponse.SUCCESS) {
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.set", sender, clan.getName(), amount));
clan.addBb(sender.getName(), AQUA + lang("bb.clan.set", sender, amount, sender.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("clan.admin.set", sender, clan.getName(), CurrencyFormat.format(amount)));
clan.addBb(sender.getName(), lang("bb.clan.set", sender, CurrencyFormat.format(amount), sender.getName()));
}
}
}
@@ -1,26 +1,17 @@
package net.sacredlabyrinth.phaed.simpleclans.commands.staff;
import org.bukkit.entity.Player;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Conditions;
import co.aikar.commands.annotation.Default;
import co.aikar.commands.annotation.Dependency;
import co.aikar.commands.annotation.Description;
import co.aikar.commands.annotation.Name;
import co.aikar.commands.annotation.Subcommand;
import co.aikar.commands.annotation.*;
import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanInput;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.StorageManager;
import org.bukkit.entity.Player;
import static org.bukkit.ChatColor.RED;
import static org.bukkit.ChatColor.AQUA;
import static org.bukkit.ChatColor.WHITE;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static org.bukkit.ChatColor.RED;
@CommandAlias("%clan")
@Conditions("%basic_conditions")
@@ -31,9 +22,13 @@ public class BbCommand extends BaseCommand {
private StorageManager storage;
@Dependency
private ClanManager cm;
@Default
@Dependency
private SettingsManager settings;
@Subcommand("%display")
@CommandPermission("simpleclans.mod.bb")
@CommandCompletion("@clans")
@Description("{@@command.description.mod.bb.display}")
public void display(Player sender, @Name("clan") ClanInput input) {
input.getClan().displayBb(sender);
@@ -41,6 +36,7 @@ public class BbCommand extends BaseCommand {
@Subcommand("%clear")
@CommandPermission("simpleclans.mod.bb-clear")
@CommandCompletion("@clans")
@Description("{@@command.description.mod.bb.clear}")
public void clear(Player player, @Name("clan") ClanInput input) {
input.getClan().clearBb();
@@ -49,10 +45,12 @@ public class BbCommand extends BaseCommand {
@Subcommand("%add")
@CommandPermission("simpleclans.mod.bb-add")
@CommandCompletion("@clans @nothing")
@Description("{@@command.description.mod.bb.post}")
public void postMessage(Player player, @Name("clan") ClanInput input, @Name("message") String msg) {
Clan clan = input.getClan();
clan.addBb(player.getName(), AQUA + player.getName() + ": " + WHITE + msg);
clan.addBb(lang("bulletin.board.message", player.getName(), msg));
clan.displayBb(player);
storage.updateClan(clan);
}
@@ -6,6 +6,8 @@ import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanInput;
import net.sacredlabyrinth.phaed.simpleclans.commands.ClanPlayerInput;
import net.sacredlabyrinth.phaed.simpleclans.events.PlayerHomeSetEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.PlayerResetKdrEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.ReloadEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.TagChangeEvent;
import net.sacredlabyrinth.phaed.simpleclans.language.LanguageResource;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
@@ -14,7 +16,6 @@ import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.StorageManager;
import net.sacredlabyrinth.phaed.simpleclans.ui.InventoryController;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.TagValidator;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@@ -22,6 +23,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
@@ -65,14 +67,14 @@ public class StaffCommands extends BaseCommand {
ChatBlock.sendMessage(sender, RED + lang("you.cannot.move.the.last.leader", sender));
return;
} else {
oldClan.addBb(oldCp.getName(), AQUA + lang("0.has.resigned", oldCp.getName()));
oldClan.addBb(oldCp.getName(), lang("0.has.resigned", oldCp.getName()));
oldClan.removePlayerFromClan(uuid);
}
}
ClanPlayer cp = cm.getCreateClanPlayer(uuid);
newClan.addBb(AQUA + lang("joined.the.clan", cp.getName()));
newClan.addBb(lang("joined.the.clan", cp.getName()));
cm.serverAnnounce(lang("has.joined", cp.getName(), newClan.getName()));
newClan.addPlayerToClan(cp);
}
@@ -90,9 +92,9 @@ public class StaffCommands extends BaseCommand {
tag = event.getNewTag();
String cleanTag = Helper.cleanTag(tag);
TagValidator validator = new TagValidator(plugin, player, tag);
if (validator.getErrorMessage() != null) {
ChatBlock.sendMessage(player, validator.getErrorMessage());
Optional<String> validationError = plugin.getTagValidator().validate(player, tag);
if (validationError.isPresent()) {
ChatBlock.sendMessage(player, validationError.get());
return;
}
@@ -102,7 +104,7 @@ public class StaffCommands extends BaseCommand {
return;
}
clan.addBb(player.getName(), AQUA + lang("tag.changed.to.0", ChatUtils.parseColors(tag)));
clan.addBb(player.getName(), lang("tag.changed.to.0", ChatUtils.parseColors(tag)));
clan.changeClanTag(tag);
player.sendMessage(lang("0.tag.changed.to.1", player, clan.getTag(), tag));
}
@@ -121,6 +123,8 @@ public class StaffCommands extends BaseCommand {
for (Clan clan : cm.getClans()) {
permissions.updateClanPermissions(clan);
}
Bukkit.getPluginManager().callEvent(new ReloadEvent(sender));
ChatBlock.sendMessage(sender, AQUA + lang("configuration.reloaded", sender));
}
@@ -226,7 +230,7 @@ public class StaffCommands extends BaseCommand {
if (!clanInput.isVerified()) {
clanInput.verifyClan();
clanInput.addBb(sender.getName(), AQUA + lang("clan.0.has.been.verified", clanInput.getName()));
clanInput.addBb(sender.getName(), lang("clan.0.has.been.verified", clanInput.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("the.clan.has.been.verified", sender));
} else {
ChatBlock.sendMessage(sender, RED + lang("the.clan.is.already.verified", sender));
@@ -263,7 +267,7 @@ public class StaffCommands extends BaseCommand {
return;
}
clan.addBb(sender.getName(), AQUA + lang("has.been.kicked.by", clanPlayer.getName(),
clan.addBb(sender.getName(), lang("has.been.kicked.by", clanPlayer.getName(),
sender.getName(), sender));
clan.removePlayerFromClan(clanPlayer.getUniqueId());
}
@@ -294,7 +298,7 @@ public class StaffCommands extends BaseCommand {
return;
}
clan.addBb(sender.getName(), AQUA + lang("promoted.to.leader", promotePl.getName()));
clan.addBb(sender.getName(), lang("promoted.to.leader", promotePl.getName()));
clan.promote(promotePl.getUniqueId());
ChatBlock.sendMessage(sender, AQUA + lang("player.successfully.promoted", sender));
}
@@ -317,7 +321,7 @@ public class StaffCommands extends BaseCommand {
return;
}
clan.demote(otherCp.getUniqueId());
clan.addBb(sender.getName(), AQUA + lang("demoted.back.to.member", otherCp.getName()));
clan.addBb(sender.getName(), lang("demoted.back.to.member", otherCp.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("player.successfully.demoted", sender));
}
@@ -326,7 +330,11 @@ public class StaffCommands extends BaseCommand {
@Description("{@@command.description.resetkdr.everyone}")
public void resetKdr(CommandSender sender) {
for (ClanPlayer cp : cm.getAllClanPlayers()) {
cm.resetKdr(cp);
PlayerResetKdrEvent event = new PlayerResetKdrEvent(cp);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
cm.resetKdr(cp);
}
}
ChatBlock.sendMessage(sender, RED + lang("you.have.reseted.kdr.of.all.players", sender));
}
@@ -335,20 +343,49 @@ public class StaffCommands extends BaseCommand {
@CommandCompletion("@players")
@CommandPermission("simpleclans.admin.resetkdr")
@Description("{@@command.description.resetkdr.player}")
public void resetKdr(CommandSender sender, @Name("player") ClanPlayerInput player) {
ClanPlayer cp = player.getClanPlayer();
cm.resetKdr(cp);
ChatBlock.sendMessage(sender, RED + lang("you.have.reseted.0.kdr", sender, cp.getName()));
public void resetKdr(CommandSender sender, @Name("player") ClanPlayerInput clanPlayer) {
ClanPlayer cp = clanPlayer.getClanPlayer();
PlayerResetKdrEvent event = new PlayerResetKdrEvent(cp);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
cm.resetKdr(cp);
ChatBlock.sendMessage(sender, RED + lang("you.have.reseted.0.kdr", sender, cp.getName()));
}
}
@Subcommand("%admin %permanent")
@CommandCompletion("@clans")
@CommandPermission("simpleclans.admin.permanent")
@Description("{@@command.description.admin.permanent}")
public void togglePermanent(CommandSender sender, @Name("clan") ClanInput clan) {
boolean permanent = !clan.getClan().isPermanent();
clan.getClan().setPermanent(permanent);
clan.getClan().addBb(sender.getName(), lang((permanent) ? "permanent.status.enabled" : "permanent.status.disabled", sender.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("you.have.toggled.permanent.status", sender, clan.getClan().getName()));
public void togglePermanent(CommandSender sender, @Name("clan") ClanInput clanInput) {
Clan clan = clanInput.getClan();
boolean permanent = !clan.isPermanent();
clan.setPermanent(permanent);
clan.addBb(sender.getName(), lang((permanent) ? "permanent.status.enabled" : "permanent.status.disabled", sender.getName()));
ChatBlock.sendMessage(sender, AQUA + lang("you.have.toggled.permanent.status", sender, clan.getName()));
}
@Subcommand("%mod %rename")
@CommandCompletion("@clans @nothing")
@CommandPermission("simpleclans.mod.rename")
@Description("{@@command.description.mod.rename}")
public void rename(CommandSender sender, @Name("clan") ClanInput clanInput, @Name("name") String clanName) {
Clan clan = clanInput.getClan();
clan.setName(clanName);
storage.updateClan(clan);
ChatBlock.sendMessageKey(sender, "you.have.successfully.renamed.the.clan", clanName);
}
@Subcommand("%mod %locale")
@CommandPermission("simpleclans.mod.locale")
@Description("{@@command.description.mod.locale}")
@CommandCompletion("@locales")
public void locale(CommandSender sender, @Name("player") ClanPlayerInput input, @Values("@locales") @Name("locale") @Single String locale) {
ClanPlayer cp = input.getClanPlayer();
cp.setLocale(Helper.forLanguageTag(locale.replace("_", "-")));
plugin.getStorageManager().updateClanPlayer(cp);
ChatBlock.sendMessage(sender, lang("locale.has.been.changed"));
}
}
@@ -4,6 +4,7 @@ import net.sacredlabyrinth.phaed.simpleclans.ChatBlock;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.events.PreCreateClanEvent;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import org.bukkit.Bukkit;
import org.bukkit.conversations.ConversationContext;
@@ -16,6 +17,7 @@ import org.jetbrains.annotations.Nullable;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.conversation.CreateClanTagPrompt.TAG_KEY;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.CLAN_DEFAULT_RANK;
import static org.bukkit.ChatColor.AQUA;
import static org.bukkit.ChatColor.RED;
@@ -66,17 +68,20 @@ public class CreateClanNamePrompt extends StringPrompt {
plugin.getClanManager().createClan(player, tag, name);
Clan clan = plugin.getClanManager().getClan(tag);
clan.addBb(player.getName(), AQUA +
lang("clan.created", name));
clan.addBb(player.getName(), lang("clan.created", name));
plugin.getStorageManager().updateClan(clan);
if (!plugin.getSettingsManager().getString(CLAN_DEFAULT_RANK).isEmpty()) {
clan.setDefaultRank(plugin.getSettingsManager().getString(CLAN_DEFAULT_RANK));
if (plugin.getSettingsManager().is(REQUIRE_VERIFICATION)) {
boolean verified = !plugin.getSettingsManager().is(REQUIRE_VERIFICATION)
|| plugin.getPermissionsManager().has(player, "simpleclans.mod.verify");
if (!verified) {
ChatBlock.sendMessage(player, AQUA +
lang("get.your.clan.verified.to.access.advanced.features", player));
if (plugin.getSettingsManager().is(REQUIRE_VERIFICATION)) {
boolean verified = !plugin.getSettingsManager().is(REQUIRE_VERIFICATION)
|| plugin.getPermissionsManager().has(player, "simpleclans.mod.verify");
if (!verified) {
ChatBlock.sendMessage(player, AQUA +
lang("get.your.clan.verified.to.access.advanced.features", player));
}
}
}
}
@@ -2,7 +2,6 @@ package net.sacredlabyrinth.phaed.simpleclans.conversation;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.TagValidator;
import org.bukkit.ChatColor;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
@@ -11,6 +10,8 @@ import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class CreateClanTagPrompt extends StringPrompt {
@@ -52,12 +53,7 @@ public class CreateClanTagPrompt extends StringPrompt {
lang("clan.with.this.tag.already.exists", player), this);
}
TagValidator validator = new TagValidator(plugin, player, clanTag);
String errorMessage = validator.getErrorMessage();
if (errorMessage == null) {
return null;
} else {
return new MessagePromptImpl(errorMessage, this);
}
Optional<String> validationError = plugin.getTagValidator().validate(player, clanTag);
return validationError.map(error -> new MessagePromptImpl(error, this)).orElse(null);
}
}
@@ -11,6 +11,10 @@ public class DisbandPrompt extends ConfirmationPrompt {
@Override
protected Prompt confirm(ClanPlayer sender, Clan clan) {
if (clan.isPermanent()) {
return new MessagePromptImpl(RED + lang("cannot.disband.permanent", sender));
}
clan.disband(sender.toPlayer(), true, false);
return new MessagePromptImpl(RED + lang("clan.has.been.disbanded", sender, clan.getName()));
}
@@ -0,0 +1,43 @@
package net.sacredlabyrinth.phaed.simpleclans.conversation;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.events.PlayerResetKdrEvent;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import org.bukkit.Bukkit;
import org.bukkit.conversations.Prompt;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static org.bukkit.ChatColor.RED;
public class ResetKdrPrompt extends ConfirmationPrompt {
private final ClanManager cm;
public ResetKdrPrompt(ClanManager cm) {
this.cm = cm;
}
@Override
protected Prompt confirm(ClanPlayer sender, Clan clan) {
PlayerResetKdrEvent event = new PlayerResetKdrEvent(sender);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled() && cm.purchaseResetKdr(sender.toPlayer())) {
cm.resetKdr(sender);
return new MessagePromptImpl(RED + lang("you.have.reseted.your.kdr", sender));
} else {
return END_OF_CONVERSATION;
}
}
@Override
protected String getPromptTextKey() {
return "resetkdr.confirmation";
}
@Override
protected String getDeclineTextKey() {
return "resetkdr.request.cancelled";
}
}
@@ -16,7 +16,7 @@ public class ResignPrompt extends ConfirmationPrompt {
@Override
protected Prompt confirm(ClanPlayer sender, Clan clan) {
if (clan.isPermanent() || !sender.isLeader() || clan.getLeaders().size() > 1) {
clan.addBb(sender.getName(), AQUA + lang("0.has.resigned", sender.getName()));
clan.addBb(sender.getName(), lang("0.has.resigned", sender.getName()));
sender.addResignTime(clan.getTag());
clan.removePlayerFromClan(sender.getUniqueId());
@@ -1,7 +1,6 @@
package net.sacredlabyrinth.phaed.simpleclans.events;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
@@ -0,0 +1,96 @@
package net.sacredlabyrinth.phaed.simpleclans.events;
import net.sacredlabyrinth.phaed.simpleclans.managers.PermissionsManager;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* This event is fired when money is granted or charged from a player's account.
* <p>Note: Cancelling this event will deny the transaction.</p>
*
* @see PermissionsManager#grantPlayer(OfflinePlayer, double, Cause)
* @see PermissionsManager#chargePlayer(OfflinePlayer, double, Cause)
*/
public class EconomyTransactionEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final OfflinePlayer player;
private double amount;
private final Cause cause;
private final TransactionType transactionType;
private boolean cancelled;
public EconomyTransactionEvent(@NotNull OfflinePlayer affected, double amount,
@NotNull Cause cause, @NotNull TransactionType transactionType) {
this.player = affected;
this.amount = amount;
this.cause = cause;
this.transactionType = transactionType;
}
public OfflinePlayer getPlayer() {
return player;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
@NotNull
public Cause getCause() {
return cause;
}
@SuppressWarnings("unused")
public TransactionType getTransactionType() {
return transactionType;
}
@Override
public @NotNull HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
/**
* If cancelled, the transaction will result as denied.
*/
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public enum Cause {
CLAN_CREATION,
CLAN_VERIFICATION,
CLAN_INVITATION,
CLAN_REGROUP,
CLAN_HOME_TELEPORT,
CLAN_HOME_TELEPORT_SET,
DISCORD_CREATION,
PLAYER_KILLED,
MEMBER_FEE_SET,
RESET_KDR
}
public enum TransactionType {
DEPOSIT, WITHDRAW
}
}
@@ -5,8 +5,6 @@
*/
package net.sacredlabyrinth.phaed.simpleclans.events;
import java.util.Collections;
import java.util.List;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import org.bukkit.Location;
@@ -14,6 +12,9 @@ import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.util.Collections;
import java.util.List;
/**
*
* @author edson
@@ -50,12 +51,16 @@ public class HomeRegroupEvent extends Event implements Cancellable {
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
cancelled = cancel;
@@ -0,0 +1,56 @@
package net.sacredlabyrinth.phaed.simpleclans.events;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* @author ThiagoROX
*/
public class PlayerResetKdrEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ClanPlayer clanPlayer;
private boolean cancelled;
/**
* Event called before a player's kill death rate is reset
*
* @param clanPlayer The ClanPlayer whose kill death rate going to be reset
*/
public PlayerResetKdrEvent(@NotNull ClanPlayer clanPlayer) {
this.clanPlayer = clanPlayer;
}
/**
* Gets the player whose kill death rate going to be reset
*
* @return The player whose kill death rate going to be reset
*/
@NotNull
public ClanPlayer getClanPlayer() {
return clanPlayer;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
@@ -0,0 +1,32 @@
package net.sacredlabyrinth.phaed.simpleclans.events;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCFrame;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class PostComponentsCreationEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private final @NotNull SCFrame frame;
public PostComponentsCreationEvent(@NotNull SCFrame frame) {
this.frame = frame;
}
public SCFrame getFrame() {
return frame;
}
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLER_LIST;
}
public static @NotNull HandlerList getHandlerList() {
return HANDLER_LIST;
}
}
@@ -0,0 +1,30 @@
package net.sacredlabyrinth.phaed.simpleclans.events;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class ReloadEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private final CommandSender sender;
public ReloadEvent(CommandSender sender) {
this.sender = sender;
}
public static @NotNull HandlerList getHandlerList() {
return HANDLER_LIST;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
public CommandSender getSender() {
return sender;
}
}
@@ -70,18 +70,13 @@ public class DiscordHook implements Listener {
private static final int MAX_CHANNELS_PER_CATEGORY = 50;
private static final int MAX_CHANNELS_PER_GUILD = 500;
private final SimpleClans plugin;
private final SettingsManager settingsManager;
private final ChatManager chatManager;
private final ClanManager clanManager;
private final AccountLinkManager accountManager = DiscordSRV.getPlugin().getAccountLinkManager();
private final Guild guild = DiscordSRV.getPlugin().getMainGuild();
private final List<String> textCategories;
private final List<String> discordClanTags;
private final List<String> clanTags;
private final Role leaderRole;
private final List<String> whitelist;
public DiscordHook(SimpleClans plugin) {
@@ -89,14 +84,13 @@ public class DiscordHook implements Listener {
settingsManager = plugin.getSettingsManager();
chatManager = plugin.getChatManager();
clanManager = plugin.getClanManager();
textCategories = settingsManager.getStringList(DISCORDCHAT_TEXT_CATEGORY_IDS).stream().
filter(this::categoryExists).collect(Collectors.toList());
whitelist = settingsManager.getStringList(DISCORDCHAT_TEXT_WHITELIST);
clanTags = clanManager.getClans().stream().map(Clan::getTag).collect(Collectors.toList());
discordClanTags = getCachedChannels().stream().map(GuildChannel::getName).collect(Collectors.toList());
leaderRole = getLeaderRole();
setupDiscord();
}
@@ -229,7 +223,7 @@ public class DiscordHook implements Listener {
@Subscribe
public void onPlayerLinking(AccountLinkedEvent event) {
ClanPlayer clanPlayer = clanManager.getClanPlayer(event.getPlayer());
Member member = guild.getMember(event.getUser());
Member member = getGuild().getMember(event.getUser());
if (clanPlayer == null || member == null) {
return;
}
@@ -250,7 +244,7 @@ public class DiscordHook implements Listener {
@Subscribe
public void onPlayerUnlinking(AccountUnlinkedEvent event) {
ClanPlayer clanPlayer = clanManager.getClanPlayer(event.getPlayer());
Member member = guild.getMember(event.getDiscordUser());
Member member = getGuild().getMember(event.getDiscordUser());
if (clanPlayer == null || clanPlayer.getClan() == null || member == null) {
return;
}
@@ -260,14 +254,23 @@ public class DiscordHook implements Listener {
}
protected void setupDiscord() {
clearChannels();
resetPermissions();
createChannels();
Map<String, TextChannel> discordTagChannels = getChannels().stream().
collect(Collectors.toMap(TextChannel::getName, textChannel -> textChannel));
SimpleClans.debug("DiscordTagChannels before clearing: " + String.join(",", discordTagChannels.keySet()));
clearChannels(discordTagChannels);
SimpleClans.debug("DiscordTagChannels after clearing: " + String.join(",", discordTagChannels.keySet()));
resetPermissions(discordTagChannels);
SimpleClans.debug("ClanTags before creating: " + String.join(",", clanTags));
createChannels(discordTagChannels);
SimpleClans.debug("ClanTags after creating: " + String.join(",", clanTags));
}
@NotNull
public Guild getGuild() {
return guild;
return DiscordSRV.getPlugin().getMainGuild();
}
/**
@@ -275,10 +278,10 @@ public class DiscordHook implements Listener {
*/
@NotNull
public Role getLeaderRole() {
Role role = guild.getRoleById(settingsManager.getString(DISCORDCHAT_LEADER_ID));
Role role = getGuild().getRoleById(settingsManager.getString(DISCORDCHAT_LEADER_ID));
if (role == null || !role.getName().equals(settingsManager.getString(DISCORDCHAT_LEADER_ROLE))) {
role = guild.createRole().
role = getGuild().createRole().
setName(settingsManager.getString(DISCORDCHAT_LEADER_ROLE)).
setColor(getLeaderColor()).
setMentionable(true).
@@ -317,19 +320,19 @@ public class DiscordHook implements Listener {
*/
@Nullable
public Category createCategory() {
if (guild.getChannels().size() >= MAX_CHANNELS_PER_GUILD) {
if (getGuild().getChannels().size() >= MAX_CHANNELS_PER_GUILD) {
return null;
}
String categoryName = settingsManager.getString(DISCORDCHAT_TEXT_CATEGORY_FORMAT);
Category category = null;
try {
category = guild.createCategory(categoryName).
category = getGuild().createCategory(categoryName).
addRolePermissionOverride(
guild.getPublicRole().getIdLong(),
getGuild().getPublicRole().getIdLong(),
Collections.emptyList(),
Collections.singletonList(VIEW_CHANNEL)).
addMemberPermissionOverride(guild.getSelfMember().getIdLong(),
addMemberPermissionOverride(getGuild().getSelfMember().getIdLong(),
Arrays.asList(VIEW_CHANNEL, MANAGE_CHANNEL),
Collections.emptyList()).
submit().get();
@@ -352,7 +355,6 @@ public class DiscordHook implements Listener {
* <p>Sets positive {@link Permission#VIEW_CHANNEL} permission to all linked clan members.</p>
*
* @param clanTag the clan tag
*
* @throws InvalidChannelException clan is not verified or permanent,
* no one member is linked or clan is not in the whitelist.
* @throws ChannelExistsException if channel is already exist
@@ -378,12 +380,14 @@ public class DiscordHook implements Listener {
try {
availableCategory.createTextChannel(clanTag).complete();
SimpleClans.debug(String.format("[%s] Creating a discord text channel for %s clan", Thread.currentThread().getId(), clanTag));
} catch (ErrorResponseException ex) {
Response response = ex.getResponse();
plugin.getLogger().warning(String.format("Could not create a channel for clan %s, error %d - %s",
clanTag, response.code, response.message));
return;
}
for (Map.Entry<ClanPlayer, Member> entry : discordClanPlayers.entrySet()) {
// The map is formed from clan#getMembers (so the clan exists)
//noinspection ConstantConditions
@@ -396,10 +400,8 @@ public class DiscordHook implements Listener {
* Retrieves channel in SimpleClans categories.
*
* @param channelName the channel name
*
* @see #getCachedCategories() retreive categories.
*
* @return the channel
* @see #getCachedCategories() retreive categories.
*/
public Optional<TextChannel> getCachedChannel(@NotNull String channelName) {
return getCachedChannels().stream().filter(textChannel -> textChannel.getName().equals(channelName)).findFirst();
@@ -409,12 +411,11 @@ public class DiscordHook implements Listener {
* Checks if a category can be obtained by id.
*
* @param categoryId the category id
* @see #channelExists(String)
*
* @return true if the category exists
* @see #channelExists(String)
*/
public boolean categoryExists(String categoryId) {
return guild.getCategoryById(categoryId) != null;
return getGuild().getCategoryById(categoryId) != null;
}
/**
@@ -423,7 +424,18 @@ public class DiscordHook implements Listener {
* @see #categoryExists(String)
*/
public boolean channelExists(String clanTag) {
return getChannels().stream().map(TextChannel::getName).anyMatch(name -> name.equals(clanTag));
return getChannel(clanTag).isPresent();
}
/**
* Retrieves the channel in SimpleClans categories.
*
* @param channelName the channel name
* @return the channel
* @see #getCachedChannel(String) retreive the <b>cached</b> channel.
*/
public Optional<TextChannel> getChannel(@NotNull String channelName) {
return getChannels().stream().filter(textChannel -> textChannel.getName().equals(channelName)).findAny();
}
/**
@@ -431,27 +443,31 @@ public class DiscordHook implements Listener {
* If there are no channels, removes category as well.
*
* @param channelName the channel name
*
* @return true, if channel was deleted and false if not.
*/
@SuppressWarnings("UnusedReturnValue")
public boolean deleteChannel(@NotNull String channelName) {
boolean deleted = false;
if (channelExists(channelName)) {
for (Category category : getCachedCategories()) {
if (category.getTextChannels().size() > 0) {
if (!category.getTextChannels().isEmpty()) {
for (TextChannel textChannel : category.getTextChannels()) {
if (textChannel.getName().equals(channelName)) {
textChannel.delete().complete();
return true;
deleted = true;
break;
}
}
if (category.getTextChannels().size() == 0) {
if (category.getTextChannels().isEmpty()) {
textCategories.remove(category.getId());
settingsManager.set(DISCORDCHAT_TEXT_CATEGORY_IDS, textCategories);
settingsManager.save();
category.delete().complete();
}
return deleted;
}
}
}
@@ -465,7 +481,7 @@ public class DiscordHook implements Listener {
public List<Category> getCachedCategories() {
return textCategories.stream().
filter(this::categoryExists).
map(guild::getCategoryById).
map(getGuild()::getCategoryById).
collect(Collectors.toList());
}
@@ -475,7 +491,7 @@ public class DiscordHook implements Listener {
* @return categories from guild
*/
public List<Category> getCategories() {
return guild.getCategoriesByName(settingsManager.getString(DISCORDCHAT_TEXT_CATEGORY_FORMAT), false);
return getGuild().getCategoriesByName(settingsManager.getString(DISCORDCHAT_TEXT_CATEGORY_FORMAT), false);
}
/**
@@ -502,51 +518,54 @@ public class DiscordHook implements Listener {
return DiscordUtil.getMemberById(discordId);
}
private void clearChannels() {
private void clearChannels(Map<String, TextChannel> discordTagChannels) {
// Removes abandoned channels
ArrayList<String> clansToDelete = new ArrayList<>(discordClanTags);
ArrayList<String> clansToDelete = new ArrayList<>(discordTagChannels.keySet());
clansToDelete.removeAll(clanTags);
clansToDelete.forEach(this::deleteChannel);
clansToDelete.forEach(clanChannel -> {
deleteChannel(clanChannel);
discordTagChannels.remove(clanChannel);
});
// Removes invalid channels
for (String clanTag : clanTags) {
Iterator<String> iterator = discordTagChannels.keySet().iterator();
while (iterator.hasNext()) {
String clanChannel = iterator.next();
try {
validateChannel(clanTag);
validateChannel(clanChannel);
} catch (InvalidChannelException ex) {
SimpleClans.debug(ex.getMessage());
deleteChannel(clanTag);
deleteChannel(clanChannel);
iterator.remove();
} catch (ChannelExistsException | ChannelsLimitException ex) {
SimpleClans.debug(ex.getMessage());
}
}
}
private void resetPermissions() {
getCachedChannels().stream().
map(TextChannel::getMemberPermissionOverrides).
flatMap(Collection::stream).
filter(permissionOverride -> !Objects.equals(permissionOverride.getPermissionHolder(), guild.getPublicRole())).
filter(permissionOverride -> !Objects.equals(permissionOverride.getMember(), guild.getSelfMember())).
forEach(permissionOverride -> permissionOverride.delete().queue());
private void resetPermissions(Map<String, TextChannel> discordClanChannels) {
for (Map.Entry<String, TextChannel> channelEntry : discordClanChannels.entrySet()) {
TextChannel channel = channelEntry.getValue();
Clan clan = clanManager.getClan(channelEntry.getKey());
Map<ClanPlayer, Member> discordPlayers = getDiscordPlayers(clan);
clanTags.stream().map(clanManager::getClan).
filter(Objects::nonNull).
map(Clan::getMembers).
flatMap(Collection::stream).
forEach(clanPlayer -> {
Member member = getMember(clanPlayer);
Clan clan = clanPlayer.getClan();
if (member != null && clan != null) {
updateViewPermission(member, clan, ADD);
}
});
for (Member member : discordPlayers.values()) {
PermissionOverride override = channel.getPermissionOverride(member);
if (override != null) {
override.delete().queue(afterSuccess -> updateViewPermission(member, channel, ADD));
}
}
}
}
private void createChannels() {
private void createChannels(Map<String, TextChannel> discordClanChannels) {
if (!settingsManager.is(DISCORDCHAT_AUTO_CREATION)) {
return;
}
// Removes already used discord channels from creation
clanTags.removeAll(discordClanChannels.keySet());
for (String clan : clanTags) {
try {
createChannel(clan);
@@ -577,7 +596,7 @@ public class DiscordHook implements Listener {
}
Map<ClanPlayer, Member> discordClanPlayers = getDiscordPlayers(clan);
if (discordClanPlayers.size() == 0) {
if (discordClanPlayers.isEmpty()) {
throw new InvalidChannelException(String.format("Clan %s doesn't have any linked players", clanTag),
"your.clan.doesnt.have.any.linked.player");
}
@@ -611,35 +630,43 @@ public class DiscordHook implements Listener {
}
private void updateLeaderRole(@NotNull Member member, @NotNull ClanPlayer clanPlayer, DiscordAction action) {
if (!clanPlayer.isLeader()) {
if (action == ADD && clanPlayer.isLeader()) {
getGuild().addRoleToMember(member, getLeaderRole()).queue();
SimpleClans.debug(String.format("Added leader role to %s (%s) discord member", member.getNickname(), member.getId()));
} else {
getGuild().removeRoleFromMember(member, getLeaderRole()).queue();
SimpleClans.debug(String.format("Revoked leader role from %s (%s) discord member", member.getNickname(), member.getId()));
}
}
private void updateViewPermission(@Nullable Member member, @NotNull GuildChannel channel, @NotNull DiscordAction action) {
if (member == null) {
return;
}
if (action == ADD) {
guild.addRoleToMember(member, leaderRole).queue();
channel.upsertPermissionOverride(member).
setPermissions(Collections.singletonList(VIEW_CHANNEL), Collections.emptyList()).queue();
SimpleClans.debug(String.format("Added view permission to %s (%s) discord member", member.getNickname(), member.getId()));
} else {
guild.removeRoleFromMember(member, leaderRole).queue();
channel.getManager().removePermissionOverride(member).queue();
SimpleClans.debug(String.format("Revoked view permission from %s (%s) discord member", member.getNickname(), member.getId()));
}
}
private void updateViewPermission(@NotNull Member member, @NotNull Clan clan, DiscordAction action) {
Optional<TextChannel> channel = getCachedChannel(clan.getTag());
String tag = clan.getTag();
Optional<TextChannel> channel = getChannel(tag);
if (channel.isPresent()) {
TextChannel textChannel = channel.get();
if (action == ADD) {
textChannel.upsertPermissionOverride(member).
setPermissions(Collections.singletonList(VIEW_CHANNEL), Collections.emptyList()).queue();
} else {
textChannel.getManager().removePermissionOverride(member).queue();
}
updateViewPermission(member, textChannel, action);
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean createChannelSilently(ClanPlayer clanPlayer) {
Clan clan = clanPlayer.getClan();
if (clan == null) {
if (clan == null || !settingsManager.is(DISCORDCHAT_AUTO_CREATION)) {
return false;
}
@@ -118,9 +118,12 @@ public class SimpleClansExpansion extends PlaceholderExpansion implements Relati
public String onRequest(@Nullable OfflinePlayer player, @NotNull String params) {
ClanPlayer cp = null;
if (player != null) {
cp = clanManager.getCreateClanPlayer(player.getUniqueId());
cp = clanManager.getAnyClanPlayer(player.getUniqueId());
}
Clan clan = cp != null ? cp.getClan() : null;
if (cp == null) {
return "";
}
Clan clan = cp.getClan();
Matcher matcher = TOP_CLANS_PATTERN.matcher(params);
if (matcher.find()) {
int position = Integer.parseInt(matcher.group("position"));
@@ -4,25 +4,34 @@ import me.ryanhamshire.GriefPrevention.Claim;
import me.ryanhamshire.GriefPrevention.DataStore;
import me.ryanhamshire.GriefPrevention.GriefPrevention;
import me.ryanhamshire.GriefPrevention.events.ClaimCreatedEvent;
import me.ryanhamshire.GriefPrevention.events.ClaimResizeEvent;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.Coordinate;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.Land;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.ProtectionProvider;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.ProtectionManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@SuppressWarnings("unused")
public class GriefPreventionProvider implements ProtectionProvider {
public class GriefPreventionProvider implements ProtectionProvider, Listener {
@Override
public void setup() {
Bukkit.getPluginManager().registerEvents(this, SimpleClans.getInstance());
}
@Override
@@ -104,4 +113,25 @@ public class GriefPreventionProvider implements ProtectionProvider {
return Bukkit.getOfflinePlayer(claim.getOwnerName()).getUniqueId();
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
private void onResize(ClaimResizeEvent event) {
ClanManager clanManager = SimpleClans.getInstance().getClanManager();
Land originalLand = getLand(event.getFrom());
Land newLand = getLand(event.getTo());
if (originalLand == null || newLand == null) {
return;
}
for (UUID owner : originalLand.getOwners()) {
ClanPlayer cp = clanManager.getAnyClanPlayer(owner);
if (cp == null) continue;
for (ProtectionManager.Action action : ProtectionManager.Action.values()) {
if (cp.isAllowed(action, originalLand.getId())) {
cp.disallow(action, originalLand.getId());
cp.allow(action, newLand.getId());
}
}
}
}
}
@@ -1,107 +0,0 @@
package net.sacredlabyrinth.phaed.simpleclans.hooks.protection.providers;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.Coordinate;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.Land;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.ProtectionProvider;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@SuppressWarnings({"unused"})
public class WorldGuardProvider implements ProtectionProvider {
private RegionContainer regionContainer;
@Override
public void setup() {
regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer();
}
@Override
public @NotNull Set<Land> getLandsAt(@NotNull Location location) {
RegionManager regionManager = getRegionManager(location.getWorld());
if (regionManager == null) {
return Collections.emptySet();
}
ApplicableRegionSet regions = regionManager.getApplicableRegions(BukkitAdapter.asBlockVector(location));
Set<Land> lands = new HashSet<>();
for (ProtectedRegion region : regions) {
lands.add(getLand(region));
}
return lands;
}
@NotNull
private Land getLand(ProtectedRegion region) {
//noinspection DuplicatedCode
List<Coordinate> coordinates = new ArrayList<>();
for (BlockVector2 point : region.getPoints()) {
coordinates.add(new Coordinate(point.getX(), point.getZ()));
}
return new Land(getIdPrefix() + region.getId(), region.getOwners().getUniqueIds(), coordinates);
}
@Override
public @NotNull Set<Land> getLandsOf(@NotNull OfflinePlayer player, @NotNull World world) {
HashSet<Land> lands = new HashSet<>();
RegionManager regionManager = getRegionManager(world);
if (regionManager != null) {
for (ProtectedRegion region : regionManager.getRegions().values()) {
if (region.getOwners().contains(player.getUniqueId())) {
lands.add(getLand(region));
}
}
}
return lands;
}
@Override
public @NotNull String getIdPrefix() {
return "wg";
}
@Override
public void deleteLand(@NotNull String id, @NotNull World world) {
id = id.replaceFirst(getIdPrefix(), "");
RegionManager regionManager = getRegionManager(world);
if (regionManager != null) {
regionManager.removeRegion(id);
}
}
@Override
public @Nullable Class<? extends Event> getCreateLandEvent() {
return null;
}
@Override
public @Nullable Player getPlayer(Event event) {
return null;
}
@Nullable
private RegionManager getRegionManager(@Nullable World world) {
if (world == null) {
return null;
}
return regionContainer.get(BukkitAdapter.adapt(world));
}
@Override
public @Nullable String getRequiredPluginName() {
return "WorldGuard";
}
}
@@ -1,34 +1,47 @@
package net.sacredlabyrinth.phaed.simpleclans.listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
public class Events {
public final class Events {
private Events() {}
private Events() {
// Can't instantiate this class
}
@Nullable
@Contract("null -> null")
public static Player getAttacker(@Nullable EntityDamageEvent parentEvent) {
if (parentEvent instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) parentEvent;
Entity damager = sub.getDamager();
if (sub.getDamager() instanceof Player) {
return (Player) sub.getDamager();
if (damager instanceof Player) {
return (Player) damager;
}
if (sub.getDamager() instanceof Projectile) {
Projectile projectile = (Projectile) sub.getDamager();
if (damager instanceof Projectile) {
Projectile projectile = (Projectile) damager;
if (projectile.getShooter() instanceof Player) {
return (Player) projectile.getShooter();
return (Player) projectile.getShooter();
}
}
if (damager instanceof TNTPrimed) {
Entity source = ((TNTPrimed) damager).getSource();
if (source instanceof Player) {
return (Player) source;
}
}
}
return null;
}
}
}
@@ -15,7 +15,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.GLOBAL_FRIENDLY_FIRE;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.SAFE_CIVILIANS;
public class FriendlyFire extends SCListener {
@@ -16,18 +16,30 @@ import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.function.BiConsumer;
import static net.sacredlabyrinth.phaed.simpleclans.managers.ProtectionManager.Action.*;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
@@ -49,13 +61,154 @@ public class LandProtection implements Listener {
}
public void registerListeners() {
Bukkit.getPluginManager().registerEvents(this, plugin);
registerBlockBreakListener();
registerBlockPlaceListener();
registerEntityDamageListener();
registerInteractEntityListener();
registerInteractListener();
registerInventoryOpenListener();
registerListener(BlockBreakEvent.class, (event, cancel) -> {
Block block = event.getBlock();
if (settingsManager.getIgnoredList(BREAK).contains(block.getType().name())) {
return;
}
if (protectionManager.can(BREAK, block.getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(HangingBreakByEntityEvent.class, (event, cancel) -> {
Entity remover = event.getRemover();
if (!(remover instanceof Player)) {
return;
}
if (protectionManager.can(BREAK, event.getEntity().getLocation(), ((Player) remover))) {
event.setCancelled(cancel);
}
});
registerListener(HangingPlaceEvent.class, (event, cancel) -> {
Player player = event.getPlayer();
if (player == null) {
return;
}
if (protectionManager.can(PLACE, event.getBlock().getLocation(), player)) {
event.setCancelled(cancel);
}
});
registerListener(StructureGrowEvent.class, (event, cancel) -> {
if (event.getPlayer() == null) {
return;
}
if (protectionManager.can(PLACE, event.getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(BlockPlaceEvent.class, (event, cancel) -> {
Block block = event.getBlock();
if (settingsManager.getIgnoredList(PLACE).contains(block.getType().name())) {
return;
}
if (protectionManager.can(PLACE, block.getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(PlayerBucketEmptyEvent.class, (event, cancel) -> {
Block block = event.getBlockClicked();
if (settingsManager.getIgnoredList(PLACE).contains(block.getType().name())) {
return;
}
if (protectionManager.can(PLACE, block.getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(PlayerBucketFillEvent.class, (event, cancel) -> {
Block block = event.getBlockClicked().getRelative(event.getBlockFace());
if (settingsManager.getIgnoredList(BREAK).contains(block.getType().name())) {
return;
}
if (protectionManager.can(BREAK, block.getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(VehicleDestroyEvent.class, (event, cancel) -> {
if (!(event.getAttacker() instanceof Player)) {
return;
}
if (protectionManager.can(BREAK, event.getVehicle().getLocation(), ((Player) event.getAttacker()))) {
event.setCancelled(cancel);
}
});
registerListener(EntityChangeBlockEvent.class, (event, cancel) -> {
if (!(event.getEntity() instanceof Player)) {
return;
}
if (protectionManager.can(BREAK, event.getBlock().getLocation(), ((Player) event.getEntity()))) {
event.setCancelled(cancel);
}
});
registerListener(EntityDamageByEntityEvent.class, (event, cancel) -> {
Player attacker = Events.getAttacker(event);
if (attacker == null) {
return;
}
Player victim = event.getEntity() instanceof Player ? ((Player) event.getEntity()) : null;
if (victim == null) {
return;
}
if (protectionManager.can(DAMAGE, event.getEntity().getLocation(), attacker, victim)) {
event.setCancelled(cancel);
}
});
registerListener(PlayerInteractAtEntityEvent.class, (event, cancel) -> {
if (protectionManager.can(INTERACT_ENTITY, event.getRightClicked().getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(PlayerInteractEntityEvent.class, (event, cancel) -> {
if (protectionManager.can(INTERACT_ENTITY, event.getRightClicked().getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
registerListener(VehicleExitEvent.class, (event, cancel) -> {
Vehicle vehicle = event.getVehicle();
if (vehicle instanceof Tameable && event.getExited() instanceof Player) {
if (protectionManager.can(INTERACT_ENTITY, vehicle.getLocation(), ((Player) event.getExited()))) {
event.setCancelled(cancel);
}
}
});
registerListener(InventoryOpenEvent.class, (event, cancel) -> {
InventoryHolder holder = event.getInventory().getHolder();
Location location = getLocation(holder);
if (holder instanceof Entity && holder == event.getPlayer()) return;
if (location == null) return;
if (protectionManager.can(CONTAINER, location, ((Player) event.getPlayer()))) {
event.setCancelled(cancel);
}
});
registerListener(PlayerInteractEvent.class, (event, cancel) -> {
if (event.getClickedBlock() == null) {
return;
}
ProtectionManager.Action action = getInteractEventAction(event);
if (protectionManager.can(action, event.getClickedBlock().getLocation(), event.getPlayer())) {
event.setUseInteractedBlock(cancel ? Result.DENY : Result.ALLOW);
event.setUseItemInHand(cancel ? Result.DENY : Result.ALLOW);
event.setCancelled(cancel);
}
});
registerListener(PlayerBedEnterEvent.class, (event, cancel) -> {
if (protectionManager.can(INTERACT, event.getBed().getLocation(), event.getPlayer())) {
event.setCancelled(cancel);
}
});
}
private <T extends Event> void registerListener(Class<T> clazz, BiConsumer<T, Boolean> listener) {
Bukkit.getPluginManager().registerEvent(clazz, this, EventPriority.LOWEST, (l, event) -> {
if (clazz.isInstance(event)) {
listener.accept(clazz.cast(event), true);
}
}, plugin, false);
Bukkit.getPluginManager().registerEvent(clazz, this, priority, (l, event) -> {
if (clazz.isInstance(event)) {
listener.accept(clazz.cast(event), false);
}
}, plugin, false);
}
public void registerCreateLandEvent(ProtectionProvider provider, @Nullable Class<? extends Event> createLandEvent) {
@@ -95,169 +248,6 @@ public class LandProtection implements Listener {
((Cancellable) event).setCancelled(true);
}
private void registerBlockBreakListener() {
Bukkit.getPluginManager().registerEvent(BlockBreakEvent.class, this, priority, (listener, event) -> {
if (!(event instanceof BlockBreakEvent)) {
return;
}
BlockBreakEvent blockBreakEvent = (BlockBreakEvent) event;
Block block = blockBreakEvent.getBlock();
if (settingsManager.getIgnoredList(BREAK).contains(block.getType().name())) {
return;
}
if (protectionManager.can(BREAK, block.getLocation(), blockBreakEvent.getPlayer())) {
blockBreakEvent.setCancelled(false);
}
}, plugin, false);
}
private void registerBlockPlaceListener() {
Bukkit.getPluginManager().registerEvent(BlockPlaceEvent.class, this, priority, (listener, event) -> {
if (!(event instanceof BlockPlaceEvent)) {
return;
}
BlockPlaceEvent blockPlaceEvent = (BlockPlaceEvent) event;
Block block = blockPlaceEvent.getBlock();
if (settingsManager.getIgnoredList(PLACE).contains(block.getType().name())) {
return;
}
if (protectionManager.can(PLACE, block.getLocation(), blockPlaceEvent.getPlayer())) {
blockPlaceEvent.setCancelled(false);
}
}, plugin, false);
}
private void registerEntityDamageListener() {
Bukkit.getPluginManager().registerEvent(EntityDamageByEntityEvent.class, this, priority,
(listener, event) -> {
if (!(event instanceof EntityDamageByEntityEvent)) {
return;
}
EntityDamageByEntityEvent entityEvent = (EntityDamageByEntityEvent) event;
if (!(entityEvent.getDamager() instanceof Player)) {
return;
}
Player attacker = ((Player) entityEvent.getDamager());
Player victim = entityEvent.getEntity() instanceof Player ? ((Player) entityEvent.getEntity()) : null;
if (protectionManager.can(DAMAGE, entityEvent.getEntity().getLocation(), attacker, victim)) {
entityEvent.setCancelled(false);
}
}, plugin, false);
}
private void registerInteractEntityListener() {
Bukkit.getPluginManager().registerEvent(PlayerInteractEntityEvent.class, this, priority, (listener, event) -> {
if (!(event instanceof PlayerInteractEntityEvent)) {
return;
}
PlayerInteractEntityEvent interactEvent = (PlayerInteractEntityEvent) event;
if (protectionManager.can(INTERACT_ENTITY, interactEvent.getRightClicked().getLocation(), interactEvent.getPlayer())) {
interactEvent.setCancelled(false);
}
}, plugin, false);
}
private void registerInventoryOpenListener() {
Bukkit.getPluginManager().registerEvent(InventoryOpenEvent.class, this, priority, (l, e) -> {
if (!(e instanceof InventoryOpenEvent)) {
return;
}
InventoryOpenEvent event = ((InventoryOpenEvent) e);
InventoryHolder holder = event.getInventory().getHolder();
Location location = getLocation(holder);
if (holder instanceof Entity && holder == event.getPlayer()) return;
if (location == null) return;
if (protectionManager.can(CONTAINER, location, ((Player) event.getPlayer()))) {
event.setCancelled(false);
}
}, plugin, false);
}
private void registerInteractListener() {
Bukkit.getPluginManager().registerEvent(PlayerInteractEvent.class, this, priority, (listener, event) -> {
if (!(event instanceof PlayerInteractEvent)) {
return;
}
PlayerInteractEvent interactEvent = (PlayerInteractEvent) event;
if (interactEvent.getClickedBlock() == null) {
return;
}
ProtectionManager.Action action = getInteractEventAction(interactEvent);
if (protectionManager.can(action, interactEvent.getClickedBlock().getLocation(), interactEvent.getPlayer())) {
interactEvent.setUseInteractedBlock(Event.Result.ALLOW);
interactEvent.setUseItemInHand(Event.Result.ALLOW);
interactEvent.setCancelled(false);
}
}, plugin, false);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBreak(BlockBreakEvent event) {
Block block = event.getBlock();
if (settingsManager.getIgnoredList(BREAK).contains(block.getType().name())) {
return;
}
if (protectionManager.can(BREAK, block.getLocation(), event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlace(BlockPlaceEvent event) {
Block block = event.getBlock();
if (settingsManager.getIgnoredList(PLACE).contains(block.getType().name())) {
return;
}
if (protectionManager.can(PLACE, block.getLocation(), event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onDamage(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
if (!(damager instanceof Player)) {
return;
}
Player victim = event.getEntity() instanceof Player ? ((Player) event.getEntity()) : null;
if (protectionManager.can(DAMAGE, event.getEntity().getLocation(), (Player) damager, victim)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryOpen(InventoryOpenEvent event) {
InventoryHolder holder = event.getInventory().getHolder();
Location location = getLocation(holder);
if (holder instanceof Entity && holder == event.getPlayer()) return;
if (location == null) return;
if (protectionManager.can(CONTAINER, location, ((Player) event.getPlayer()))) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInteractEntity(PlayerInteractEntityEvent event) {
if (protectionManager.can(INTERACT_ENTITY, event.getRightClicked().getLocation(), event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null) {
return;
}
ProtectionManager.Action action = getInteractEventAction(event);
if (protectionManager.can(action, event.getClickedBlock().getLocation(), event.getPlayer())) {
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
event.setCancelled(true);
}
}
private @Nullable Location getLocation(@Nullable InventoryHolder holder) {
if (holder instanceof BlockState) {
return ((BlockState) holder).getLocation();
@@ -18,6 +18,7 @@ import java.time.LocalDateTime;
import java.util.logging.Level;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.events.EconomyTransactionEvent.Cause.PLAYER_KILLED;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
/**
@@ -48,6 +49,7 @@ public class PlayerDeath extends SCListener {
// record death for victim
victimCp.addDeath();
plugin.getStorageManager().updateClanPlayer(victimCp);
plugin.getStorageManager().updateClanPlayer(attackerCp);
}
@EventHandler
@@ -98,7 +100,7 @@ public class PlayerDeath extends SCListener {
}
player.sendMessage(ChatColor.AQUA + lang("player.got.money", player, money,
victim.getName(), attacker.getKDR()));
plugin.getPermissionsManager().playerGrantMoney(player, money);
plugin.getPermissionsManager().grantPlayer(player, money, PLAYER_KILLED);
}
}
}
@@ -165,7 +167,7 @@ public class PlayerDeath extends SCListener {
ClanPlayer killer = kill.getKiller();
ClanPlayer victim = kill.getVictim();
killer.addKill(type);
plugin.getStorageManager().insertKill(killer, victim, type.getShortname());
plugin.getStorageManager().insertKill(killer, victim, type.getShortname(), kill.getTime());
}
private double calculateReward(@NotNull ClanPlayer attacker, @NotNull ClanPlayer victim) {
@@ -83,15 +83,12 @@ public class SCPlayerListener extends SCListener {
if (isBlacklistedWorld(player)) {
return;
}
ClanPlayer cp = plugin.getClanManager().getAnyClanPlayer(player.getUniqueId());
ClanPlayer cp = plugin.getClanManager().getCreateClanPlayer(player.getUniqueId());
updatePlayerName(player);
plugin.getClanManager().updateLastSeen(player);
plugin.getClanManager().updateDisplayName(player);
if (cp == null) {
return;
}
plugin.getPermissionsManager().addPlayerPermissions(cp);
if (settingsManager.is(BB_SHOW_ON_LOGIN) && cp.isBbEnabled() && cp.getClan() != null) {
@@ -190,7 +187,7 @@ public class SCPlayerListener extends SCListener {
if (duplicate != null) {
plugin.getLogger().warning(String.format("Found duplicate for %s, UUIDs: %s, %s", player.getName(),
player.getUniqueId(), duplicate.getUniqueId()));
duplicate.setName(duplicate.getName() + "_duplicate");
duplicate.setName(duplicate.getUniqueId().toString());
plugin.getStorageManager().updatePlayerName(duplicate);
}
if (cp != null) {
@@ -130,10 +130,11 @@ public final class ChatManager {
.replace("%nick-color%",
(sender.isLeader() ? leaderColor : sender.isTrusted() ? trustedColor : memberColor))
.replace("%player%", sender.getName())
.replace("%rank%", rankFormat)
.replace("%rank%", rankFormat);
parsedFormat = parseWithPapi(message.getSender(), parsedFormat)
.replace("%message%", message.getContent());
return parseWithPapi(message.getSender(), parsedFormat);
return parsedFormat;
}
public boolean isDiscordHookEnabled() {
@@ -1,11 +1,14 @@
package net.sacredlabyrinth.phaed.simpleclans.managers;
import com.cryptomorin.xseries.XMaterial;
import net.md_5.bungee.api.chat.TextComponent;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.CreateClanEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.EconomyTransactionEvent.Cause;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.VanishUtils;
import net.sacredlabyrinth.phaed.simpleclans.uuid.UUIDMigration;
import org.bukkit.Bukkit;
@@ -24,10 +27,12 @@ import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static org.bukkit.ChatColor.AQUA;
import static org.bukkit.ChatColor.RED;
/**
@@ -36,8 +41,8 @@ import static org.bukkit.ChatColor.RED;
public final class ClanManager {
private final SimpleClans plugin;
private final HashMap<String, Clan> clans = new HashMap<>();
private final HashMap<UUID, ClanPlayer> clanPlayers = new HashMap<>();
private final ConcurrentHashMap<String, Clan> clans = new ConcurrentHashMap<>();
private final ConcurrentHashMap<UUID, ClanPlayer> clanPlayers = new ConcurrentHashMap<>();
private final HashMap<ClanPlayer, List<Kill>> kills = new HashMap<>();
/**
@@ -74,7 +79,7 @@ public final class ClanManager {
continue;
}
//cleaning
// cleaning
final int delay = plugin.getSettingsManager().getInt(KDR_DELAY_BETWEEN_KILLS);
long timePassed = oldKill.getTime().until(LocalDateTime.now(), ChronoUnit.MINUTES);
if (timePassed >= delay) {
@@ -145,7 +150,7 @@ public final class ClanManager {
importClan(clan);
plugin.getStorageManager().updateClanPlayer(cp);
plugin.getRequestManager().deny(cp); //denies any previous invitation
plugin.getRequestManager().deny(cp); // denies any previous invitation
SimpleClans.getInstance().getPermissionsManager().updateClanPermissions(clan);
SimpleClans.getInstance().getServer().getPluginManager().callEvent(new CreateClanEvent(clan));
}
@@ -325,20 +330,20 @@ public final class ClanManager {
return clanPlayers.get(uuid);
}
@SuppressWarnings("deprecation")
@Nullable
public ClanPlayer getAnyClanPlayer(String playerName) {
for (ClanPlayer cp : getAllClanPlayers()) {
if (cp.getName().equals(playerName)) {
if (cp.getName().equalsIgnoreCase(playerName)) {
return cp;
}
}
return getAnyClanPlayer(Bukkit.getOfflinePlayer(playerName).getUniqueId());
return null;
}
/**
* Gets the ClanPlayer object for the player, creates one if not found
*/
@Deprecated
public @Nullable ClanPlayer getCreateClanPlayerUUID(String playerName) {
UUID playerUniqueId = UUIDMigration.getForcedPlayerUUID(playerName);
if (playerUniqueId != null) {
@@ -392,8 +397,9 @@ public final class ClanManager {
if (plugin.getSettingsManager().is(DISABLE_MESSAGES)) {
return;
}
plugin.getProxyManager().sendMessage("ALL", ChatColor.DARK_GRAY + "* " + ChatColor.AQUA + msg);
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "[" + lang("server.announce") + "] " + ChatColor.WHITE + msg);
plugin.getProxyManager().sendMessage("ALL", ChatColor.DARK_GRAY + "* " + AQUA + msg);
Bukkit.getConsoleSender().sendMessage(AQUA + "[" + lang("server.announce") + "] " + ChatColor.WHITE + msg);
}
/**
@@ -412,8 +418,10 @@ public final class ClanManager {
if (plugin.getSettingsManager().is(DISPLAY_CHAT_TAGS)) {
String prefix = plugin.getPermissionsManager().getPrefix(player);
//String suffix = plugin.getPermissionsManager().getSuffix(player);
String lastColor = plugin.getSettingsManager().is(COLOR_CODE_FROM_PREFIX_FOR_NAME) ? ChatUtils.getLastColorCode(prefix) : ChatColor.WHITE + "";
// String suffix = plugin.getPermissionsManager().getSuffix(player);
String lastColor = plugin.getSettingsManager().is(COLOR_CODE_FROM_PREFIX_FOR_NAME)
? ChatUtils.getLastColorCode(prefix)
: ChatColor.WHITE + "";
String fullName = player.getName();
ClanPlayer cp = plugin.getClanManager().getAnyClanPlayer(player.getUniqueId());
@@ -523,7 +531,7 @@ public final class ClanManager {
if (h.getType().equals(XMaterial.CHAINMAIL_HELMET.parseMaterial())) {
out += ChatColor.WHITE + lang("armor.h", player);
} else if (h.getType().equals(XMaterial.DIAMOND_HELMET.parseMaterial())) {
out += ChatColor.AQUA + lang("armor.h", player);
out += AQUA + lang("armor.h", player);
} else if (h.getType().equals(XMaterial.GOLDEN_HELMET.parseMaterial())) {
out += ChatColor.YELLOW + lang("armor.h", player);
} else if (h.getType().equals(XMaterial.IRON_HELMET.parseMaterial())) {
@@ -542,7 +550,7 @@ public final class ClanManager {
if (c.getType().equals(XMaterial.CHAINMAIL_CHESTPLATE.parseMaterial())) {
out += ChatColor.WHITE + lang("armor.c", player);
} else if (c.getType().equals(XMaterial.DIAMOND_CHESTPLATE.parseMaterial())) {
out += ChatColor.AQUA + lang("armor.c", player);
out += AQUA + lang("armor.c", player);
} else if (c.getType().equals(XMaterial.GOLDEN_CHESTPLATE.parseMaterial())) {
out += ChatColor.YELLOW + lang("armor.c", player);
} else if (c.getType().equals(XMaterial.IRON_CHESTPLATE.parseMaterial())) {
@@ -580,7 +588,7 @@ public final class ClanManager {
if (b.getType().equals(XMaterial.CHAINMAIL_BOOTS.parseMaterial())) {
out += ChatColor.WHITE + lang("armor.B", player);
} else if (b.getType().equals(XMaterial.DIAMOND_BOOTS.parseMaterial())) {
out += ChatColor.AQUA + lang("armor.B", player);
out += AQUA + lang("armor.B", player);
} else if (b.getType().equals(XMaterial.GOLDEN_BOOTS.parseMaterial())) {
out += ChatColor.YELLOW + lang("armor.B", player);
} else if (b.getType().equals(XMaterial.IRON_BOOTS.parseMaterial())) {
@@ -594,7 +602,7 @@ public final class ClanManager {
}
}
if (out.length() == 0) {
if (out.isEmpty()) {
out = lang("none", player);
}
@@ -619,7 +627,7 @@ public final class ClanManager {
if (count > 0) {
String countString = count > 1 ? count + "" : "";
out += ChatColor.AQUA + lang("weapon.S", player) + headColor + countString;
out += AQUA + lang("weapon.S", player) + headColor + countString;
}
count = getItemCount(inv, XMaterial.GOLDEN_SWORD);
@@ -665,7 +673,7 @@ public final class ClanManager {
out += ChatColor.WHITE + lang("weapon.A", player) + headColor + count;
}
if (out.length() == 0) {
if (out.isEmpty()) {
out = lang("none", player);
}
@@ -926,10 +934,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.MEMBER_FEE_SET);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -949,10 +957,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_CREATION);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -972,10 +980,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_INVITATION);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -995,10 +1003,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_HOME_TELEPORT);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -1018,10 +1026,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_HOME_TELEPORT_SET);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -1041,10 +1049,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.RESET_KDR);
player.spigot().sendMessage(new TextComponent(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price))));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.spigot().sendMessage(new TextComponent(RED + MessageFormat.format(lang("not.sufficient.money", player), CurrencyFormat.format(price))));
return false;
}
}
@@ -1071,29 +1079,25 @@ public final class ClanManager {
price = price * VanishUtils.getNonVanished(player, clan).size();
}
if (plugin.getSettingsManager().is(ECONOMY_ISSUER_PAYS_REGROUP)) {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
return false;
}
if (plugin.getSettingsManager().is(ECONOMY_ISSUER_PAYS_REGROUP) && plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_REGROUP);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
} else {
double money = plugin.getPermissionsManager().playerGetMoney(player);
switch (clan.withdraw(new BankOperator(player, money), ClanBalanceUpdateEvent.Cause.COMMAND, price)) {
case SUCCESS:
if (plugin.getPermissionsManager().playerGrantMoney(player, price)) {
player.sendMessage(ChatColor.AQUA + lang("player.clan.withdraw", player, price));
clan.addBb(player.getName(), ChatColor.AQUA + lang("bb.clan.withdraw", price));
if (plugin.getPermissionsManager().grantPlayer(player, price)) {
player.sendMessage(AQUA + lang("player.clan.withdraw", player, CurrencyFormat.format(price)));
clan.addBb(player.getName(), lang("bb.clan.withdraw", CurrencyFormat.format(price)));
return true;
}
break;
case NOT_ENOUGH_BALANCE:
player.sendMessage(lang("clan.bank.not.enough.money", player));
break;
}
}
@@ -1112,10 +1116,10 @@ public final class ClanManager {
if (plugin.getPermissionsManager().hasEconomy()) {
if (plugin.getPermissionsManager().playerHasMoney(player, price)) {
plugin.getPermissionsManager().playerChargeMoney(player, price);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), price));
plugin.getPermissionsManager().chargePlayer(player, price, Cause.CLAN_VERIFICATION);
player.sendMessage(RED + MessageFormat.format(lang("account.has.been.debited", player), CurrencyFormat.format(price)));
} else {
player.sendMessage(RED + lang("not.sufficient.money", player, price));
player.sendMessage(RED + lang("not.sufficient.money", player, CurrencyFormat.format(price)));
return false;
}
}
@@ -1145,11 +1149,11 @@ public final class ClanManager {
if (command.equals(lang("on", player))) {
cp.setGlobalChat(true);
plugin.getStorageManager().updateClanPlayer(cp);
ChatBlock.sendMessage(player, ChatColor.AQUA + "You have enabled global chat");
ChatBlock.sendMessage(player, AQUA + "You have enabled global chat");
} else if (command.equals(lang("off", player))) {
cp.setGlobalChat(false);
plugin.getStorageManager().updateClanPlayer(cp);
ChatBlock.sendMessage(player, ChatColor.AQUA + "You have disabled global chat");
ChatBlock.sendMessage(player, AQUA + "You have disabled global chat");
} else {
return true;
}
@@ -2,23 +2,29 @@ package net.sacredlabyrinth.phaed.simpleclans.managers;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import net.milkbowl.vault.permission.Permission;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.events.EconomyTransactionEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.EconomyTransactionEvent.Cause;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.ENABLE_AUTO_GROUPS;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.PERMISSIONS_AUTO_GROUP_GROUPNAME;
import static org.bukkit.Bukkit.getPluginManager;
/**
* @author phaed
@@ -50,7 +56,6 @@ public final class PermissionsManager {
/**
* Whether economy plugin exists and is enabled
*
*/
public boolean hasEconomy() {
return economy != null && economy.isEnabled();
@@ -80,7 +85,6 @@ public final class PermissionsManager {
/**
* Adds all permissions for a clan
*
*/
public void updateClanPermissions(Clan clan) {
for (ClanPlayer cp : clan.getMembers()) {
@@ -90,7 +94,6 @@ public final class PermissionsManager {
/**
* Adds permissions for a player
*
*/
public void addPlayerPermissions(@Nullable ClanPlayer cp) {
if (cp == null) {
@@ -120,7 +123,6 @@ public final class PermissionsManager {
/**
* Removes permissions for a clan (when it gets disbanded for example)
*
*/
public void removeClanPermissions(Clan clan) {
for (ClanPlayer cp : clan.getMembers()) {
@@ -131,7 +133,6 @@ public final class PermissionsManager {
/**
* Removes permissions for a player (when he gets kicked for example)
*
*/
public void removeClanPlayerPermissions(@Nullable ClanPlayer cp) {
if (cp != null && cp.getClan() != null && cp.toPlayer() != null) {
@@ -166,20 +167,133 @@ public final class PermissionsManager {
return permissions.get(clan.getTag());
}
public String format(double value) {
return Objects.requireNonNull(economy, "Can't find economy provider").format(value);
}
/**
* Charge a player some money
*
* @deprecated use {@link PermissionsManager#chargePlayer(OfflinePlayer, double)} instead
*/
@Deprecated
public boolean playerChargeMoney(OfflinePlayer player, double money) {
return economy.withdrawPlayer(player, money).transactionSuccess();
return chargePlayer(player, money);
}
/**
* Charges the specified amount of money from the player's account.
* <p>
* As the {@link EconomyTransactionEvent.Cause} is not passed, this method won't fire the {@link EconomyTransactionEvent}.
* Use this method when you don't need to track the cause or handle custom transaction events.
* </p>
*
* @param player The player whose account will be charged.
* @param money The amount of money to charge.
* @see EconomyTransactionEvent
*/
public boolean chargePlayer(OfflinePlayer player, double money) {
return chargePlayer(player, money, null);
}
/**
* Charges the specified amount of money from the player's account.
*
* @param player The player whose account will be charged.
* @param money The amount of money to charge.
* @param cause The cause of the transaction.
* @return {@code true} if the charge was successful, {@code false} otherwise.
* @see EconomyTransactionEvent
*/
public boolean chargePlayer(@NotNull OfflinePlayer player, double money, @Nullable Cause cause) {
EconomyResponse response = Objects.requireNonNull(economy, "Can't find economy provider").withdrawPlayer(player, money);
if (!response.transactionSuccess()) {
return false;
} else if (cause == null) {
return true;
}
EconomyTransactionEvent event = new EconomyTransactionEvent(player, money, cause, EconomyTransactionEvent.TransactionType.WITHDRAW);
getPluginManager().callEvent(event);
if (event.isCancelled()) {
economy.depositPlayer(player, money);
return false;
}
// handle EconomyTransactionEvent#setAmount
double difference = event.getAmount() - response.amount;
if (difference > 0) {
economy.withdrawPlayer(player, difference);
}
if (difference < 0) {
economy.depositPlayer(player, Math.abs(difference));
}
return true;
}
/**
* Grants a player some money
*
* @deprecated use {@link PermissionsManager#grantPlayer(OfflinePlayer, double)} instead
*/
@Deprecated
public boolean playerGrantMoney(OfflinePlayer player, double money) {
return economy.depositPlayer(player, money).transactionSuccess();
return grantPlayer(player, money);
}
/**
* Grants the specified amount of money to the player's account.
* <p>
* As the {@link EconomyTransactionEvent.Cause} is not passed, this method won't fire the {@link EconomyTransactionEvent}.
* Use this method when you don't need to track the cause or handle custom transaction events.
* </p>
*
* @param player The player to whom the money will be granted.
* @param money The amount of money to grant.
* @see PermissionsManager#grantPlayer(OfflinePlayer, double, Cause)
* @see EconomyTransactionEvent
*/
public boolean grantPlayer(OfflinePlayer player, double money) {
return grantPlayer(player, money, null);
}
/**
* Grants the specified amount of money to the player's account.
*
* @param player The player to whom the money will be granted.
* @param money The amount of money to grant.
* @param cause The cause of the transaction.
* @return {@code true} if the grant was successful, {@code false} otherwise.
* @see EconomyTransactionEvent
*/
public boolean grantPlayer(@NotNull OfflinePlayer player, double money, @Nullable Cause cause) {
EconomyResponse response = Objects.requireNonNull(economy, "Can't find economy provider").depositPlayer(player, money);
if (!response.transactionSuccess()) {
return false;
} else if (cause == null) {
return true;
}
EconomyTransactionEvent event = new EconomyTransactionEvent(player, response.amount, cause, EconomyTransactionEvent.TransactionType.DEPOSIT);
getPluginManager().callEvent(event);
if (event.isCancelled()) {
economy.withdrawPlayer(player, money);
return false;
}
// handle EconomyTransactionEvent#setAmount
double difference = event.getAmount() - response.amount;
if (difference > 0) {
economy.depositPlayer(player, difference);
}
if (difference < 0) {
economy.withdrawPlayer(player, Math.abs(difference));
}
return true;
}
/**
@@ -226,10 +340,9 @@ public final class PermissionsManager {
/**
* Checks if the player has the rank permission or the permission level, and the equivalent Bukkit permission
*
* @param player the player
* @param player the player
* @param permission the rank permission
* @param notify notify the player if they don't have permission
*
* @param notify notify the player if they don't have permission
* @deprecated use {@link PermissionsManager#has(Player, RankPermission, boolean)} or {@link PermissionsManager#has(Player, String)}
*/
@Deprecated
@@ -248,17 +361,7 @@ public final class PermissionsManager {
return false;
}
boolean hasLevel = false;
if (level != null) {
switch (level) {
case LEADER:
hasLevel = clanPlayer.isLeader();
break;
case TRUSTED:
hasLevel = clanPlayer.isTrusted();
break;
}
}
boolean hasLevel = hasLevel(clanPlayer, level);
boolean hasRankPermission = false;
String rankName = clanPlayer.getRankId();
@@ -282,9 +385,9 @@ public final class PermissionsManager {
/**
* Checks if the player has the rank permission or the permission level, and the equivalent Bukkit permission
*
* @param player the player
* @param player the player
* @param permission the rank permission
* @param notify notify the player if they don't have permission
* @param notify notify the player if they don't have permission
*/
public boolean has(Player player, RankPermission permission, boolean notify) {
if (player == null || permission == null) {
@@ -307,16 +410,7 @@ public final class PermissionsManager {
return false;
}
boolean hasLevel = false;
switch (permission.getPermissionLevel()) {
case LEADER:
hasLevel = clanPlayer.isLeader();
break;
case TRUSTED:
hasLevel = clanPlayer.isTrusted();
break;
}
boolean hasLevel = hasLevel(clanPlayer, permission.getPermissionLevel());
boolean hasRankPermission = false;
String rankName = clanPlayer.getRankId();
Clan clan = clanPlayer.getClan();
@@ -337,9 +431,20 @@ public final class PermissionsManager {
return hasLevel || hasRankPermission;
}
private boolean hasLevel(@NotNull ClanPlayer cp, @Nullable PermissionLevel level) {
if (level != null) {
switch (level) {
case LEADER:
return cp.isLeader();
case TRUSTED:
return cp.isTrusted();
}
}
return false;
}
/**
* Gives the player permissions linked to a clan
*
*/
public void addClanPermissions(ClanPlayer cp) {
if (!plugin.getSettingsManager().is(ENABLE_AUTO_GROUPS) || cp == null || permission == null) {
@@ -9,7 +9,10 @@ import net.sacredlabyrinth.phaed.simpleclans.events.WarStartEvent;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.Land;
import net.sacredlabyrinth.phaed.simpleclans.hooks.protection.ProtectionProvider;
import net.sacredlabyrinth.phaed.simpleclans.listeners.LandProtection;
import org.bukkit.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
@@ -5,9 +5,7 @@ import net.sacredlabyrinth.phaed.simpleclans.events.RequestEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.RequestFinishedEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.WarEndEvent;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.uuid.UUIDMigration;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
@@ -17,8 +15,7 @@ import java.text.MessageFormat;
import java.util.*;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.CLAN_MAX_MEMBERS;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.REQUEST_FREQUENCY;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static org.bukkit.ChatColor.RED;
/**
@@ -42,124 +39,145 @@ public final class RequestManager {
}
public void addDemoteRequest(ClanPlayer requester, String demotedName, Clan clan) {
if (requests.containsKey(clan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("asking.for.the.demotion"), requester.getName(), demotedName);
if (requests.containsKey(clan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("asking.for.the.demotion"), requester.getName(), demotedName);
ClanPlayer demotedTp = plugin.getClanManager().getClanPlayer(UUIDMigration.getForcedPlayerUUID(demotedName));
ClanPlayer demotedTp = plugin.getClanManager().getAnyClanPlayer(demotedName);
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(clan.getLeaders());
acceptors.remove(demotedTp);
Request req = new Request(plugin, ClanRequest.DEMOTE, acceptors, requester, demotedName, clan, msg);
Request req = new Request(ClanRequest.DEMOTE, acceptors, requester, demotedName, clan, msg);
req.vote(requester.getName(), VoteResult.ACCEPT);
requests.put(req.getClan().getTag(), req);
ask(req);
}
public void addPromoteRequest(ClanPlayer requester, String promotedName, Clan clan) {
if (requests.containsKey(clan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("asking.for.the.promotion"), requester.getName(), promotedName);
/**
* This method asks <i>all</i> leaders about
* some action <i>inside</i> their clan.
* <p>
* Example of possible requests:
* </p>
* <ul>
* <li>Disband request can be asked from all leaders</li>
* <li>Rename request can be asked from all leaders</li>
* <li>Promote request can be asked from all leaders</li>
* </ul>
*
* <p>
* Examples of incompatible requests:
* </p>
* <ul>
* <li>Demote request can be asked from all leaders,
* <b>except the demoted one.</b></li>
* <li>Invite request has to ask someone <b>outside</b> of leaders clan</li>
* </ul>
*
* @param requester the clan player, who sent the request
* @param request the type of request, see: {@link ClanRequest}
* @param target the target which will be used in request processing
* @param key the language key that would be translated and send the message to all leaders
* @param args the language objects, requires in some language strings.
* @throws IllegalArgumentException if passed incompatible request
*/
public void requestAllLeaders(@NotNull ClanPlayer requester, @NotNull ClanRequest request,
@NotNull String target, @NotNull String key, @Nullable Object... args) {
if (request.equals(ClanRequest.INVITE) || request.equals(ClanRequest.DEMOTE)) {
throw new IllegalArgumentException("Unsupported request: " + request.name());
}
Clan clan = requester.getClan();
if (clan == null || requests.containsKey(clan.getTag())) {
return;
}
String msg = lang(key, args);
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(clan.getLeaders());
Request req = new Request(plugin, ClanRequest.PROMOTE, acceptors, requester, promotedName, clan, msg);
requests.put(req.getClan().getTag(), req);
Request req = new Request(request, acceptors, requester, target, clan, msg);
requests.put(clan.getTag(), req);
req.vote(requester.getName(), VoteResult.ACCEPT);
ask(req);
}
public void addDisbandRequest(ClanPlayer requester, Clan clan) {
if (requests.containsKey(clan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("asking.for.the.deletion"), requester.getName());
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(clan.getLeaders());
Request req = new Request(plugin, ClanRequest.DISBAND, acceptors, requester, clan.getTag(), clan, msg);
requests.put(req.getTarget(), req);
req.vote(requester.getName(), VoteResult.ACCEPT);
ask(req);
}
/**
* Add a member invite request
*
* @param requester the requester
* @param requester the requester
* @param invitedName the invited Player
* @param clan the Clan
* @param clan the Clan
*/
public void addInviteRequest(ClanPlayer requester, String invitedName, Clan clan) {
if (requests.containsKey(invitedName.toLowerCase())) {
return;
}
if (requests.containsKey(invitedName.toLowerCase())) {
return;
}
Player player = Bukkit.getPlayer(invitedName);
if (player == null) {
return;
}
String msg = lang("inviting.you.to.join", player, requester.getName(), clan.getName());
Request req = new Request(plugin, ClanRequest.INVITE, null, requester, invitedName, clan, msg);
String msg = lang("inviting.you.to.join", player, requester.getName(), clan.getName());
Request req = new Request(ClanRequest.INVITE, null, requester, invitedName, clan, msg);
requests.put(invitedName.toLowerCase(), req);
ask(req);
}
public void addWarStartRequest(ClanPlayer requester, Clan warClan, Clan requestingClan) {
if (requests.containsKey(warClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.war"), requestingClan.getName(), ChatUtils.stripColors(warClan.getColorTag()));
if (requests.containsKey(warClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.war"), requestingClan.getName(), ChatUtils.stripColors(warClan.getColorTag()));
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(warClan.getLeaders());
acceptors.remove(requester);
Request req = new Request(plugin, ClanRequest.START_WAR, acceptors, requester, warClan.getTag(), requestingClan, msg);
Request req = new Request(ClanRequest.START_WAR, acceptors, requester, warClan.getTag(), requestingClan, msg);
requests.put(req.getTarget(), req);
ask(req);
}
public void addWarEndRequest(ClanPlayer requester, Clan warClan, Clan requestingClan) {
if (requests.containsKey(warClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.to.end.the.war"), requestingClan.getName(), ChatUtils.stripColors(warClan.getColorTag()));
if (requests.containsKey(warClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.to.end.the.war"), requestingClan.getName(), ChatUtils.stripColors(warClan.getColorTag()));
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(warClan.getLeaders());
acceptors.remove(requester);
Request req = new Request(plugin, ClanRequest.END_WAR, acceptors, requester, warClan.getTag(), requestingClan, msg);
Request req = new Request(ClanRequest.END_WAR, acceptors, requester, warClan.getTag(), requestingClan, msg);
requests.put(req.getTarget(), req);
ask(req);
}
public void addAllyRequest(ClanPlayer requester, Clan allyClan, Clan requestingClan) {
if (requests.containsKey(allyClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.an.alliance"), requestingClan.getName(), ChatUtils.stripColors(allyClan.getColorTag()));
if (requests.containsKey(allyClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.an.alliance"), requestingClan.getName(), ChatUtils.stripColors(allyClan.getColorTag()));
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(allyClan.getLeaders());
acceptors.remove(requester);
Request req = new Request(plugin, ClanRequest.CREATE_ALLY, acceptors, requester, allyClan.getTag(), requestingClan, msg);
Request req = new Request(ClanRequest.CREATE_ALLY, acceptors, requester, allyClan.getTag(), requestingClan, msg);
requests.put(req.getTarget(), req);
ask(req);
}
public void addRivalryBreakRequest(ClanPlayer requester, Clan rivalClan, Clan requestingClan) {
if (requests.containsKey(rivalClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.to.end.the.rivalry"), requestingClan.getName(), ChatUtils.stripColors(rivalClan.getColorTag()));
if (requests.containsKey(rivalClan.getTag())) {
return;
}
String msg = MessageFormat.format(lang("proposing.to.end.the.rivalry"), requestingClan.getName(), ChatUtils.stripColors(rivalClan.getColorTag()));
List<ClanPlayer> acceptors = Helper.stripOffLinePlayers(rivalClan.getLeaders());
acceptors.remove(requester);
Request req = new Request(plugin, ClanRequest.BREAK_RIVALRY, acceptors, requester, rivalClan.getTag(), requestingClan, msg);
Request req = new Request(ClanRequest.BREAK_RIVALRY, acceptors, requester, rivalClan.getTag(), requestingClan, msg);
requests.put(req.getTarget(), req);
ask(req);
}
@@ -205,11 +223,11 @@ public final class RequestManager {
if (vote.equals(VoteResult.ACCEPT)) {
ClanPlayer cp = plugin.getClanManager().getCreateClanPlayer(invited.getUniqueId());
int maxMembers = plugin.getSettingsManager().getInt(CLAN_MAX_MEMBERS);
int maxMembers = !clan.isVerified() ? plugin.getSettingsManager().getInt(CLAN_UNVERIFIED_MAX_MEMBERS) : plugin.getSettingsManager().getInt(CLAN_MAX_MEMBERS);
if (maxMembers > 0 && maxMembers > clan.getSize()) {
ChatBlock.sendMessageKey(invited, "accepted.invitation", clan.getName());
clan.addBb(ChatColor.AQUA + lang("joined.the.clan", invited.getName()));
clan.addBb(lang("joined.the.clan", invited.getName()));
plugin.getClanManager().serverAnnounce(lang("has.joined", invited.getName(), clan.getName()));
clan.addPlayerToClan(cp);
} else {
@@ -221,87 +239,105 @@ public final class RequestManager {
}
}
public void processResults(Request req) {
Clan requestClan = req.getClan();
ClanPlayer requester = req.getRequester();
String target = req.getTarget();
Clan requestClan = req.getClan();
ClanPlayer requester = req.getRequester();
String target = req.getTarget();
@Nullable
Clan targetClan = plugin.getClanManager().getClan(target);
Clan targetClan = plugin.getClanManager().getClan(target);
ClanPlayer targetCp = plugin.getClanManager().getAnyClanPlayer(target);
@Nullable
UUID targetPlayer = UUIDMigration.getForcedPlayerUUID(target);
List<String> accepts = req.getAccepts();
List<String> denies = req.getDenies();
switch (req.getType()) {
case START_WAR:
processStartWar(requester, requestClan, targetClan, accepts, denies);
break;
case END_WAR:
processEndWar(requester, requestClan, targetClan, accepts, denies);
break;
case CREATE_ALLY:
processCreateAlly(requester, requestClan, targetClan, accepts, denies);
UUID targetUuid = targetCp != null ? targetCp.getUniqueId() : null;
List<String> accepts = req.getAccepts();
List<String> denies = req.getDenies();
switch (req.getType()) {
case START_WAR:
processStartWar(requester, requestClan, targetClan, accepts, denies);
break;
case BREAK_RIVALRY:
processBreakRivalry(requester, requestClan, targetClan, accepts, denies);
case END_WAR:
processEndWar(requester, requestClan, targetClan, accepts, denies);
break;
case DEMOTE: case PROMOTE:
if (!req.votingFinished() || targetPlayer == null) {
return;
}
target = requestClan.getTag();
if (req.getType() == ClanRequest.DEMOTE) {
processDemote(req, requestClan, targetPlayer, denies);
}
if (req.getType() == ClanRequest.PROMOTE) {
processPromote(req, requestClan, targetPlayer, denies);
}
break;
case DISBAND:
if (!req.votingFinished()) {
return;
}
case CREATE_ALLY:
processCreateAlly(requester, requestClan, targetClan, accepts, denies);
break;
case BREAK_RIVALRY:
processBreakRivalry(requester, requestClan, targetClan, accepts, denies);
break;
case DEMOTE:
case PROMOTE:
if (!req.votingFinished() || targetUuid == null) {
return;
}
target = requestClan.getTag();
if (req.getType() == ClanRequest.DEMOTE) {
processDemote(req, requestClan, targetUuid, denies);
}
if (req.getType() == ClanRequest.PROMOTE) {
processPromote(req, requestClan, targetUuid, denies);
}
break;
case DISBAND:
if (!req.votingFinished()) {
return;
}
processDisband(requester, requestClan, denies);
break;
default:
return;
}
case RENAME:
if (!req.votingFinished()) {
return;
}
processRename(req);
break;
default:
return;
}
requests.remove(target);
SimpleClans.getInstance().getServer().getPluginManager().callEvent(new RequestFinishedEvent(req));
req.cleanVotes();
}
private void processRename(Request request) {
if (request.getDenies().isEmpty()) {
request.getClan().setName(request.getTarget());
} else {
String deniers = String.join(", ", request.getDenies());
request.getClan().leaderAnnounce(RED + lang("rename.refused", deniers));
}
}
private void processDisband(ClanPlayer requester, Clan requestClan, List<String> denies) {
if (denies.isEmpty()) {
if (denies.isEmpty()) {
requestClan.disband(requester.toPlayer(), true, false);
} else {
String deniers = String.join(", ", denies);
requestClan.leaderAnnounce(RED + lang("clan.deletion", deniers));
}
}
} else {
String deniers = String.join(", ", denies);
requestClan.leaderAnnounce(RED + lang("clan.deletion", deniers));
}
}
private void processPromote(Request req, Clan requestClan, UUID targetPlayer, List<String> denies) {
String promotedName = req.getTarget();
if (denies.isEmpty()) {
requestClan.addBb(lang("leaders"), ChatColor.AQUA + lang("promoted.to.leader", promotedName));
requestClan.promote(targetPlayer);
} else {
String deniers = String.join(", ", denies);
requestClan.leaderAnnounce(RED + lang("denied.the.promotion", deniers, promotedName));
}
}
private void processPromote(Request req, Clan requestClan, UUID targetPlayer, List<String> denies) {
String promotedName = req.getTarget();
if (denies.isEmpty()) {
requestClan.addBb(lang("leaders"), lang("promoted.to.leader", promotedName));
requestClan.promote(targetPlayer);
} else {
String deniers = String.join(", ", denies);
requestClan.leaderAnnounce(RED + lang("denied.the.promotion", deniers, promotedName));
}
}
private void processDemote(Request req, Clan requestClan, UUID targetPlayer, List<String> denies) {
private void processDemote(Request req, Clan requestClan, UUID targetPlayer, List<String> denies) {
String demotedName = req.getTarget();
if (denies.isEmpty()) {
requestClan.addBb(lang("leaders"), ChatColor.AQUA
+ lang("demoted.back.to.member", demotedName));
requestClan.addBb(lang("leaders"), lang("demoted.back.to.member", demotedName));
requestClan.demote(targetPlayer);
} else {
String deniers = String.join(", ", denies);
@@ -315,11 +351,11 @@ public final class RequestManager {
if (targetClan != null && requestClan != null) {
if (!accepts.isEmpty()) {
requestClan.removeRival(targetClan);
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("broken.the.rivalry", accepts.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("broken.the.rivalry.with", requester.getName(), targetClan.getName()));
targetClan.addBb(requester.getName(), lang("broken.the.rivalry", accepts.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), lang("broken.the.rivalry.with", requester.getName(), targetClan.getName()));
} else {
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("denied.to.make.peace", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("peace.agreement.denied", targetClan.getName()));
targetClan.addBb(requester.getName(), lang("denied.to.make.peace", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), lang("peace.agreement.denied", targetClan.getName()));
}
}
}
@@ -330,11 +366,11 @@ public final class RequestManager {
if (!accepts.isEmpty()) {
requestClan.addAlly(targetClan);
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("accepted.an.alliance", accepts.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("created.an.alliance", requester.getName(), targetClan.getName()));
targetClan.addBb(requester.getName(), lang("accepted.an.alliance", accepts.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), lang("created.an.alliance", requester.getName(), targetClan.getName()));
} else {
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("denied.an.alliance", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("the.alliance.was.denied", targetClan.getName()));
targetClan.addBb(requester.getName(), lang("denied.an.alliance", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), lang("the.alliance.was.denied", targetClan.getName()));
}
}
}
@@ -348,11 +384,11 @@ public final class RequestManager {
requestClan.removeWarringClan(targetClan);
targetClan.removeWarringClan(requestClan);
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("you.are.no.longer.at.war", accepts.get(0), requestClan.getColorTag()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("you.are.no.longer.at.war", requestClan.getName(), targetClan.getColorTag()));
targetClan.addBb(requester.getName(), lang("you.are.no.longer.at.war", accepts.get(0), requestClan.getColorTag()));
requestClan.addBb(requester.getName(), lang("you.are.no.longer.at.war", requestClan.getName(), targetClan.getColorTag()));
} else {
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("denied.war.end", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("end.war.denied", targetClan.getName()));
targetClan.addBb(requester.getName(), lang("denied.war.end", denies.get(0), requestClan.getName()));
requestClan.addBb(requester.getName(), lang("end.war.denied", targetClan.getName()));
}
}
}
@@ -363,9 +399,9 @@ public final class RequestManager {
if (!accepts.isEmpty()) {
plugin.getProtectionManager().addWar(requester, requestClan, targetClan);
} else {
targetClan.addBb(requester.getName(), ChatColor.AQUA + lang("denied.war.req", denies.get(0),
targetClan.addBb(requester.getName(), lang("denied.war.req", denies.get(0),
requestClan.getName()));
requestClan.addBb(requester.getName(), ChatColor.AQUA + lang("end.war.denied",
requestClan.addBb(requester.getName(), lang("end.war.denied",
targetClan.getName()));
}
}
@@ -406,10 +442,10 @@ public final class RequestManager {
* Starts the task that asks for the votes of all requests
*/
public void askerTask() {
new BukkitRunnable() {
@Override
public void run() {
new BukkitRunnable() {
@Override
public void run() {
for (Iterator<Map.Entry<String, Request>> iter = requests.entrySet().iterator(); iter.hasNext(); ) {
Request req = iter.next().getValue();
@@ -422,9 +458,10 @@ public final class RequestManager {
}
ask(req);
req.incrementAskCount();
}
}}.runTaskTimerAsynchronously(plugin, 0, plugin.getSettingsManager().getSeconds(REQUEST_FREQUENCY));
req.incrementAskCount();
}
}
}.runTaskTimerAsynchronously(plugin, 0, plugin.getSettingsManager().getSeconds(REQUEST_FREQUENCY));
}
/**
@@ -3,16 +3,22 @@ package net.sacredlabyrinth.phaed.simpleclans.managers;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Rank;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCFrame;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.logging.Level;
import java.util.concurrent.ConcurrentHashMap;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static net.sacredlabyrinth.phaed.simpleclans.utils.RankingNumberResolver.RankingType;
@@ -29,6 +35,7 @@ public final class SettingsManager {
private final FileConfiguration config;
private final File configFile;
private final Map<Class<? extends SCFrame>, FileConfiguration> frameConfigs = new ConcurrentHashMap<>();
public SettingsManager(SimpleClans plugin) {
this.plugin = plugin;
@@ -90,10 +97,11 @@ public final class SettingsManager {
if (configFile.exists()) {
try {
config.load(configFile);
} catch (Exception e) {
e.printStackTrace();
} catch (IOException | InvalidConfigurationException ex) {
SimpleClans.getInstance().getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
frameConfigs.clear();
save();
}
@@ -101,8 +109,8 @@ public final class SettingsManager {
public void save() {
try {
config.save(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (IOException ex) {
SimpleClans.getInstance().getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@@ -116,7 +124,7 @@ public final class SettingsManager {
" that matches their clan tag.");
}
if (discordSrv == null && is (DISCORDCHAT_ENABLE)) {
if (discordSrv == null && is(DISCORDCHAT_ENABLE)) {
plugin.getLogger().warning("DiscordChat can't be initialized, please, install DiscordSRV.");
}
}
@@ -132,6 +140,30 @@ public final class SettingsManager {
return new Locale(language);
}
public FileConfiguration getConfig(Class<? extends SCFrame> clazz) {
return frameConfigs.computeIfAbsent(clazz, this::readConfig);
}
private FileConfiguration readConfig(Class<? extends SCFrame> clazz) {
String configPath = clazz.getName().replace("net.sacredlabyrinth.phaed.simpleclans.ui.", "")
.replace(".", File.separator) + ".yml";
File externalFile = new File(plugin.getDataFolder(), configPath);
InputStream resource = plugin.getResource(configPath);
YamlConfiguration config = YamlConfiguration.loadConfiguration(externalFile);
if (resource != null) {
YamlConfiguration defaults = YamlConfiguration.loadConfiguration(new InputStreamReader(resource));
config.setDefaults(defaults);
if (!externalFile.exists()) {
try {
defaults.save(externalFile);
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, String.format("Error saving defaults to %s", configPath), e);
}
}
}
return config;
}
public List<Material> getItemList() {
List<Material> itemsList = new ArrayList<>();
for (String material : getStringList(ITEM_LIST)) {
@@ -149,7 +181,7 @@ public final class SettingsManager {
* Check whether a word is disallowed
*
* @param word the world
* @return whether its a disallowed word
* @return whether its disallowed word
*/
public boolean isDisallowedWord(String word) {
for (String disallowedTag : getStringList(DISALLOWED_TAGS)) {
@@ -169,13 +201,8 @@ public final class SettingsManager {
* @return whether the string contains the color code
*/
public boolean hasDisallowedColor(String str) {
for (String disallowedTag : getStringList(DISALLOWED_TAG_COLORS)) {
if (str.contains("&" + disallowedTag)) {
return true;
}
}
return false;
String loweredString = str.toLowerCase();
return getStringList(DISALLOWED_TAG_COLORS).stream().map(String::toLowerCase).anyMatch(color -> loweredString.contains("&" + color));
}
/**
@@ -252,13 +279,16 @@ public final class SettingsManager {
}
}
@SuppressWarnings("unchecked")
public @NotNull Collection<Rank> getStarterRanks() {
List<Rank> ranks = new ArrayList<>();
ConfigurationSection section = config.getConfigurationSection("clan.starter-ranks");
if (section != null) {
for (String name : section.getKeys(false)) {
String displayName = section.getString(name + ".display-name");
List<String> permissions = section.getStringList(name + ".permissions");
List<Map<?, ?>> mapList = config.getMapList("clan.starter-ranks");
for (Map<?, ?> rankMap : mapList) {
Set<String> names = (Set<String>) rankMap.keySet();
for (String name : names) {
Map<String, Object> rank = (Map<String, Object>) rankMap.get(name);
String displayName = (String) rank.get("display-name");
List<String> permissions = (List<String>) rank.get("permissions");
ranks.add(new Rank(name, displayName, new HashSet<>(permissions)));
}
}
@@ -305,13 +335,16 @@ public final class SettingsManager {
ALLOW_RESET_KDR("settings.allow-reset-kdr", false),
REJOIN_COOLDOWN("settings.rejoin-cooldown", 60),
ENABLE_REJOIN_COOLDOWN("settings.rejoin-cooldown-enabled", false),
ACCEPT_OTHER_ALPHABETS_LETTERS("settings.accept-other-alphabets-letters-on-tag", false),
RANKING_TYPE("settings.ranking-type", "DENSE"),
LIST_DEFAULT_ORDER_BY("settings.list-default-order-by", "kdr"),
LORE_LENGTH("settings.lore-length", 36),
PVP_ONLY_WHILE_IN_WAR("settings.pvp-only-while-at-war", false),
PAST_CLANS_LIMIT("settings.past-clans-limit", 10),
USERNAME_REGEX("settings.username-regex", "^\\**[a-zA-Z0-9_$]{1,16}$"),
TAG_REGEX("settings.tag-regex", ""),
ACCEPT_OTHER_ALPHABETS_LETTERS("settings.accept-other-alphabets-letters-on-tag", false),
DATE_TIME_PATTERN("settings.date-time-pattern", "HH:mm - dd/MM/yyyy"),
BUNGEE_SERVERS("settings.bungee-servers"),
/*
================
> Tag Settings
@@ -319,12 +352,12 @@ public final class SettingsManager {
*
*/
TAG_DEFAULT_COLOR("tag.default-color", "8"),
TAG_MAX_LENGTH("tag.max-length", 5),
TAG_BRACKET_COLOR("tag.bracket.color", "8"),
TAG_BRACKET_LEADER_COLOR("tag.bracket.leader-color", "4"),
TAG_BRACKET_LEFT("tag.bracket.left", ""),
TAG_BRACKET_RIGHT("tag.bracket.right", ""),
TAG_MAX_LENGTH("tag.max-length", 5),
TAG_MIN_LENGTH("tag.min-length", 2),
TAG_BRACKET_RIGHT("tag.bracket.right", ""),
TAG_SEPARATOR_COLOR("tag.separator.color", "8"),
TAG_SEPARATOR_LEADER_COLOR("tag.separator.leader-color", "4"),
TAG_SEPARATOR_CHAR("tag.separator.char", " ."),
@@ -398,8 +431,8 @@ public final class SettingsManager {
ECONOMY_PURCHASE_HOME_TELEPORT_SET("economy.purchase-home-teleport-set", false),
ECONOMY_REGROUP_PRICE("economy.home-regroup-price", 5.0),
ECONOMY_PURCHASE_HOME_REGROUP("economy.purchase-home-regroup", false),
ECONOMY_PURCHASE_DISCORD_CREATE("purchase-discord-create", false),
ECONOMY_DISCORD_CREATION_PRICE("discord-creation-price", 1000.0),
ECONOMY_PURCHASE_DISCORD_CREATE("economy.purchase-discord-create", false),
ECONOMY_DISCORD_CREATION_PRICE("economy.discord-creation-price", 1000.0),
ECONOMY_UNIQUE_TAX_ON_REGROUP("economy.unique-tax-on-regroup", true),
ECONOMY_ISSUER_PAYS_REGROUP("economy.issuer-pays-regroup", true),
ECONOMY_MONEY_PER_KILL("economy.money-per-kill", false),
@@ -442,6 +475,7 @@ public final class SettingsManager {
CLAN_MAX_DESCRIPTION_LENGTH("clan.max-description-length", 120),
CLAN_MIN_DESCRIPTION_LENGTH("clan.min-description-length", 10),
CLAN_MAX_MEMBERS("clan.max-members", 25),
CLAN_UNVERIFIED_MAX_MEMBERS("clan.unverified-max-members", 10),
CLAN_MAX_ALLIANCES("clan.max-alliances", -1),
CLAN_CONFIRMATION_FOR_PROMOTE("clan.confirmation-for-promote", false),
CLAN_TRUST_MEMBERS_BY_DEFAULT("clan.trust-members-by-default", false),
@@ -449,6 +483,7 @@ public final class SettingsManager {
CLAN_PERCENTAGE_ONLINE_TO_DEMOTE("clan.percentage-online-to-demote", 100.0),
CLAN_FF_ON_BY_DEFAULT("clan.ff-on-by-default", false),
CLAN_MIN_TO_VERIFY("clan.min-to-verify", 1),
CLAN_DEFAULT_RANK("clan.default-rank", "recruit"),
/*
================
> Tasks Settings
@@ -512,8 +547,7 @@ public final class SettingsManager {
> BB Settings
================
*/
BB_COLOR("bb.color", "e"),
BB_ACCENT_COLOR("bb.accent-color", "8"),
BB_PREFIX("bb.prefix", "&8* &e"),
BB_SHOW_ON_LOGIN("bb.show-on-login", true),
BB_SIZE("bb.size", 6),
BB_LOGIN_SIZE("bb.login-size", 6),
@@ -574,6 +608,7 @@ public final class SettingsManager {
MYSQL_ENABLE("mysql.enable", false),
MYSQL_PASSWORD("mysql.password", ""),
MYSQL_DATABASE("mysql.database", ""),
MYSQL_TABLE_PREFIX("mysql.table_prefix", "sc_"),
/*
================
> Permissions Settings
@@ -1,6 +1,5 @@
package net.sacredlabyrinth.phaed.simpleclans.managers;
import com.google.common.base.Charsets;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankLogger;
@@ -11,7 +10,6 @@ import net.sacredlabyrinth.phaed.simpleclans.storage.SQLiteCore;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.YAMLSerializer;
import net.sacredlabyrinth.phaed.simpleclans.uuid.UUIDFetcher;
import net.sacredlabyrinth.phaed.simpleclans.uuid.UUIDMigration;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -20,11 +18,17 @@ import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
@@ -57,7 +61,7 @@ public final class StorageManager {
* @return the ChatBlock
*/
public ChatBlock getChatBlock(Player player) {
return chatBlocks.get(player.getUniqueId().toString());
return chatBlocks.get(player.getName());
}
/**
@@ -65,13 +69,7 @@ public final class StorageManager {
*
*/
public void addChatBlock(CommandSender player, ChatBlock cb) {
UUID uuid = UUIDMigration.getForcedPlayerUUID(player.getName());
if (uuid == null) {
return;
}
chatBlocks.put(uuid.toString(), cb);
chatBlocks.put(player.getName(), cb);
}
/**
@@ -85,10 +83,10 @@ public final class StorageManager {
if (core.checkConnection()) {
plugin.getLogger().info(lang("mysql.connection.successful"));
if (!core.existsTable("sc_clans")) {
plugin.getLogger().info("Creating table: sc_clans");
if (!core.existsTable(getPrefixedTable("clans"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("clans"));
String query = "CREATE TABLE IF NOT EXISTS `sc_clans` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("clans") + "` ("
+ " `id` bigint(20) NOT NULL auto_increment,"
+ " `verified` tinyint(1) default '0',"
+ " `tag` varchar(25) NOT NULL,"
@@ -113,10 +111,10 @@ public final class StorageManager {
core.execute(query);
}
if (!core.existsTable("sc_players")) {
plugin.getLogger().info("Creating table: sc_players");
if (!core.existsTable(getPrefixedTable("players"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("players"));
String query = "CREATE TABLE IF NOT EXISTS `sc_players` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("players") + "` ("
+ " `id` bigint(20) NOT NULL auto_increment,"
+ " `name` varchar(16) NOT NULL,"
+ " `leader` tinyint(1) default '0',"
@@ -139,16 +137,17 @@ public final class StorageManager {
core.execute(query);
}
if (!core.existsTable("sc_kills")) {
plugin.getLogger().info("Creating table: sc_kills");
if (!core.existsTable(getPrefixedTable("kills"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("kills"));
String query = "CREATE TABLE IF NOT EXISTS `sc_kills` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("kills") + "` ("
+ " `kill_id` bigint(20) NOT NULL auto_increment,"
+ " `attacker` varchar(16) NOT NULL,"
+ " `attacker_tag` varchar(16) NOT NULL,"
+ " `victim` varchar(16) NOT NULL,"
+ " `victim_tag` varchar(16) NOT NULL,"
+ " `kill_type` varchar(1) NOT NULL,"
+ " `created_at` datetime NULL,"
+ " PRIMARY KEY (`kill_id`));";
core.execute(query);
}
@@ -162,10 +161,10 @@ public final class StorageManager {
plugin.getLogger().info(lang("sqlite.connection.successful"));
if (!core.existsTable("sc_clans")) {
plugin.getLogger().info("Creating table: sc_clans");
if (!core.existsTable(getPrefixedTable("clans"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("clans"));
String query = "CREATE TABLE IF NOT EXISTS `sc_clans` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("clans") + "` ("
+ " `id` bigint(20),"
+ " `verified` tinyint(1) default '0',"
+ " `tag` varchar(25) NOT NULL,"
@@ -190,10 +189,10 @@ public final class StorageManager {
core.execute(query);
}
if (!core.existsTable("sc_players")) {
plugin.getLogger().info("Creating table: sc_players");
if (!core.existsTable(getPrefixedTable("players"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("players"));
String query = "CREATE TABLE IF NOT EXISTS `sc_players` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("players") + "` ("
+ " `id` bigint(20),"
+ " `name` varchar(16) NOT NULL,"
+ " `leader` tinyint(1) default '0',"
@@ -216,16 +215,17 @@ public final class StorageManager {
core.execute(query);
}
if (!core.existsTable("sc_kills")) {
plugin.getLogger().info("Creating table: sc_kills");
if (!core.existsTable(getPrefixedTable("kills"))) {
plugin.getLogger().info("Creating table: " + getPrefixedTable("kills"));
String query = "CREATE TABLE IF NOT EXISTS `sc_kills` ("
String query = "CREATE TABLE IF NOT EXISTS `" + getPrefixedTable("kills") + "` ("
+ " `kill_id` bigint(20),"
+ " `attacker` varchar(16) NOT NULL,"
+ " `attacker_tag` varchar(16) NOT NULL,"
+ " `victim` varchar(16) NOT NULL,"
+ " `victim_tag` varchar(16) NOT NULL,"
+ " `kill_type` varchar(1) NOT NULL,"
+ " `created_at` datetime NULL,"
+ " PRIMARY KEY (`kill_id`));";
core.execute(query);
}
@@ -325,6 +325,9 @@ public final class StorageManager {
for (Clan clan : purge) {
plugin.getLogger().info(lang("purging.clan", clan.getName()));
for (ClanPlayer member : clan.getMembers()) {
clan.removePlayerFromClan(member.getUniqueId());
}
deleteClan(clan);
clans.remove(clan);
}
@@ -361,7 +364,7 @@ public final class StorageManager {
public List<Clan> retrieveClans() {
List<Clan> out = new ArrayList<>();
String query = "SELECT * FROM `sc_clans`;";
String query = "SELECT * FROM `" + getPrefixedTable("clans") + "`;";
ResultSet res = core.select(query);
if (res != null) {
@@ -435,7 +438,7 @@ public final class StorageManager {
public @Nullable Clan retrieveOneClan(String tagClan) {
Clan out = null;
String query = "SELECT * FROM `sc_clans` WHERE `tag` = '" + tagClan + "';";
String query = "SELECT * FROM `" + getPrefixedTable("clans") + "` WHERE `tag` = '" + tagClan + "';";
ResultSet res = core.select(query);
if (res != null) {
@@ -509,7 +512,7 @@ public final class StorageManager {
public List<ClanPlayer> retrieveClanPlayers() {
List<ClanPlayer> out = new ArrayList<>();
String query = "SELECT * FROM `sc_players`;";
String query = "SELECT * FROM `" + getPrefixedTable("players") + "`;";
ResultSet res = core.select(query);
if (res != null) {
@@ -536,7 +539,7 @@ public final class StorageManager {
if (last_seen == 0) {
last_seen = (new Date()).getTime();
}
}
ClanPlayer cp = new ClanPlayer();
if (uuid != null) {
@@ -587,7 +590,7 @@ public final class StorageManager {
public @Nullable ClanPlayer retrieveOneClanPlayer(UUID playerUniqueId) {
ClanPlayer out = null;
String query = "SELECT * FROM `sc_players` WHERE `uuid` = '" + playerUniqueId.toString() + "';";
String query = "SELECT * FROM `" + getPrefixedTable("players") + "` WHERE `uuid` = '" + playerUniqueId.toString() + "';";
ResultSet res = core.select(query);
if (res != null) {
@@ -684,7 +687,7 @@ public final class StorageManager {
public void insertClan(Clan clan) {
plugin.getProxyManager().sendUpdate(clan);
String query = "INSERT INTO `sc_clans` (`banner`, `ranks`, `description`, `fee_enabled`, `fee_value`, `verified`, `tag`," +
String query = "INSERT INTO `" + getPrefixedTable("clans") + "` (`banner`, `ranks`, `description`, `fee_enabled`, `fee_value`, `verified`, `tag`," +
" `color_tag`, `name`, `friendly_fire`, `founded`, `last_used`, `packed_allies`, `packed_rivals`, " +
"`packed_bb`, `cape_url`, `flags`, `balance`) ";
String values = "VALUES ( '"
@@ -743,7 +746,7 @@ public final class StorageManager {
* @param cp to update
*/
public void updatePlayerName(final @NotNull ClanPlayer cp) {
String query = "UPDATE `sc_players` SET `name` = '" + cp.getName() + "' WHERE uuid = '" + cp.getUniqueId() + "';";
String query = "UPDATE `" + getPrefixedTable("players") + "` SET `name` = '" + cp.getName() + "' WHERE uuid = '" + cp.getUniqueId() + "';";
core.executeUpdate(query);
}
@@ -780,7 +783,7 @@ public final class StorageManager {
}
private PreparedStatement prepareUpdateClanStatement(Connection connection) throws SQLException {
String sql = "UPDATE `sc_clans` SET ranks = ?, banner = ?, description = ?, fee_enabled = ?, fee_value = ?, " +
String sql = "UPDATE `" + getPrefixedTable("clans") + "` SET ranks = ?, banner = ?, description = ?, fee_enabled = ?, fee_value = ?, " +
"verified = ?, tag = ?, color_tag = ?, `name` = ?, friendly_fire = ?, founded = ?, last_used = ?, " +
"packed_allies = ?, packed_rivals = ?, packed_bb = ?, balance = ?, flags = ? WHERE tag = ?;";
return connection.prepareStatement(sql);
@@ -812,7 +815,7 @@ public final class StorageManager {
*/
public void deleteClan(Clan clan) {
plugin.getProxyManager().sendDelete(clan);
String query = "DELETE FROM `sc_clans` WHERE tag = '" + clan.getTag() + "';";
String query = "DELETE FROM `" + getPrefixedTable("clans") + "` WHERE tag = '" + clan.getTag() + "';";
core.executeUpdate(query);
}
@@ -823,7 +826,7 @@ public final class StorageManager {
public void insertClanPlayer(ClanPlayer cp) {
plugin.getProxyManager().sendUpdate(cp);
String query = "INSERT INTO `sc_players` (`uuid`, `name`, `leader`, `tag`, `friendly_fire`, `neutral_kills`, " +
String query = "INSERT INTO `" + getPrefixedTable("players") + "` (`uuid`, `name`, `leader`, `tag`, `friendly_fire`, `neutral_kills`, " +
"`rival_kills`, `civilian_kills`, `deaths`, `last_seen`, `join_date`, `packed_past_clans`, `flags`) ";
String values = "VALUES ('" + cp.getUniqueId().toString() + "', '" + cp.getName() + "',"
+ (cp.isLeader() ? 1 : 0) + ",'" + Helper.escapeQuotes(cp.getTag()) + "',"
@@ -868,7 +871,7 @@ public final class StorageManager {
}
private PreparedStatement prepareUpdateClanPlayerStatement(Connection connection) throws SQLException {
String sql = "UPDATE `sc_players` SET locale = ?, resign_times = ?, leader = ?, tag = ?, friendly_fire = ?," +
String sql = "UPDATE `" + getPrefixedTable("players") + "` SET locale = ?, resign_times = ?, leader = ?, tag = ?, friendly_fire = ?," +
" neutral_kills = ?, ally_kills = ?, rival_kills = ?, civilian_kills = ?, deaths = ?, last_seen = ?," +
" packed_past_clans = ?, trusted = ?, flags = ?, `name` = ? WHERE `uuid` = ?;";
return connection.prepareStatement(sql);
@@ -899,11 +902,11 @@ public final class StorageManager {
public void deleteClanPlayer(ClanPlayer cp) {
final Clan clan = cp.getClan();
if (clan != null) {
clan.addBbWithoutSaving(ChatColor.AQUA + MessageFormat.format(lang("has.been.purged"), cp.getName()));
clan.addBbWithoutSaving(MessageFormat.format(lang("has.been.purged"), cp.getName()));
updateClan(clan, false);
}
plugin.getProxyManager().sendDelete(cp);
String query = "DELETE FROM `sc_players` WHERE uuid = '" + cp.getUniqueId() + "';";
String query = "DELETE FROM `" + getPrefixedTable("players") + "` WHERE uuid = '" + cp.getUniqueId() + "';";
core.executeUpdate(query);
deleteKills(cp.getUniqueId());
}
@@ -914,7 +917,7 @@ public final class StorageManager {
*/
@Deprecated
public void insertKill(Player attacker, String attackerTag, Player victim, String victimTag, String type) {
String query = "INSERT INTO `sc_kills` ( `attacker_uuid`, `attacker`, `attacker_tag`, `victim_uuid`, `victim`, `victim_tag`, `kill_type`) ";
String query = "INSERT INTO `" + getPrefixedTable("kills") + "` ( `attacker_uuid`, `attacker`, `attacker_tag`, `victim_uuid`, `victim`, `victim_tag`, `kill_type`) ";
String values = "VALUES ( '" + attacker.getUniqueId() + "','" + attacker.getName() + "','" + attackerTag + "','" + victim.getUniqueId() + "','" + victim.getName() + "','" + victimTag + "','" + type + "');";
core.executeUpdate(query + values);
}
@@ -926,11 +929,11 @@ public final class StorageManager {
* @param victim the victim
* @param type the kill type
*/
public void insertKill(@NotNull ClanPlayer attacker, @NotNull ClanPlayer victim, @NotNull String type) {
public void insertKill(@NotNull ClanPlayer attacker, @NotNull ClanPlayer victim, @NotNull String type, @NotNull LocalDateTime time) {
String query = "INSERT INTO `sc_kills` ( `attacker_uuid`, `attacker`, `attacker_tag`, `victim_uuid`, " +
"`victim`, `victim_tag`, `kill_type`) ";
"`victim`, `victim_tag`, `kill_type`, `created_at`) ";
String values = "VALUES ( '" + attacker.getUniqueId() + "','" + attacker.getName() + "','" + attacker.getTag()
+ "','" + victim.getUniqueId() + "','" + victim.getName() + "','" + victim.getTag() + "','" + type + "');";
+ "','" + victim.getUniqueId() + "','" + victim.getName() + "','" + victim.getTag() + "','" + type + "','" + time + "');";
core.executeUpdate(query + values);
}
@@ -940,7 +943,7 @@ public final class StorageManager {
*/
@Deprecated
public void deleteKills(String playerName) {
String query = "DELETE FROM `sc_kills` WHERE `attacker` = '" + playerName + "'";
String query = "DELETE FROM `" + getPrefixedTable("kills") + "` WHERE `attacker` = '" + playerName + "'";
core.executeUpdate(query);
}
@@ -949,7 +952,7 @@ public final class StorageManager {
*
*/
public void deleteKills(UUID playerUniqueId) {
String query = "DELETE FROM `sc_kills` WHERE `attacker_uuid` = '" + playerUniqueId + "'";
String query = "DELETE FROM `" + getPrefixedTable("kills") + "` WHERE `attacker_uuid` = '" + playerUniqueId + "'";
core.executeUpdate(query);
}
@@ -964,7 +967,7 @@ public final class StorageManager {
public Map<String, Integer> getKillsPerPlayer(String playerName) {
HashMap<String, Integer> out = new HashMap<>();
String query = "SELECT victim, count(victim) AS kills FROM `sc_kills` WHERE attacker = '" + playerName + "' GROUP BY victim ORDER BY count(victim) DESC;";
String query = "SELECT victim, count(victim) AS kills FROM `" + getPrefixedTable("kills") + "` WHERE attacker = '" + playerName + "' GROUP BY victim ORDER BY count(victim) DESC;";
ResultSet res = core.select(query);
if (res != null) {
@@ -997,7 +1000,7 @@ public final class StorageManager {
public Map<String, Integer> getMostKilled() {
HashMap<String, Integer> out = new HashMap<>();
String query = "SELECT attacker, victim, count(victim) AS kills FROM `sc_kills` GROUP BY attacker, victim ORDER BY 3 DESC;";
String query = "SELECT attacker, victim, count(victim) AS kills FROM `" + getPrefixedTable("kills") + "` GROUP BY attacker, victim ORDER BY 3 DESC;";
ResultSet res = core.select(query);
if (res != null) {
@@ -1075,98 +1078,104 @@ public final class StorageManager {
/*
* From 2.2.6.3 to 2.3
*/
if (!core.existsColumn("sc_clans", "balance")) {
query = "ALTER TABLE sc_clans ADD COLUMN `balance` double(64,2);";
if (!core.existsColumn(getPrefixedTable("clans"), "balance")) {
query = "ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `balance` double(64,2);";
core.execute(query);
}
/*
* From 2.7.16 to 2.7.17
*/
if (!core.existsColumn("sc_clans", "fee_enabled")) {
query = "ALTER TABLE sc_clans ADD COLUMN `fee_enabled` tinyint(1) default '0';";
if (!core.existsColumn(getPrefixedTable("clans"), "fee_enabled")) {
query = "ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `fee_enabled` tinyint(1) default '0';";
core.execute(query);
}
if (!core.existsColumn("sc_clans", "fee_value")) {
query = "ALTER TABLE sc_clans ADD COLUMN `fee_value` double(64,2);";
if (!core.existsColumn(getPrefixedTable("clans"), "fee_value")) {
query = "ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `fee_value` double(64,2);";
core.execute(query);
}
/*
* From 2.7.21 to 2.7.22
*/
if (!core.existsColumn("sc_clans", "description")) {
query = "ALTER TABLE sc_clans ADD COLUMN `description` varchar(255);";
if (!core.existsColumn(getPrefixedTable("clans"), "description")) {
query = "ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `description` varchar(255);";
core.execute(query);
}
/*
* From 2.7.22 to 2.7.23
*/
if (!core.existsColumn("sc_players", "resign_times")) {
query = "ALTER TABLE sc_players ADD COLUMN `resign_times` text;";
if (!core.existsColumn(getPrefixedTable("players"), "resign_times")) {
query = "ALTER TABLE `" + getPrefixedTable("players") + "` ADD COLUMN `resign_times` text;";
core.execute(query);
}
/*
* From 2.8.2 to 2.9
*/
if (!core.existsColumn("sc_clans", "ranks")) {
query = "ALTER TABLE sc_clans ADD COLUMN `ranks` text;";
if (!core.existsColumn(getPrefixedTable("clans"), "ranks")) {
query = "ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `ranks` text;";
core.execute(query);
}
// From 2.12.1 to 2.13.0
if (!core.existsColumn("sc_players", "locale")) {
query = "ALTER TABLE sc_players ADD COLUMN `locale` varchar(10);";
if (!core.existsColumn(getPrefixedTable("players"), "locale")) {
query = "ALTER TABLE `" + getPrefixedTable("players") + "` ADD COLUMN `locale` varchar(10);";
core.execute(query);
}
if (!core.existsColumn("sc_clans", "banner")) {
core.execute("ALTER TABLE sc_clans ADD COLUMN `banner` text;");
if (!core.existsColumn(getPrefixedTable("clans"), "banner")) {
core.execute("ALTER TABLE `" + getPrefixedTable("clans") + "` ADD COLUMN `banner` text;");
}
// From 2.15.1 to 2.15.2
if (!core.existsColumn("sc_players", "ally_kills")) {
core.execute("ALTER TABLE sc_players ADD COLUMN `ally_kills` int(11) DEFAULT NULL;");
if (!core.existsColumn(getPrefixedTable("players"), "ally_kills")) {
core.execute("ALTER TABLE `" + getPrefixedTable("players") + "` ADD COLUMN `ally_kills` int(11) DEFAULT NULL;");
}
if (plugin.getSettingsManager().is(MYSQL_ENABLE)) {
core.execute("ALTER TABLE sc_clans MODIFY color_tag VARCHAR(255);");
core.execute("ALTER TABLE `" + getPrefixedTable("clans") + "` MODIFY color_tag VARCHAR(255);");
}
/*
* Bukkit 1.7.5+ UUID Migration
*/
if (!core.existsColumn("sc_kills", "attacker_uuid")) {
query = "ALTER TABLE sc_kills ADD attacker_uuid VARCHAR( 255 ) DEFAULT NULL;";
if (!core.existsColumn(getPrefixedTable("kills"), "attacker_uuid")) {
query = "ALTER TABLE `" + getPrefixedTable("kills") + "` ADD attacker_uuid VARCHAR( 255 ) DEFAULT NULL;";
core.execute(query);
}
if (!core.existsColumn("sc_kills", "victim_uuid")) {
query = "ALTER TABLE sc_kills ADD victim_uuid VARCHAR( 255 ) DEFAULT NULL;";
if (!core.existsColumn(getPrefixedTable("kills"), "victim_uuid")) {
query = "ALTER TABLE `" + getPrefixedTable("kills") + "` ADD victim_uuid VARCHAR( 255 ) DEFAULT NULL;";
core.execute(query);
}
boolean useMysql = plugin.getSettingsManager().is(MYSQL_ENABLE);
if (!core.existsColumn("sc_players", "uuid")) {
query = "ALTER TABLE sc_players ADD uuid VARCHAR( 255 ) DEFAULT NULL;";
if (!core.existsColumn(getPrefixedTable("players"), "uuid")) {
query = "ALTER TABLE `" + getPrefixedTable("players") + "` ADD uuid VARCHAR( 255 ) DEFAULT NULL;";
core.execute(query);
if (useMysql) {
query = "ALTER TABLE `sc_players` ADD UNIQUE `uq_player_uuid` (`uuid`);";
query = "ALTER TABLE `" + getPrefixedTable("players") + "` ADD UNIQUE `uq_player_uuid` (`uuid`);";
core.execute(query);
}
updatePlayersToUUID();
if (useMysql) {
query = "ALTER TABLE sc_players DROP INDEX uq_sc_players_1;";
query = "ALTER TABLE `" + getPrefixedTable("players") + "` DROP INDEX uq_sc_players_1;";
} else {
query = "DROP INDEX IF EXISTS uq_sc_players_1;";
}
core.execute(query);
}
if (core.existsColumn("sc_players", "uuid") && !useMysql) {
query = "CREATE UNIQUE INDEX IF NOT EXISTS `uq_player_uuid` ON `sc_players` (`uuid`);";
if (core.existsColumn(getPrefixedTable("players"), "uuid") && !useMysql) {
query = "CREATE UNIQUE INDEX IF NOT EXISTS `uq_player_uuid` ON `" + getPrefixedTable("players") + "` (`uuid`);";
core.execute(query);
}
// From 2.19.3 to 2.20.0
if (!core.existsColumn(getPrefixedTable("kills"), "created_at")) {
query = "ALTER TABLE sc_kills ADD `created_at` datetime NULL;";
core.execute(query);
}
}
@@ -1175,55 +1184,94 @@ public final class StorageManager {
* Updates the database to the latest version
*
*/
private void updatePlayersToUUID() {
plugin.getLogger().log(Level.WARNING, "Starting Migration to UUID Players !");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DONT STOP BUKKIT ! ==================== ");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DONT STOP BUKKIT ! ==================== ");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DONT STOP BUKKIT ! ==================== ");
SimpleClans.getInstance().setUUID(false);
logMigrationStart();
List<ClanPlayer> cps = retrieveClanPlayers();
Map<String, UUID> uuidMap = fetchUUIDs(cps);
int i = 1;
for (ClanPlayer cp : cps) {
int totalPlayers = cps.size();
for (int i = 0; i < totalPlayers; i++) {
ClanPlayer cp = cps.get(i);
try {
UUID uuidPlayer;
if (SimpleClans.getInstance().getServer().getOnlineMode()) {
uuidPlayer = UUIDFetcher.getUUIDOfThrottled(cp.getName());
} else {
uuidPlayer = UUID.nameUUIDFromBytes(("OfflinePlayer:" + cp.getName()).getBytes(Charsets.UTF_8));
UUID uuid = uuidMap.get(cp.getName());
if (uuid != null) {
updatePlayerInDatabase(cp.getName(), uuid);
logSuccess(i + 1, totalPlayers, cp.getName(), uuid);
}
String query = "UPDATE `sc_players` SET uuid = '" + uuidPlayer.toString() + "' WHERE name = '" + cp.getName() + "';";
core.executeUpdate(query);
String query2 = "UPDATE `sc_kills` SET attacker_uuid = '" + uuidPlayer + "' WHERE attacker = '" + cp.getName() + "';";
core.executeUpdate(query2);
String query3 = "UPDATE `sc_kills` SET victim_uuid = '" + uuidPlayer + "' WHERE victim = '" + cp.getName() + "';";
core.executeUpdate(query3);
plugin.getLogger().info("[" + i + " / " + cps.size() + "] Success: " + cp.getName() + "; UUID: " + uuidPlayer.toString());
} catch (Exception ex) {
plugin.getLogger().log(Level.WARNING, "[" + i + " / " + cps.size() + "] Failed [ERRO]: " + cp.getName() + "; UUID: ???");
logFailure(i + 1, totalPlayers, cp.getName(), ex);
}
i++;
}
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
if (!cps.isEmpty()) {
plugin.getLogger().info(MessageFormat.format(lang("clan.players"), cps.size()));
}
SimpleClans.getInstance().setUUID(true);
logMigrationEnd(totalPlayers);
}
private void updatePlayerInDatabase(String playerName, UUID uuid) {
String[] tables = {"players", "kills", "kills"};
String[] columns = {"uuid", "attacker_uuid", "victim_uuid"};
String[] conditions = {"name", "attacker", "victim"};
for (int i = 0; i < tables.length; i++) {
String query = String.format("UPDATE `%s` SET %s = '%s' WHERE %s = '%s';",
getPrefixedTable(tables[i]), columns[i], uuid.toString(), conditions[i], playerName);
core.executeUpdate(query);
}
}
private Map<String, UUID> fetchUUIDs(List<ClanPlayer> clanPlayers) {
Map<String, UUID> uuidMap = new HashMap<>();
try {
if (SimpleClans.getInstance().getServer().getOnlineMode()) {
uuidMap = UUIDFetcher.fetchUUIDsForClanPlayers(clanPlayers);
} else {
uuidMap = clanPlayers.stream().collect(Collectors.toMap(ClanPlayer::getName, player ->
UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(StandardCharsets.UTF_8))));
}
} catch (InterruptedException | ExecutionException ex) {
plugin.getLogger().log(Level.SEVERE, "Error fetching UUIDs in bulk: " + ex.getMessage(), ex);
}
return uuidMap;
}
private void logSuccess(int current, int total, String playerName, UUID uuid) {
plugin.getLogger().info(String.format("[%d / %d] Success: %s; UUID: %s", current, total, playerName, uuid));
}
private void logFailure(int current, int total, String playerName, Exception ex) {
plugin.getLogger().log(Level.WARNING, String.format("[%d / %d] Failed [ERROR]: %s; UUID: ???", current, total, playerName), ex);
}
private void logMigrationStart() {
plugin.getLogger().log(Level.WARNING, "Starting Migration to UUID Players!");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DON'T STOP BUKKIT! ====================");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DON'T STOP BUKKIT! ====================");
plugin.getLogger().log(Level.WARNING, "==================== ATTENTION DON'T STOP BUKKIT! ====================");
}
private void logMigrationEnd(int totalPlayers) {
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
plugin.getLogger().log(Level.WARNING, "==================== END OF MIGRATION ====================");
if (totalPlayers > 0) {
plugin.getLogger().info(MessageFormat.format(lang("clan.players"), totalPlayers));
}
}
private String getPrefixedTable(String name) {
return plugin.getSettingsManager().getString(MYSQL_TABLE_PREFIX) + name;
}
/**
* Saves modified Clans and ClanPlayers to the database
*
* @author RoinujNosde
* @since 2.10.2
* @since 2.10.2
*
* <p>
* author: RoinujNosde
* </p>
*/
public void saveModified() {
try (PreparedStatement pst = prepareUpdateClanPlayerStatement(core.getConnection())) {
@@ -14,7 +14,6 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.jetbrains.annotations.NotNull;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -0,0 +1,29 @@
package net.sacredlabyrinth.phaed.simpleclans.migrations;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
/**
* Class responsible to migrate from old bb format to new one.
* <p>
* `bb.accent-color` and `bb.color` replaced to `bb.prefix`.
* </p>
*
* @since 2.19.0
*/
public class BbMigration extends ConfigMigration {
public BbMigration(SettingsManager settingsManager) {
super(settingsManager);
}
@Override
public void migrate() {
if (config.contains("bb.accent-color")) {
config.set("bb.accent-color", null);
}
if (config.contains("bb.color")) {
config.set("bb.color", null);
}
}
}
@@ -0,0 +1,98 @@
package net.sacredlabyrinth.phaed.simpleclans.migrations;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
/**
* @author RoinujNosde
*/
public class ChatFormatMigration extends ConfigMigration {
public ChatFormatMigration(SettingsManager settingsManager) {
super(settingsManager);
}
public void migrateClanChat() {
if (config.getString("clanchat.name-color") == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append('&');
sb.append(settings.getColored(CLANCHAT_BRACKET_COLOR));
sb.append(settings.getString(CLANCHAT_BRACKET_LEFT));
sb.append("%clan%");
sb.append("&");
sb.append(settings.getColored(CLANCHAT_BRACKET_COLOR));
sb.append(settings.getString(CLANCHAT_BRACKET_RIGHT));
sb.append(" ");
sb.append('&');
sb.append(settings.getColored(CLANCHAT_NAME_COLOR));
sb.append(settings.getString(CLANCHAT_PLAYER_BRACKET_LEFT));
sb.append("%nick-color%");
sb.append("%player%");
sb.append('&');
sb.append(settings.getColored(CLANCHAT_NAME_COLOR));
sb.append(settings.getString(CLANCHAT_PLAYER_BRACKET_RIGHT));
sb.append(" %rank%: ");
sb.append('&');
sb.append(settings.getColored(CLANCHAT_MESSAGE_COLOR));
sb.append("%message%");
config.set("clanchat.format", sb.toString());
config.set("clanchat.rank", "&f[%rank%&f]");
config.set("clanchat.rank.color", null);
config.set("clanchat.name-color", null);
config.set("clanchat.player-bracket", null);
config.set("clanchat.message-color", null);
config.set("clanchat.tag-bracket", null);
}
public void migrateAllyChat() {
//Checks if the old format is still in use
if (config.getString("allychat.tag-color") == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_BRACKET_COLOR));
sb.append(settings.getString(ALLYCHAT_BRACKET_lEFT));
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_TAG_COLOR));
sb.append(settings.getString(COMMANDS_ALLY));
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_BRACKET_COLOR));
sb.append(settings.getString(ALLYCHAT_BRACKET_RIGHT));
sb.append(" ");
sb.append("&4<%clan%&4> ");
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_BRACKET_COLOR));
sb.append(settings.getString(ALLYCHAT_PLAYER_BRACKET_LEFT));
sb.append("%nick-color%");
sb.append("%player%");
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_BRACKET_COLOR));
sb.append(settings.getString(ALLYCHAT_PLAYER_BRACKET_RIGHT));
sb.append(" %rank%: ");
sb.append('&');
sb.append(settings.getColored(ALLYCHAT_MESSAGE_COLOR));
sb.append("%message%");
config.set("allychat.format", sb.toString());
config.set("allychat.rank", "&f[%rank%&f]");
config.set("allychat.tag-color", null);
config.set("allychat.name-color", null);
config.set("allychat.player-bracket", null);
config.set("allychat.message-color", null);
config.set("allychat.tag-bracket", null);
}
@Override
public void migrate() {
migrateClanChat();
migrateAllyChat();
}
}
@@ -0,0 +1,18 @@
package net.sacredlabyrinth.phaed.simpleclans.migrations;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import org.bukkit.configuration.file.FileConfiguration;
public abstract class ConfigMigration implements Migration {
protected final SettingsManager settings;
protected final FileConfiguration config;
public ConfigMigration(SettingsManager settingsManager) {
this.settings = settingsManager;
this.config = settings.getConfig();
migrate();
settings.save();
}
}
@@ -1,37 +1,29 @@
package net.sacredlabyrinth.phaed.simpleclans.language;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
package net.sacredlabyrinth.phaed.simpleclans.migrations;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Utility class that migrates old language files (yaml) to the new format (properties)
*
*
* @author RoinujNosde
*
*/
public class LanguageMigration {
private SimpleClans plugin;
public class LanguageMigration implements Migration {
private final SimpleClans plugin;
public LanguageMigration(SimpleClans plugin) {
this.plugin = plugin;
}
/**
* Migrates all language files in the plugin's data folder
*/
@@ -43,7 +35,7 @@ public class LanguageMigration {
File[] languageFiles = dataFolder.listFiles(f -> {
return f.getName().startsWith("language") && f.getName().endsWith(".yml");
});
for (File file : languageFiles) {
convert(file);
backup(file);
@@ -53,21 +45,22 @@ public class LanguageMigration {
/**
* Copies the file to the backup folder
*
* @param file the file to backup
*
* @param file the file to back up
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
private void backup(File file) {
File backupFolder = new File(plugin.getDataFolder(), "language_backup");
if (!backupFolder.exists()) {
backupFolder.mkdir();
}
file.renameTo(new File(backupFolder, file.getName()));
file.renameTo(new File(backupFolder, file.getName()));
}
/**
* Converts the yaml file to properties
*
*
* @param file
*/
private void convert(File file) {
@@ -0,0 +1,6 @@
package net.sacredlabyrinth.phaed.simpleclans.migrations;
public interface Migration {
void migrate();
}
@@ -23,9 +23,7 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.logging.Level;
public final class BungeeManager implements ProxyManager, PluginMessageListener {
@@ -35,11 +33,14 @@ public final class BungeeManager implements ProxyManager, PluginMessageListener
private static final String DELETE_CLAN_CHANNEL = "DeleteClan";
private static final String DELETE_CLANPLAYER_CHANNEL = "DeleteClanPlayer";
private static final String CHAT_CHANNEL = "Chat";
private static final String BROADCAST = "Broadcast";
private static final String MESSAGE = "Message";
private final SimpleClans plugin;
private final Gson gson;
private final List<String> onlinePlayers = new ArrayList<>();
private String serverName = "";
private final Set<String> unknownChannels = new HashSet<>();
public BungeeManager(SimpleClans plugin) {
this.plugin = plugin;
@@ -61,18 +62,40 @@ public final class BungeeManager implements ProxyManager, PluginMessageListener
public void onPluginMessageReceived(@NotNull String channel, @NotNull Player player, byte[] data) {
ByteArrayDataInput input = ByteStreams.newDataInput(data);
String subChannel = input.readUTF();
if (unknownChannels.contains(subChannel)) {
return;
}
SimpleClans.debug("Message received, sub-channel: " + subChannel);
try {
Class<?> clazz = Class.forName("net.sacredlabyrinth.phaed.simpleclans.proxy.listeners." + subChannel);
MessageListener listener = (MessageListener) clazz.getConstructor(BungeeManager.class).newInstance(this);
String serverName = null;
if (!listener.isBungeeSubchannel()) {
serverName = input.readUTF();
}
if (serverName != null && !isServerAllowed(serverName)) {
SimpleClans.debug(String.format("Server not allowed: %s", serverName));
return;
}
listener.accept(input);
SimpleClans.debug("Message processed");
} catch (ClassNotFoundException e) {
SimpleClans.debug(String.format("Unknown channel: %s", subChannel));
unknownChannels.add(subChannel);
} catch (ReflectiveOperationException ex) {
plugin.getLogger().log(Level.SEVERE, String.format("Error processing channel %s", subChannel), ex);
}
}
private boolean isServerAllowed(@NotNull String serverName) {
List<String> servers = plugin.getSettingsManager().getStringList(ConfigField.BUNGEE_SERVERS);
if (servers.isEmpty()) {
return true;
}
return servers.contains(serverName);
}
@Override
public boolean isOnline(String playerName) {
if (Bukkit.getOnlinePlayers().stream().anyMatch(player -> player.getName().equals(playerName))) {
@@ -100,23 +123,45 @@ public final class BungeeManager implements ProxyManager, PluginMessageListener
forwardPluginMessage(CHAT_CHANNEL, gson.toJson(message), false);
}
@SuppressWarnings("UnstableApiUsage")
@Override
public void sendMessage(@NotNull String target, @NotNull String message) {
if (isChannelRegistered()) {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("Message");
output.writeUTF(target);
output.writeUTF(message);
sendOnBungeeChannel(output);
} else {
if ("ALL".equals(target)) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendMessage(message));
} else {
Optional.ofNullable(Bukkit.getPlayer(target)).ifPresent(p -> p.sendMessage(message));
}
if (message.isEmpty()) {
return;
}
if ("ALL".equals(target)) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendMessage(message));
sendBroadcast(message);
return;
}
Player player = Bukkit.getPlayerExact(target);
if (player != null) {
player.sendMessage(message);
return;
}
sendPrivateMessage(target, message);
}
private void sendBroadcast(@NotNull String message) {
forwardPluginMessage(BROADCAST, message, false);
}
@SuppressWarnings("UnstableApiUsage")
private void sendPrivateMessage(@NotNull String playerName, @NotNull String message) {
if (!isChannelRegistered()) {
return;
}
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeUTF("Forward");
output.writeUTF("ONLINE");
output.writeUTF(MESSAGE);
output.writeUTF(serverName);
output.writeUTF(playerName);
output.writeUTF(message);
sendOnBungeeChannel(output);
}
@Override
@@ -182,7 +227,9 @@ public final class BungeeManager implements ProxyManager, PluginMessageListener
@SuppressWarnings("UnstableApiUsage")
private void forwardPluginMessage(final String subChannel, final String message, final boolean all) {
SimpleClans.debug(String.format("Forwarding message, channel %s, message %s, all %s", subChannel, message, all));
if (!isChannelRegistered()) {
SimpleClans.debug("Not registered");
return;
}
String target = all ? "ALL" : "ONLINE";
@@ -190,6 +237,7 @@ public final class BungeeManager implements ProxyManager, PluginMessageListener
output.writeUTF("Forward");
output.writeUTF(target);
output.writeUTF(subChannel);
output.writeUTF(serverName);
output.writeUTF(message);
sendOnBungeeChannel(output);
@@ -5,8 +5,8 @@ import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
@@ -39,7 +39,8 @@ public class ConfigurationSerializableAdapter implements TypeAdapterFactory {
return null;
}
Map map = adapter.read(in);
return ConfigurationSerialization.deserializeObject(map);
return ConfigurationSerialization.deserializeObject(map,
(Class<? extends ConfigurationSerializable>) type.getRawType());
}
};
}
@@ -0,0 +1,23 @@
package net.sacredlabyrinth.phaed.simpleclans.proxy.listeners;
import com.google.common.io.ByteArrayDataInput;
import net.sacredlabyrinth.phaed.simpleclans.proxy.BungeeManager;
import org.bukkit.Bukkit;
public class Broadcast extends MessageListener {
public Broadcast(BungeeManager bungee) {
super(bungee);
}
@Override
public void accept(ByteArrayDataInput data) {
String message = data.readUTF();
Bukkit.getOnlinePlayers().forEach(p -> p.sendMessage(message));
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
}
@@ -18,4 +18,9 @@ public class Chat extends MessageListener {
}
bungee.getPlugin().getChatManager().processChat(message);
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
}
@@ -1,6 +1,7 @@
package net.sacredlabyrinth.phaed.simpleclans.proxy.listeners;
import com.google.common.io.ByteArrayDataInput;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.proxy.BungeeManager;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.debug;
@@ -15,6 +16,19 @@ public class DeleteClan extends MessageListener {
public void accept(ByteArrayDataInput data) {
String tag = data.readUTF();
getClanManager().removeClan(tag);
for (ClanPlayer cp : getClanManager().getAllClanPlayers()) {
if (tag.equals(cp.getTag())) {
cp.setClan(null);
cp.setJoinDate(0);
cp.setRank(null);
cp.setLeader(false);
}
}
debug(String.format("Deleted clan %s", tag));
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
}
@@ -19,4 +19,9 @@ public class DeleteClanPlayer extends MessageListener {
getClanManager().deleteClanPlayerFromMemory(uuid);
debug(String.format("Deleted cp %s", uuid));
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
}
@@ -14,4 +14,9 @@ public class GetServer extends MessageListener {
String name = data.readUTF();
bungee.setServerName(name);
}
@Override
public boolean isBungeeSubchannel() {
return true;
}
}
@@ -0,0 +1,29 @@
package net.sacredlabyrinth.phaed.simpleclans.proxy.listeners;
import com.google.common.io.ByteArrayDataInput;
import net.sacredlabyrinth.phaed.simpleclans.proxy.BungeeManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Message extends MessageListener {
public Message(BungeeManager bungee) {
super(bungee);
}
@Override
public void accept(ByteArrayDataInput data) {
String target = data.readUTF();
String message = data.readUTF();
Player player = Bukkit.getPlayerExact(target);
if (player != null) {
player.sendMessage(message);
}
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
}
@@ -15,6 +15,8 @@ public abstract class MessageListener {
public abstract void accept(ByteArrayDataInput data);
public abstract boolean isBungeeSubchannel();
protected ClanManager getClanManager() {
return bungee.getPlugin().getClanManager();
}
@@ -20,4 +20,9 @@ public class PlayerList extends MessageListener {
bungee.setOnlinePlayers(players);
SimpleClans.debug("Updated player list");
}
@Override
public boolean isBungeeSubchannel() {
return true;
}
}
@@ -27,6 +27,7 @@ public abstract class Update<T> extends MessageListener {
T current = getCurrent(t);
if (current == null) {
insert(t);
debug(String.format("Inserted %s", t));
return;
}
try {
@@ -10,6 +10,11 @@ public class UpdateClan extends Update<Clan> {
super(bungee);
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
@Override
protected Class<Clan> getType() {
return Clan.class;
@@ -10,6 +10,11 @@ public class UpdateClanPlayer extends Update<ClanPlayer> {
super(bungee);
}
@Override
public boolean isBungeeSubchannel() {
return false;
}
@Override
protected Class<ClanPlayer> getType() {
return ClanPlayer.class;
@@ -4,6 +4,7 @@ import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.managers.PermissionsManager;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.scheduler.BukkitRunnable;
@@ -52,15 +53,15 @@ public class CollectFeeTask extends BukkitRunnable {
for (ClanPlayer cp : clan.getFeePayers()) {
OfflinePlayer player = Bukkit.getOfflinePlayer(cp.getUniqueId());
boolean success = pm.playerChargeMoney(player, memberFee);
boolean success = pm.chargePlayer(player, memberFee);
if (success) {
ChatBlock.sendMessage(cp, AQUA + lang("fee.collected", cp, memberFee));
ChatBlock.sendMessage(cp, AQUA + lang("fee.collected", cp, CurrencyFormat.format(memberFee)));
clan.deposit(new BankOperator(cp, pm.playerGetMoney(player)), Cause.MEMBER_FEE, memberFee);
plugin.getStorageManager().updateClan(clan);
} else {
clan.removePlayerFromClan(cp.getUniqueId());
clan.addBb(AQUA + lang("bb.fee.player.kicked", cp.getName()));
clan.addBb(lang("bb.fee.player.kicked", cp.getName()));
}
}
}
@@ -6,13 +6,13 @@ import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.events.ClanBalanceUpdateEvent;
import net.sacredlabyrinth.phaed.simpleclans.loggers.BankOperator;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import org.bukkit.scheduler.BukkitRunnable;
import java.text.MessageFormat;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.*;
import static org.bukkit.ChatColor.AQUA;
/**
*
@@ -60,7 +60,7 @@ public class CollectUpkeepTask extends BukkitRunnable {
clan.disband(null, true, false);
}
if (response == EconomyResponse.SUCCESS) {
clan.addBb(AQUA + MessageFormat.format(lang("upkeep.collected"), upkeep), false);
clan.addBb(MessageFormat.format(lang("upkeep.collected"), CurrencyFormat.format(upkeep)), false);
}
});
}
@@ -1,8 +1,9 @@
package net.sacredlabyrinth.phaed.simpleclans.threads;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import java.sql.Connection;
import java.sql.SQLException;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
/**
*
@@ -27,7 +27,7 @@ import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.COMMANDS_CLAN;
/**
*
*
* @author RoinujNosde
*
*/
@@ -40,7 +40,7 @@ public class InventoryController implements Listener {
if (!(entity instanceof Player)) {
return;
}
frames.remove(entity.getUniqueId());
}
@@ -55,13 +55,13 @@ public class InventoryController implements Listener {
if (frame == null) {
return;
}
event.setCancelled(true);
if (event.getClickedInventory() == null || event.getClickedInventory().getType() == InventoryType.PLAYER) {
return;
}
SCComponent component = frame.getComponent(event.getSlot());
if (component == null) {
return;
@@ -77,7 +77,7 @@ public class InventoryController implements Listener {
InventoryDrawer.open(new WarningFrame(frame, (Player) entity, null));
return;
}
Object permission = component.getPermission(click);
if (permission != null) {
if (!hasPermission((Player) entity, permission)) {
@@ -124,7 +124,7 @@ public class InventoryController implements Listener {
/**
* Checks if the player has the permission
*
*
* @param player the Player
* @param permission the permission
* @return true if they have permission
@@ -147,8 +147,8 @@ public class InventoryController implements Listener {
/**
* Registers the frame in the InventoryController
* @param frame the frame
*
* @author RoinujNosde
* <p>
* author: RoinujNosde
*/
public static void register(@NotNull SCFrame frame) {
frames.put(frame.getViewer().getUniqueId(), frame);
@@ -169,15 +169,16 @@ public class InventoryController implements Listener {
* @param player the Player
* @param subcommand the subcommand
* @param update whether to update the inventory instead of closing
*
* @author RoinujNosde
* <p>
* author: RoinujNosde
* </p>
*/
public static void runSubcommand(@NotNull Player player, @NotNull String subcommand, boolean update, String... args) {
SimpleClans plugin = SimpleClans.getInstance();
String baseCommand = plugin.getSettingsManager().getString(COMMANDS_CLAN);
String finalCommand = String.format("%s %s ", baseCommand, subcommand) + String.join(" ", args);
new BukkitRunnable() {
@Override
public void run() {
player.performCommand(finalCommand);
@@ -3,6 +3,7 @@ package net.sacredlabyrinth.phaed.simpleclans.ui;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.events.FrameOpenEvent;
import net.sacredlabyrinth.phaed.simpleclans.events.PostComponentsCreationEvent;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.utils.WordWrapper;
import org.bukkit.Bukkit;
@@ -35,19 +36,19 @@ public class InventoryDrawer {
return;
}
OPENING.put(uuid, frame);
FrameOpenEvent event = new FrameOpenEvent(frame.getViewer(), frame);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
OPENING.put(uuid, frame);
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
Inventory inventory = prepareInventory(frame);
Inventory inventory = prepareInventory(frame);
if (!frame.equals(OPENING.get(uuid))) {
return;
}
Bukkit.getScheduler().runTask(plugin, () -> {
FrameOpenEvent event = new FrameOpenEvent(frame.getViewer(), frame);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
frame.getViewer().openInventory(inventory);
InventoryController.register(frame);
OPENING.remove(uuid);
@@ -82,6 +83,7 @@ public class InventoryDrawer {
frame.clear();
try {
frame.createComponents();
Bukkit.getPluginManager().callEvent(new PostComponentsCreationEvent(frame));
} catch (NoSuchFieldError ex) {
runHelpCommand(frame.getViewer());
return;
@@ -93,7 +95,7 @@ public class InventoryDrawer {
return;
}
for (SCComponent c : frame.getComponents()) {
if (c.getSlot() >= frame.getSize()) {
if (c.getSlot() >= frame.getSize() || !c.isEnabled()) {
continue;
}
checkLorePermission(frame, c);
@@ -0,0 +1,62 @@
package net.sacredlabyrinth.phaed.simpleclans.ui;
import net.sacredlabyrinth.phaed.simpleclans.utils.Paginator;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
public abstract class PageableFrame<T> extends SCFrame {
public PageableFrame(@Nullable SCFrame parent, @NotNull Player viewer) {
super(parent, viewer);
}
@Override
@OverridingMethodsMustInvokeSuper
public void createComponents() {
super.createComponents();
SCComponent nextPage = new SCComponentImpl.Builder(getConfig(), "next_page")
.withViewer(getViewer())
.withDisplayNameKey("gui.next.page.title").build();
setOneTimeListener(nextPage, this::nextPage, getPaginator().hasNextPage());
add(nextPage);
SCComponent previousPage = new SCComponentImpl.Builder(getConfig(), "previous_page")
.withViewer(getViewer())
.withDisplayNameKey("gui.previous.page.title").build();
setOneTimeListener(previousPage, this::previousPage, getPaginator().hasPreviousPage());
add(previousPage);
}
public abstract Paginator<T> getPaginator();
public int getPageSize() {
return getConfig().getIntegerList("components.list.slots").size();
}
private void nextPage() {
if (getPaginator().nextPage()) {
update();
}
}
private void previousPage() {
if (getPaginator().previousPage()) {
update();
}
}
private void setOneTimeListener(final SCComponent component, final Runnable runnable, boolean pageCheck) {
if (!pageCheck) {
return;
}
component.setListener(ClickType.LEFT, () -> {
component.setListener(ClickType.LEFT, null);
runnable.run();
});
}
}
@@ -1,16 +1,15 @@
package net.sacredlabyrinth.phaed.simpleclans.ui;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Class that represents a button
@@ -20,6 +19,7 @@ import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
*/
public abstract class SCComponent {
private boolean enabled = true;
private final HashMap<ClickType, Runnable> listeners = new HashMap<>();
private final HashMap<ClickType, Object> permissions = new HashMap<>();
private final Set<ClickType> verified = new HashSet<>();
@@ -31,6 +31,14 @@ public abstract class SCComponent {
public abstract int getSlot();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Nullable
public ItemMeta getItemMeta() {
return getItem().getItemMeta();
@@ -1,15 +1,25 @@
package net.sacredlabyrinth.phaed.simpleclans.ui;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.ui.frames.Components;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class SCComponentImpl extends SCComponent {
@@ -45,6 +55,7 @@ public class SCComponentImpl extends SCComponent {
itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
item.setItemMeta(itemMeta);
}
checkSlot(slot);
this.slot = slot;
}
@@ -58,34 +69,66 @@ public class SCComponentImpl extends SCComponent {
return slot;
}
private static void checkMaterial(String material) {
if (material == null || material.isEmpty()) {
throw new IllegalStateException("material cannot be null or empty");
}
}
private static void checkSlot(int slot) {
if (slot < 0) {
throw new IllegalStateException("slot must be >= 0 and < 54");
}
}
public static class Builder {
private final SCComponentImpl component = new SCComponentImpl();
private boolean enabled;
private final ItemStack item;
private String displayName;
private int slot;
private @Nullable List<String> lore;
private Player viewer;
public Builder(@NotNull XMaterial material) {
this(material.parseItem());
}
@SuppressWarnings("unused")
public Builder(@NotNull Material material) {
component.item = new ItemStack(material);
this(new ItemStack(material));
}
public Builder(@Nullable ItemStack item) {
if (item == null) {
item = new ItemStack(Material.STONE);
}
component.item = item;
this.item = item;
}
public Builder(FileConfiguration config, String id) {
String materialName = config.getString("components." + id + ".material");
checkMaterial(materialName);
item = Objects.requireNonNull(XMaterial.matchXMaterial(materialName).orElse(XMaterial.STONE).parseItem());
slot = config.getInt("components." + id + ".slot");
checkSlot(slot);
enabled = config.getBoolean("components." + id + ".enabled");
}
public Builder withViewer(@NotNull Player player) {
this.viewer = player;
return this;
}
public Builder withDisplayName(@Nullable String displayName) {
ItemMeta itemMeta = component.getItemMeta();
if (itemMeta != null) {
itemMeta.setDisplayName(displayName);
component.setItemMeta(itemMeta);
}
this.displayName = displayName;
return this;
}
public Builder withDisplayNameKey(@NotNull String key, Object... args) {
if (viewer == null) throw new IllegalStateException("viewer is null");
return withDisplayName(lang(key, viewer, args));
}
public Builder withLore(@Nullable List<String> lore) {
this.lore = lore;
return this;
@@ -99,18 +142,154 @@ public class SCComponentImpl extends SCComponent {
return this;
}
public Builder withLoreKey(@NotNull String key, Object... args) {
if (viewer == null) throw new IllegalStateException("viewer is null");
return withLoreLine(lang(key, viewer, args));
}
public Builder withSlot(int slot) {
component.slot = slot;
checkSlot(slot);
this.slot = slot;
return this;
}
public SCComponent build() {
ItemMeta itemMeta = component.getItemMeta();
SCComponentImpl component = new SCComponentImpl();
component.item = item;
component.setEnabled(enabled);
ItemMeta itemMeta = item.getItemMeta();
if (itemMeta != null) {
itemMeta.setLore(lore);
itemMeta.setDisplayName(displayName);
component.setItemMeta(itemMeta);
}
component.slot = slot;
return component;
}
}
public static class ListBuilder<T> {
private final boolean enabled;
private final XMaterial material;
private Function<T, ItemStack> item;
private Function<T, OfflinePlayer> owningPlayer;
private final List<Integer> slots;
private final List<T> elements;
private Player viewer;
private Function<T, String> displayName = (t) -> null;
private final List<Function<T, String>> lore = new ArrayList<>();
private final Map<ClickType, Function<T, Runnable>> listeners = new HashMap<>();
private final Map<ClickType, String> bukkitPermissions = new HashMap<>();
private final Map<ClickType, RankPermission> rankPermissions = new HashMap<>();
private final Set<ClickType> confirmationRequired = new HashSet<>();
private String lorePermission;
public ListBuilder(@NotNull FileConfiguration config, @NotNull String id, @NotNull List<T> elements) {
String materialName = config.getString("components." + id + ".material");
checkMaterial(materialName);
material = XMaterial.matchXMaterial(materialName).orElse(XMaterial.STONE);
item = (t) -> Objects.requireNonNull(material.parseItem());
slots = config.getIntegerList("components." + id + ".slots").stream().filter(i -> i >= 0 && i < 54)
.collect(Collectors.toList());
this.elements = elements;
enabled = config.getBoolean("components." + id + ".enabled");
}
public ListBuilder(@NotNull FileConfiguration config, @NotNull String id) {
this(config, id, new ArrayList<>());
slots.forEach(e -> elements.add(null));
}
public ListBuilder<T> withItem(@NotNull Function<T, ItemStack> item) {
this.item = (t) -> {
ItemStack result = item.apply(t);
return result == null ? material.parseItem() : result;
};
return this;
}
public ListBuilder<T> withViewer(@NotNull Player player) {
viewer = player;
return this;
}
@SafeVarargs
public final ListBuilder<T> withDisplayNameKey(@NotNull String key, Function<T, Object>... args) {
displayName = (t) -> processLang(key, t, args);
return this;
}
@SafeVarargs
public final ListBuilder<T> withLoreKey(@NotNull String key, Function<T, Object>... args) {
lore.add((t) -> processLang(key, t, args));
return this;
}
public final ListBuilder<T> withLoreLine(Function<T, String> line) {
lore.add(line);
return this;
}
public final ListBuilder<T> withOwningPlayer(Function<T, OfflinePlayer> owningPlayer) {
this.owningPlayer = owningPlayer;
return this;
}
@NotNull
private String processLang(@NotNull String key, T t, Function<T, Object>[] args) {
Object[] processedArgs = Arrays.stream(args).map(func -> func.apply(t)).toArray();
if (viewer == null) throw new IllegalStateException("viewer is null");
return lang(key, viewer, processedArgs);
}
public ListBuilder<T> withLorePermission(@Nullable String permission) {
lorePermission = permission;
return this;
}
public ListBuilder<T> withListener(@NotNull ClickType click, @Nullable Function<T, Runnable> runnable, @Nullable String permission) {
bukkitPermissions.put(click, permission);
listeners.put(click, runnable);
return this;
}
public ListBuilder<T> withListener(@NotNull ClickType click, @Nullable Function<T, Runnable> runnable, @Nullable RankPermission permission) {
rankPermissions.put(click, permission);
listeners.put(click, runnable);
return this;
}
public ListBuilder<T> withConfirmationRequired(@NotNull ClickType click) {
confirmationRequired.add(click);
return this;
}
public List<SCComponent> build() {
List<SCComponent> components = new ArrayList<>();
for (int i = 0; i < elements.size() && i < slots.size(); i++) {
T t = elements.get(i);
SCComponentImpl component = new SCComponentImpl();
component.setEnabled(enabled);
component.item = item.apply(t);
component.slot = slots.get(i);
ItemMeta itemMeta = component.getItemMeta();
if (itemMeta != null) {
itemMeta.setDisplayName(displayName.apply(t));
List<String> processedLore = lore.stream().map(f -> f.apply(t)).collect(Collectors.toList());
itemMeta.setLore(processedLore);
if (itemMeta instanceof SkullMeta && owningPlayer != null) {
Components.setOwningPlayer(((SkullMeta) itemMeta), owningPlayer.apply(t));
}
component.setItemMeta(itemMeta);
}
component.setLorePermission(lorePermission);
listeners.forEach((click, fn) -> component.setListener(click, fn.apply(t)));
bukkitPermissions.forEach(component::setPermission);
rankPermissions.forEach(component::setPermission);
confirmationRequired.forEach(component::setConfirmationRequired);
components.add(component);
}
return components;
}
}
}
@@ -1,11 +1,18 @@
package net.sacredlabyrinth.phaed.simpleclans.ui;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import java.util.Collection;
/**
*
@@ -17,7 +24,7 @@ public abstract class SCFrame {
private final SCFrame parent;
private final Player viewer;
private final Set<SCComponent> components = ConcurrentHashMap.newKeySet();
public SCFrame(@Nullable SCFrame parent, @NotNull Player viewer) {
this.parent = parent;
this.viewer = viewer;
@@ -36,9 +43,27 @@ public abstract class SCFrame {
return parent;
}
public abstract int getSize();
public int getSize() {
return getConfig().getInt("rows", 6) * 9;
}
public abstract void createComponents();
@OverridingMethodsMustInvokeSuper
public void createComponents() {
SCComponent back = new SCComponentImpl.Builder(getConfig(), "back")
.withViewer(getViewer())
.withDisplayNameKey("gui.back.title").build();
back.setListener(ClickType.LEFT, () -> InventoryDrawer.open(getParent()));
add(back);
ConfigurationSection decorSection = getConfig().getConfigurationSection("components.decorations");
if (decorSection != null) {
for (String key : decorSection.getKeys(false)) {
addAll(new SCComponentImpl.ListBuilder<>(getConfig(), "decorations." + key)
.withViewer(getViewer())
.withDisplayNameKey(" ").build());
}
}
}
@Nullable
public SCComponent getComponent(int slot) {
@@ -51,18 +76,34 @@ public abstract class SCFrame {
}
public void add(@NotNull SCComponent c) {
SCComponent old = getComponent(c.getSlot());
if (old != null) {
components.remove(old);
}
components.add(c);
}
public void addAll(@NotNull Collection<SCComponent> collection) {
collection.forEach(this::add);
}
public void clear() {
components.clear();
}
public void update() {
InventoryDrawer.open(this);
}
@NotNull
public Set<SCComponent> getComponents() {
return components;
}
protected FileConfiguration getConfig() {
return SimpleClans.getInstance().getSettingsManager().getConfig(getClass());
}
@Override
public boolean equals(Object other) {
if (other instanceof SCFrame) {
@@ -1,6 +1,5 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
@@ -10,77 +9,46 @@ import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class AddAllyFrame extends SCFrame {
private final List<Clan> notAllies;
private final Paginator paginator;
public class AddAllyFrame extends PageableFrame<Clan> {
private final Paginator<Clan> paginator;
public AddAllyFrame(SCFrame parent, Player viewer, Clan subject) {
super(parent, viewer);
SimpleClans plugin = SimpleClans.getInstance();
notAllies = plugin.getClanManager().getClans().stream()
.filter(c -> !c.equals(subject) && !c.isRival(subject.getTag()) && !c.isAlly(subject.getTag()))
.collect(Collectors.toList());
paginator = new Paginator(getSize() - 9, notAllies);
}
public AddAllyFrame(SCFrame parent, Player viewer, Clan subject) {
super(parent, viewer);
SimpleClans plugin = SimpleClans.getInstance();
List<Clan> notAllies = plugin.getClanManager().getClans().stream()
.filter(c -> !c.equals(subject) && !c.isRival(subject.getTag()) && !c.isAlly(subject.getTag()))
.collect(Collectors.toList());
paginator = new Paginator<>(getPageSize(), notAllies);
}
@Override
public void createComponents() {
for (int slot = 0; slot < 9; slot++) {
if (slot == 2 || slot == 6 || slot == 7)
continue;
add(Components.getPanelComponent(slot));
}
add(Components.getBackComponent(getParent(), 2, getViewer()));
@Override
public void createComponents() {
super.createComponents();
List<SCComponent> list = new SCComponentImpl.ListBuilder<>(getConfig(), "list", paginator.getCurrentElements())
.withViewer(getViewer())
.withLoreKey("gui.add.ally.clan.lore")
.withListener(ClickType.LEFT, this::addAlly, RankPermission.ALLY_ADD)
.build();
addAll(list);
}
add(Components.getPreviousPageComponent(6, this::previousPage, paginator, getViewer()));
add(Components.getNextPageComponent(7, this::nextPage, paginator, getViewer()));
private Runnable addAlly(Clan clan) {
return () -> InventoryController.runSubcommand(getViewer(), "ally add", false, clan.getTag());
}
int slot = 9;
for (int i = paginator.getMinIndex(); paginator.isValidIndex(i); i++) {
@Override
public Paginator<Clan> getPaginator() {
return paginator;
}
Clan notRival = notAllies.get(i);
SCComponent c = new SCComponentImpl(
lang("gui.clanlist.clan.title", getViewer(), notRival.getColorTag(), notRival.getName()),
Collections.singletonList(lang("gui.add.ally.clan.lore", getViewer())), XMaterial.CYAN_BANNER,
slot);
@Override
public @NotNull String getTitle() {
return lang("gui.add.ally.title", getViewer());
}
c.setListener(ClickType.LEFT, () -> InventoryController.runSubcommand(getViewer(),
"ally add", false, notRival.getTag()));
c.setPermission(ClickType.LEFT, RankPermission.ALLY_ADD);
add(c);
slot++;
}
}
private void previousPage() {
if (paginator.previousPage()) {
updateFrame();
}
}
private void nextPage() {
if (paginator.nextPage()) {
updateFrame();
}
}
private void updateFrame() {
InventoryDrawer.open(this);
}
@Override
public @NotNull String getTitle() {
return lang("gui.add.ally.title",getViewer());
}
@Override
public int getSize() {
return 6 * 9;
}
}
@@ -1,23 +1,27 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Helper;
import net.sacredlabyrinth.phaed.simpleclans.Rank;
import net.sacredlabyrinth.phaed.simpleclans.ui.*;
import net.sacredlabyrinth.phaed.simpleclans.ui.InventoryController;
import net.sacredlabyrinth.phaed.simpleclans.ui.PageableFrame;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCComponent;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCComponentImpl.ListBuilder;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCFrame;
import net.sacredlabyrinth.phaed.simpleclans.utils.Paginator;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class AddPermissionFrame extends SCFrame {
private final String[] availablePermissions;
private final Paginator paginator;
public class AddPermissionFrame extends PageableFrame<String> {
private final List<String> availablePermissions;
private final Paginator<String> paginator;
private final Rank rank;
public AddPermissionFrame(SCFrame parent, Player viewer, Rank rank) {
@@ -25,63 +29,38 @@ public class AddPermissionFrame extends SCFrame {
this.rank = rank;
Set<String> rankPerms = rank.getPermissions();
availablePermissions = Arrays.stream(Helper.fromPermissionArray()).filter(p -> !rankPerms.contains(p))
.toArray(String[]::new);
paginator = new Paginator(getSize() - 9, availablePermissions.length);
.collect(Collectors.toList());
paginator = new Paginator<>(getPageSize(), availablePermissions);
}
@Override
public void createComponents() {
for (int slot = 0; slot < 9; slot++) {
if (slot == 2 || slot == 6 || slot == 7)
continue;
add(Components.getPanelComponent(slot));
}
add(Components.getBackComponent(getParent(), 2, getViewer()));
add(Components.getPreviousPageComponent(6, this::previousPage, paginator, getViewer()));
add(Components.getNextPageComponent(7, this::nextPage, paginator, getViewer()));
int slot = 9;
for (int i = paginator.getMinIndex(); paginator.isValidIndex(i); i++) {
String permission = availablePermissions[i];
SCComponent c = new SCComponentImpl(
lang("gui.add.permission.permission.title",getViewer(), permission),
Collections.singletonList(lang("gui.add.permission.permission.lore",getViewer())),
XMaterial.PAPER, slot);
c.setListener(ClickType.LEFT, () -> InventoryController.runSubcommand(getViewer(),
"rank permissions add", true, rank.getName(), permission));
c.setPermission(ClickType.LEFT, "simpleclans.leader.rank.permissions.add");
add(c);
slot++;
}
super.createComponents();
List<SCComponent> list = new ListBuilder<>(getConfig(), "list", paginator.getCurrentElements())
.withViewer(getViewer())
.withDisplayNameKey("gui.add.permission.permission.title", p -> p)
.withLoreKey("gui.add.permission.permission.lore")
.withListener(ClickType.LEFT, this::addPermission, "simpleclans.leader.rank.permissions.add")
.build();
addAll(list);
}
private void previousPage() {
if (paginator.previousPage()) {
updateFrame();
}
private Runnable addPermission(String permission) {
return () -> {
availablePermissions.remove(permission);
InventoryController.runSubcommand(getViewer(), "rank permissions add", true,
rank.getName(), permission);
};
}
private void nextPage() {
if (paginator.nextPage()) {
updateFrame();
}
}
private void updateFrame() {
InventoryDrawer.open(this);
@Override
public Paginator<String> getPaginator() {
return paginator;
}
@Override
public @NotNull String getTitle() {
return lang("gui.add.permission.title",getViewer());
}
@Override
public int getSize() {
return 3 * 9;
return lang("gui.add.permission.title", getViewer());
}
}
@@ -1,6 +1,5 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
@@ -10,79 +9,45 @@ import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class AddRivalFrame extends SCFrame {
public class AddRivalFrame extends PageableFrame<Clan> {
private final List<Clan> notRivals;
private final Paginator paginator;
private final Paginator<Clan> paginator;
public AddRivalFrame(SCFrame parent, Player viewer, Clan subject) {
super(parent, viewer);
SimpleClans plugin = SimpleClans.getInstance();
notRivals = plugin.getClanManager().getClans().stream()
.filter(c -> !c.equals(subject) && !c.isRival(subject.getTag()) && !c.isAlly(subject.getTag()))
.collect(Collectors.toList());
paginator = new Paginator(getSize() - 9, notRivals.size());
}
public AddRivalFrame(SCFrame parent, Player viewer, Clan subject) {
super(parent, viewer);
SimpleClans plugin = SimpleClans.getInstance();
List<Clan> notRivals = plugin.getClanManager().getClans().stream().filter(c -> !c.equals(subject) && !c.isRival(subject.getTag()) && !c.isAlly(subject.getTag())).collect(Collectors.toList());
paginator = new Paginator<>(getPageSize(), notRivals);
}
@Override
public void createComponents() {
for (int slot = 0; slot < 9; slot++) {
if (slot == 2 || slot == 6 || slot == 7)
continue;
add(Components.getPanelComponent(slot));
}
add(Components.getBackComponent(getParent(), 2, getViewer()));
@Override
public void createComponents() {
super.createComponents();
List<SCComponent> list = new SCComponentImpl.ListBuilder<>(getConfig(), "list", paginator.getCurrentElements())
.withViewer(getViewer())
.withDisplayNameKey("gui.clanlist.clan.title", Clan::getColorTag, Clan::getName)
.withLoreKey("gui.add.rival.clan.lore")
.withListener(ClickType.LEFT, this::addRival, RankPermission.RIVAL_ADD)
.withConfirmationRequired(ClickType.LEFT).build();
addAll(list);
}
add(Components.getPreviousPageComponent(6, this::previousPage, paginator, getViewer()));
add(Components.getNextPageComponent(7, this::nextPage, paginator, getViewer()));
private Runnable addRival(Clan clan) {
return () -> InventoryController.runSubcommand(getViewer(), "rival add", false, clan.getTag());
}
int slot = 9;
for (int i = paginator.getMinIndex(); paginator.isValidIndex(i); i++) {
@Override
public Paginator<Clan> getPaginator() {
return paginator;
}
Clan notRival = notRivals.get(i);
SCComponent c = new SCComponentImpl(
lang("gui.clanlist.clan.title",getViewer(), notRival.getColorTag(), notRival.getName()),
Collections.singletonList(lang("gui.add.rival.clan.lore", getViewer())), XMaterial.RED_BANNER,
slot);
c.setListener(ClickType.LEFT, () -> InventoryController.runSubcommand(getViewer(),
"rival add", false, notRival.getTag()));
c.setConfirmationRequired(ClickType.LEFT);
c.setPermission(ClickType.LEFT, RankPermission.RIVAL_ADD);
add(c);
slot++;
}
}
private void previousPage() {
if (paginator.previousPage()) {
updateFrame();
}
}
private void nextPage() {
if (paginator.nextPage()) {
updateFrame();
}
}
private void updateFrame() {
InventoryDrawer.open(this);
}
@Override
public @NotNull String getTitle() {
return lang("gui.add.rival.title",getViewer());
}
@Override
public int getSize() {
return 6 * 9;
}
@Override
public @NotNull String getTitle() {
return lang("gui.add.rival.title", getViewer());
}
}
@@ -1,94 +1,64 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import net.sacredlabyrinth.phaed.simpleclans.ui.*;
import net.sacredlabyrinth.phaed.simpleclans.utils.Paginator;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
public class AlliesFrame extends SCFrame {
private final SimpleClans plugin = SimpleClans.getInstance();
private final Paginator paginator;
private final List<String> allies;
private final Clan subject;
public class AlliesFrame extends PageableFrame<Clan> {
private final Paginator<Clan> paginator;
private final Clan subject;
public AlliesFrame(Player viewer, SCFrame parent, Clan subject) {
super(parent, viewer);
this.subject = subject;
allies = subject.getAllies();
paginator = new Paginator(getSize() - 9, allies.size());
}
public AlliesFrame(Player viewer, SCFrame parent, Clan subject) {
super(parent, viewer);
this.subject = subject;
ClanManager manager = SimpleClans.getInstance().getClanManager();
List<Clan> allies = subject.getAllies().stream().map(manager::getClan).filter(Objects::nonNull).collect(Collectors.toList());
paginator = new Paginator<>(getPageSize(), allies);
}
@Override
public void createComponents() {
for (int slot = 0; slot < 9; slot++) {
if (slot == 2 || slot == 4 || slot == 6 || slot == 7)
continue;
add(Components.getPanelComponent(slot));
}
@Override
public void createComponents() {
super.createComponents();
add(Components.getBackComponent(getParent(), 2, getViewer()));
SCComponent add = new SCComponentImpl.Builder(getConfig(), "add")
.withViewer(getViewer())
.withDisplayNameKey("gui.allies.add.title")
.build();
add.setVerifiedOnly(ClickType.LEFT);
add.setListener(ClickType.LEFT, () -> InventoryDrawer.open(new AddAllyFrame(this, getViewer(), subject)));
add.setPermission(ClickType.LEFT, RankPermission.ALLY_ADD);
add(add);
SCComponent add = new SCComponentImpl(lang("gui.allies.add.title",getViewer()), null,
XMaterial.CYAN_WOOL, 4);
add.setVerifiedOnly(ClickType.LEFT);
add.setListener(ClickType.LEFT, () -> InventoryDrawer.open(new AddAllyFrame(this, getViewer(), subject)));
add.setPermission(ClickType.LEFT, RankPermission.ALLY_ADD);
add(add);
List<SCComponent> list = new SCComponentImpl.ListBuilder<>(getConfig(), "list", paginator.getCurrentElements())
.withViewer(getViewer())
.withDisplayNameKey("gui.clanlist.clan.title", Clan::getColorTag, Clan::getName)
.withLoreKey("gui.allies.clan.lore")
.withListener(ClickType.RIGHT, (clan) -> () -> InventoryController.runSubcommand(getViewer(),
"ally remove", false, clan.getTag()), RankPermission.ALLY_REMOVE)
.build();
addAll(list);
}
add(Components.getPreviousPageComponent(6, this::previousPage, paginator, getViewer()));
add(Components.getNextPageComponent(7, this::nextPage, paginator, getViewer()));
@Override
public Paginator<Clan> getPaginator() {
return paginator;
}
int slot = 9;
for (int i = paginator.getMinIndex(); paginator.isValidIndex(i); i++) {
Clan clan = plugin.getClanManager().getClan(allies.get(i));
if (clan == null)
continue;
SCComponent c = new SCComponentImpl(
lang("gui.clanlist.clan.title",getViewer(), clan.getColorTag(), clan.getName()),
Collections.singletonList(lang("gui.allies.clan.lore",getViewer())), XMaterial.CYAN_BANNER, slot);
c.setListener(ClickType.RIGHT, () -> InventoryController.runSubcommand(getViewer(),
"ally remove", false, clan.getTag()));
c.setPermission(ClickType.RIGHT, RankPermission.ALLY_REMOVE);
add(c);
slot++;
}
}
private void previousPage() {
if (paginator.previousPage()) {
updateFrame();
}
}
private void nextPage() {
if (paginator.nextPage()) {
updateFrame();
}
}
private void updateFrame() {
InventoryDrawer.open(this);
}
@Override
public @NotNull String getTitle() {
return lang("gui.allies.title",getViewer());
}
@Override
public int getSize() {
return 6 * 9;
}
@Override
public @NotNull String getTitle() {
return lang("gui.allies.title", getViewer());
}
}
@@ -1,11 +1,15 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.*;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer.Channel;
import net.sacredlabyrinth.phaed.simpleclans.RankPermission;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.ui.*;
import net.sacredlabyrinth.phaed.simpleclans.utils.ChatUtils;
import net.sacredlabyrinth.phaed.simpleclans.utils.CurrencyFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.VanishUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
@@ -139,6 +143,7 @@ public class ClanDetailsFrame extends SCFrame {
50);
disband.setListener(ClickType.DROP, () -> InventoryController.runSubcommand(getViewer(), "disband", false));
disband.setPermission(ClickType.DROP, "simpleclans.leader.disband");
disband.setConfirmationRequired(ClickType.LEFT);
add(disband);
}
@@ -161,7 +166,7 @@ public class ClanDetailsFrame extends SCFrame {
List<String> lore = verified ? null : new ArrayList<>();
if (!verified) {
if (purchaseVerification) {
lore.add(lang("gui.clandetails.verify.price.lore", getViewer(), settings.getDouble(ECONOMY_VERIFICATION_PRICE)));
lore.add(lang("gui.clandetails.verify.price.lore", getViewer(), CurrencyFormat.format(settings.getDouble(ECONOMY_VERIFICATION_PRICE))));
}
lore.add(lang("gui.clandetails.not.verified.lore", getViewer()));
}
@@ -177,7 +182,7 @@ public class ClanDetailsFrame extends SCFrame {
String withdrawStatus = clan.isAllowWithdraw() ? lang("allowed",getViewer()) : lang("blocked",getViewer());
String depositStatus = clan.isAllowDeposit() ? lang("allowed", getViewer()) : lang("blocked", getViewer());
SCComponent bank = new SCComponentImpl(lang("gui.clandetails.bank.title", getViewer()),
Arrays.asList(lang("gui.clandetails.bank.balance.lore", getViewer(), clan.getBalance()),
Arrays.asList(lang("gui.clandetails.bank.balance.lore", getViewer(), clan.getBalanceFormatted()),
lang("gui.clandetails.bank.withdraw.status.lore", getViewer(), withdrawStatus),
lang("gui.clandetails.bank.deposit.status.lore", getViewer(), depositStatus),
lang("gui.clandetails.bank.withdraw.toggle.lore", getViewer()),
@@ -242,7 +247,7 @@ public class ClanDetailsFrame extends SCFrame {
}
List<String> lore = new ArrayList<>();
if (price != 0) lore.add(lang("gui.clandetails.regroup.lore.price", getViewer(), price));
if (price != 0) lore.add(lang("gui.clandetails.regroup.lore.price", getViewer(), CurrencyFormat.format(price)));
lore.add(lang("gui.clandetails.regroup.lore.home", getViewer()));
lore.add(lang("gui.clandetails.regroup.lore.me", getViewer()));
@@ -264,9 +269,9 @@ public class ClanDetailsFrame extends SCFrame {
double setPrice = settings.is(ECONOMY_PURCHASE_HOME_TELEPORT_SET) ? settings.getDouble(ECONOMY_HOME_TELEPORT_SET_PRICE) : 0;
List<String> lore = new ArrayList<>();
if (homePrice != 0) lore.add(lang("gui.clandetails.home.lore.teleport.price", getViewer(), homePrice));
if (homePrice != 0) lore.add(lang("gui.clandetails.home.lore.teleport.price", getViewer(), CurrencyFormat.format(homePrice)));
lore.add(lang("gui.clandetails.home.lore.teleport", getViewer()));
if (setPrice != 0) lore.add(lang("gui.clandetails.home.lore.set.price", getViewer(), setPrice));
if (setPrice != 0) lore.add(lang("gui.clandetails.home.lore.set.price", getViewer(), CurrencyFormat.format(setPrice)));
lore.add(lang("gui.clandetails.home.lore.set", getViewer()));
lore.add(lang("gui.clandetails.home.lore.clear", getViewer()));
@@ -1,31 +1,28 @@
package net.sacredlabyrinth.phaed.simpleclans.ui.frames;
import com.cryptomorin.xseries.XMaterial;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager;
import net.sacredlabyrinth.phaed.simpleclans.ui.InventoryDrawer;
import net.sacredlabyrinth.phaed.simpleclans.ui.PageableFrame;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCComponent;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCComponentImpl;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCComponentImpl.ListBuilder;
import net.sacredlabyrinth.phaed.simpleclans.ui.SCFrame;
import net.sacredlabyrinth.phaed.simpleclans.utils.KDRFormat;
import net.sacredlabyrinth.phaed.simpleclans.utils.Paginator;
import net.sacredlabyrinth.phaed.simpleclans.utils.RankingNumberResolver;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static net.sacredlabyrinth.phaed.simpleclans.SimpleClans.lang;
import static net.sacredlabyrinth.phaed.simpleclans.managers.SettingsManager.ConfigField.SHOW_UNVERIFIED_ON_LIST;
public class ClanListFrame extends SCFrame {
public class ClanListFrame extends PageableFrame<Clan> {
private final List<Clan> clans;
private final Paginator paginator;
private final Paginator<Clan> paginator;
private final RankingNumberResolver<Clan, BigDecimal> rankingResolver;
public ClanListFrame(SCFrame parent, Player viewer) {
@@ -34,8 +31,8 @@ public class ClanListFrame extends SCFrame {
SettingsManager sm = plugin.getSettingsManager();
clans = plugin.getClanManager().getClans().stream()
.filter(clan -> clan.isVerified() || sm.is(SHOW_UNVERIFIED_ON_LIST)).collect(Collectors.toList());
paginator = new Paginator(getSize() - 9, clans);
plugin.getClanManager().sortClansByKDR(clans);
paginator = new Paginator<>(getPageSize(), clans);
rankingResolver = new RankingNumberResolver<>(clans, c -> KDRFormat.toBigDecimal(c.getTotalKDR()), false,
sm.getRankingType());
@@ -43,57 +40,26 @@ public class ClanListFrame extends SCFrame {
@Override
public void createComponents() {
for (int slot = 0; slot < 9; slot++) {
if (slot == 2 || slot == 6 || slot == 7)
continue;
add(Components.getPanelComponent(slot));
}
add(Components.getBackComponent(getParent(), 2, getViewer()));
add(Components.getPreviousPageComponent(6, this::previousPage, paginator, getViewer()));
add(Components.getNextPageComponent(7, this::nextPage, paginator, getViewer()));
int slot = 9;
for (int i = paginator.getMinIndex(); paginator.isValidIndex(i); i++) {
Clan clan = clans.get(i);
ItemStack banner = clan.getBanner() != null ? clan.getBanner() : XMaterial.BLACK_BANNER.parseItem();
SCComponent c = new SCComponentImpl(
lang("gui.clanlist.clan.title", getViewer(), clan.getColorTag(), clan.getName()),
Arrays.asList(lang("gui.clanlist.clan.lore.position", getViewer(),
rankingResolver.getRankingNumber(clan)),
lang("gui.clanlist.clan.lore.kdr", getViewer(), KDRFormat.format(clan.getTotalKDR())),
lang("gui.clanlist.clan.lore.members", getViewer(), clan.getMembers().size())),
banner, slot);
c.setLorePermission("simpleclans.anyone.list");
add(c);
slot++;
}
super.createComponents();
List<SCComponent> list = new ListBuilder<>(getConfig(), "list", paginator.getCurrentElements())
.withItem(Clan::getBanner)
.withViewer(getViewer())
.withDisplayNameKey("gui.clanlist.clan.title", Clan::getColorTag, Clan::getName)
.withLoreKey("gui.clanlist.clan.lore.position", rankingResolver::getRankingNumber)
.withLoreKey("gui.clanlist.clan.lore.kdr", clan -> KDRFormat.format(clan.getTotalKDR()))
.withLoreKey("gui.clanlist.clan.lore.members", clan -> clan.getMembers().size())
.withLorePermission("simpleclans.anyone.list").build();
addAll(list);
}
private void previousPage() {
if (paginator.previousPage()) {
updateFrame();
}
}
private void nextPage() {
if (paginator.nextPage()) {
updateFrame();
}
}
private void updateFrame() {
InventoryDrawer.open(this);
@Override
public Paginator<Clan> getPaginator() {
return paginator;
}
@Override
public @NotNull String getTitle() {
return lang("gui.clanlist.title",getViewer(), clans.size());
}
@Override
public int getSize() {
return 6 * 9;
return lang("gui.clanlist.title", getViewer(), clans.size());
}
}
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more