Compare commits

...
286 Commits
Author SHA1 Message Date
BenCodez fe401f1988 Update version number to 7.1 in pom.xml for release
- Changed version from 7.1-SNAPSHOT to 7.1
- Updated dependency version from 3.8.1-SNAPSHOT to 3.8.1
2026-06-07 15:15:25 -06:00
Ben 14feedf4f0 Update javadoc source folder path in workflow 2026-06-07 15:15:13 -06:00
BenCodez 1aa360d844 Refactor VoteStreak command handlers and add new functionalities
- Updated command structure for setting legacy vote streaks (daily,
weekly, monthly).
- Introduced commands for advancing vote streaks and setting amounts
without rewards.
- Enhanced tab completion for vote streak states and reset targets.
- Fixed minor config.yml comment update
2026-06-07 14:21:33 -06:00
BenCodez 4b899c2175 Migrate legacy vote streak configurations to shared progress groups
- Updated migration logic to handle enabled legacy entries only.
- Created new configuration sections for progress groups and milestones.
- Adjusted reward paths for migrated definitions.
2026-06-06 20:51:48 -06:00
BenCodez 8bea5b70ec Add tests for lost rewards handling in progress groups for VoteStreaks
- Implement tests to verify lost rewards behavior based on milestone
  requirements and streak counts.
- Validate that lost rewards are correctly configured in YAML sections
  for progress groups.
2026-06-06 20:43:41 -06:00
BenCodez 6e986f0e3a Add lost rewards handling for progress groups in VoteStreaks
- Implement logic to give rewards when a progress group streak is lost.
- Introduce configuration option 'RequireMilestoneForLostRewards' in
SpecialRewards.yml to control reward eligibility based on milestone
achievement.
- Update methods to handle lost rewards and check for enabled
milestones.
2026-06-06 20:38:25 -06:00
BenCodez 09fcb7f926 Add special rewards editor paths for vote streak progress groups
- Introduced a method to register directly editable rewards paths from
  SpecialRewards.yml for VoteMilestones and ProgressGroups.
- Enhanced configuration handling for milestone rewards within the
  VoteStreaks section.
2026-06-06 20:29:28 -06:00
BenCodez 920e243fc4 Add ProgressGroups example configuration for daily vote streaks 2026-06-06 20:26:28 -06:00
Ben 02b8d013ab Merge pull request #1520 from semisolar/feature/votestreak-shared-progress-only
Add shared VoteStreaks progress groups
2026-06-02 16:03:43 -06:00
semisolar 2193fa4e1a Add shared VoteStreaks progress groups 2026-06-01 23:32:28 -04:00
Ben 6e6986a373 Merge pull request #1519 from semisolar/feature/votestreak-reset-command
Add VoteStreaks reset command
2026-06-01 19:25:48 -06:00
semisolar 121cca6a97 Add VoteStreaks reset command 2026-06-01 18:02:49 -04:00
BenCodez c633baa12b update junit version in pom.xml to 5.12.2 2026-05-31 13:41:30 -06:00
Ben b3aec70ebc Merge pull request #1499 from BenCodez/dependabot/maven/VotingPlugin/org.junit.jupiter-junit-jupiter-api-6.0.3
Bump org.junit.jupiter:junit-jupiter-api from 5.12.2 to 6.0.3 in /VotingPlugin
2026-05-31 13:36:50 -06:00
Ben bf08a03059 Merge pull request #1502 from BenCodez/dependabot/maven/VotingPlugin/org.mockito-mockito-junit-jupiter-5.23.0
Bump org.mockito:mockito-junit-jupiter from 5.15.2 to 5.23.0 in /VotingPlugin
2026-05-31 13:35:30 -06:00
Ben b6542debaf Merge pull request #1501 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-shade-plugin-3.6.2
Bump org.apache.maven.plugins:maven-shade-plugin from 3.6.1 to 3.6.2 in /VotingPlugin
2026-05-31 13:35:14 -06:00
Ben 549686fd37 Merge pull request #1500 from BenCodez/dependabot/maven/VotingPlugin/me.clip-placeholderapi-2.12.2
Bump me.clip:placeholderapi from 2.11.6 to 2.12.2 in /VotingPlugin
2026-05-31 13:35:00 -06:00
Ben 1166db03ec Merge pull request #1498 from BenCodez/dependabot/maven/VotingPlugin/org.bstats-bstats-velocity-3.2.1
Bump org.bstats:bstats-velocity from 3.1.0 to 3.2.1 in /VotingPlugin
2026-05-31 13:34:41 -06:00
BenCodez e4bbd982a2 Update JAR final name format in pom.xml to remove .jar extension 2026-05-18 11:49:11 -06:00
BenCodez 3112e76227 Update JAR naming convention in pom.xml
Changed the final name of the built JAR to include the build number for
better version tracking. Removed the copy-rename plugin configuration as
it is no longer needed.
2026-05-18 11:46:53 -06:00
BenCodez e3088f5e70 Add JavaScript engine configuration options to Config.yml
- Introduced settings for enabling JavaScript support and
auto-downloading
  dependencies in the configuration file.
- Removed legacy options for better clarity and updated documentation
  for each setting.
2026-05-17 15:15:30 -06:00
BenCodez 7137de2ce3 Fix inventory closing method in VoteShop confirmation GUI
Replaced the deprecated method for closing the inventory with the
current event method to ensure proper functionality in the
VoteShop confirmation dialog.
2026-05-14 17:16:24 -06:00
BenCodez 2c97bc171f Fix missing semicolon 2026-05-14 16:44:55 -06:00
BenCodez df950984c3 Fix closing inventory on saying no in shop confirmation GUI 2026-05-14 16:42:42 -06:00
BenCodez 11f54ef959 Remove unnecessary GUI close check in VoteShop confirmation dialog 2026-05-14 15:53:08 -06:00
BenCodez 213623835d Fix case sensitivity in VoteStreak definition retrieval tests
Updated test cases in VoteStreakHandlerTest to ensure that
the retrieval of VoteStreak definitions is case insensitive.
This includes assertions for different casing variations
of the "DailyStreak" identifier.
2026-05-13 18:23:32 -06:00
BenCodez 2dc6af10b1 Add command to force VoteStreak rewards by ID and amount in streak
- Introduced new admin commands to force VoteStreak rewards for users.
- Added tab completion for VoteStreak IDs.
- Updated VoteStreakHandler to support forced rewards without altering
streak progress or vote counts.
2026-05-13 18:18:02 -06:00
BenCodez 8e8c10c7a2 Fix GUI close behavior in VoteShop confirmation dialog
- Added functionality to close the inventory when the close button is
clicked.
- Improved code formatting for better readability.
2026-05-13 18:09:11 -06:00
Ben 35dc993bf1 Merge pull request #1509 from semisolar/fix-votestreak-migration-recurring
Fix VoteStreak one-time rewards and legacy list migration
2026-05-02 08:08:23 -06:00
SemiSolar 425374a757 Fix VoteStreak one-time rewards and legacy list migration 2026-05-02 02:39:48 -04:00
BenCodez a74a7e35b8 Add legacy VoteStreak migration command and update configuration
- Introduced a command to migrate legacy VoteStreak configurations to
the new format.
- Updated VoteStreakDefinition to include a recurring flag.
- Modified VoteStreakHandler to handle legacy progress migration.
- Adjusted SpecialRewards.yml to include a Recurring option for rewards.
2026-05-01 21:11:11 -06:00
BenCodez 49d8020fd1 Bump version number to 7.1-SNAPSHOT in pom.xml 2026-04-18 21:28:34 -06:00
BenCodez 4db6239653 Update dependencies and refactor HTTP requests to use HttpClient
- Bump version to 26.1.2-R0.1-SNAPSHOT
- Replace HttpURLConnection with HttpClient for GitHub and Mojang API
requests
- Update methods to handle InterruptedException
- Adjust tests to accommodate new method signatures
2026-04-10 21:04:28 -06:00
BenCodez 71f3894a5d Add NameMC like reward feature with configuration options
- Introduced NameMCLikeCheckerTask to periodically check NameMC likes.
- Added configuration options for enabling the feature, setting the URL,
and defining check intervals in SpecialRewards.yml.
- Updated VotingPluginUser to track if the NameMC like reward has been
claimed.
2026-04-10 20:56:22 -06:00
BenCodez ded0b93880 Refactor voteparty vote reminder configuration and add command support
- Updated configuration paths in SpecialRewardsConfig for clarity.
- Introduced new command list for vote reminders in SpecialRewards.yml.
- Enhanced VoteParty to execute console commands for reminders.
2026-04-10 20:48:21 -06:00
BenCodez dcb29e3cca Revert minor change 2026-04-05 19:43:56 -06:00
BenCodez 6c24ae9397 Improve updating proxy voteparty votes, even if set to 0 2026-04-05 19:38:33 -06:00
BenCodez 285a19c422 Update proxy voteparty placeholders right away on voteupdate message 2026-04-05 19:02:44 -06:00
BenCodez 55fc3dc0b1 Update proxy vote party placeholders on update 2026-04-05 18:17:23 -06:00
BenCodez 0516a4f679 Enhance debug logging for vote update messages in BungeeHandler
- Include current and required vote party counts along with service info
2026-04-05 14:10:39 -06:00
BenCodez b73a82cba9 Update version in pom.xml and refactor VoteShop command handling
- Bump version to 26.1.1-R0.1-SNAPSHOT in pom.xml
- Refactor VoteShop command to check if vote shop is enabled
- Improve user feedback when vote shop is disabled
2026-04-03 12:44:27 -06:00
BenCodez f89ad455cb Remove command aliases from plugin.yml 2026-03-31 16:08:58 -06:00
BenCodez 5cc9650728 Update version in pom.xml and refactor VoteHelp, VoteToday, SignHandler
- Bump version to 26.1-R0.1-SNAPSHOT in pom.xml
- Remove unused NMSManager imports and legacy version checks
- Simplify placeholder chaining in VoteToday and VoteHelp
2026-03-28 21:11:32 -06:00
BenCodez 14f0197bc3 Refactor trigger votifier event handling to use ProxyVotifierEvent
- Removed BungeeVotifierEvent class and replaced its usage with
ProxyVotifierEvent.
- Added error handling for cases where the ProxyVotifierEvent class is
not found.
2026-03-21 17:38:59 -06:00
BenCodez 13e59f3c6b Remove unused commmand aliases plugin.yml 2026-03-21 12:36:40 -06:00
BenCodez 8f5ed0c95e Refactor PlayerVoteListener to enhance user validation process
Updated the user validation logic to utilize UserValidationResult,
providing more detailed feedback on validation outcomes. This change
improves the clarity of the validation process and ensures that
user checks are performed before full resolution.
2026-03-18 17:13:14 -06:00
BenCodez 1a6da05234 Refactor PlayerVoteListener to improve user validity checks
- Updated validity check logic to use properName instead of
creditedName.
- Maintained existing behavior for handling unjoined players based on
config settings.
- Added warning log for players who have not joined before voting.
2026-03-18 16:24:20 -06:00
BenCodez 8193c255c2 Update velocity version in pom.xml to 3.4.0 2026-03-17 17:08:04 -06:00
dependabot[bot] 3b664e7fa7 Bump org.mockito:mockito-junit-jupiter in /VotingPlugin
Bumps [org.mockito:mockito-junit-jupiter](https://github.com/mockito/mockito) from 5.15.2 to 5.23.0.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v5.15.2...v5.23.0)

---
updated-dependencies:
- dependency-name: org.mockito:mockito-junit-jupiter
  dependency-version: 5.23.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 06:41:06 +00:00
dependabot[bot] 11439f16da Bump org.apache.maven.plugins:maven-shade-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.6.1 to 3.6.2.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.6.1...maven-shade-plugin-3.6.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-version: 3.6.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 06:35:54 +00:00
dependabot[bot] 57ff828998 Bump me.clip:placeholderapi from 2.11.6 to 2.12.2 in /VotingPlugin
Bumps me.clip:placeholderapi from 2.11.6 to 2.12.2.

---
updated-dependencies:
- dependency-name: me.clip:placeholderapi
  dependency-version: 2.12.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 06:35:04 +00:00
dependabot[bot] 8bb0fec810 Bump org.junit.jupiter:junit-jupiter-api in /VotingPlugin
Bumps [org.junit.jupiter:junit-jupiter-api](https://github.com/junit-team/junit-framework) from 5.12.2 to 6.0.3.
- [Release notes](https://github.com/junit-team/junit-framework/releases)
- [Commits](https://github.com/junit-team/junit-framework/compare/r5.12.2...r6.0.3)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter-api
  dependency-version: 6.0.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 06:33:58 +00:00
dependabot[bot] de18c48c5f Bump org.bstats:bstats-velocity from 3.1.0 to 3.2.1 in /VotingPlugin
Bumps [org.bstats:bstats-velocity](https://github.com/Bastian/bStats-Metrics) from 3.1.0 to 3.2.1.
- [Release notes](https://github.com/Bastian/bStats-Metrics/releases)
- [Commits](https://github.com/Bastian/bStats-Metrics/compare/v3.1.0...v3.2.1)

---
updated-dependencies:
- dependency-name: org.bstats:bstats-velocity
  dependency-version: 3.2.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 06:33:31 +00:00
Ben 79f41ec605 Merge pull request #1489 from BenCodez/dependabot/maven/VotingPlugin/org.spongepowered-configurate-core-4.2.0
Bump org.spongepowered:configurate-core from 4.1.2 to 4.2.0 in /VotingPlugin
2026-03-15 16:14:16 -06:00
Ben 796978fbf2 Merge pull request #1487 from BenCodez/dependabot/maven/VotingPlugin/org.spongepowered-configurate-gson-4.2.0
Bump org.spongepowered:configurate-gson from 4.1.2 to 4.2.0 in /VotingPlugin
2026-03-15 16:14:06 -06:00
Ben bbd77d1686 Update Java version from 17 to 21 in workflow 2026-03-14 17:32:32 -06:00
BenCodez 00da2b575d Add unit tests for GitHubVoteSitePresetLoader and related classes
- Implement tests for finding vote site presets by exact and subdomain
matches.
- Verify behavior for unmatched URLs and ensure correct preset
retrieval.
- Add tests for PlaceholderDef deserialization and
VoteSiteJsonPresetManager functionality.
2026-03-14 17:14:44 -06:00
BenCodez 261187abc4 Add command to find vote site preset by URL
- Implemented a command to search for vote site presets based on a
provided URL.
- Enhanced error handling and logging for preset retrieval failures.
- Updated method visibility for better access in preset handling.
2026-03-14 17:09:39 -06:00
BenCodez 671b7c7add Add vote site preset management and configuration via GitHub API
- Introduced VoteSitePreset and related classes for handling presets.
- Implemented GitHubVoteSitePresetLoader to fetch presets from a GitHub
repository.
- Added VoteSitePresetSetupHandler for user interaction to select and
configure presets.
- Updated GUI configuration options to support new preset features.
- Enhanced placeholder definitions and matching information for presets.
2026-03-14 16:56:41 -06:00
BenCodez 279b71c4b5 Refactor value request handling to use SimpleAPI
- Replaced AdvancedCore value request imports with SimpleAPI
equivalents.
- Updated request methods to include plugin and dialog service for
better context.
- Cleaned up unused imports and improved type declarations for clarity.
2026-03-14 15:23:03 -06:00
BenCodez cd6289ab47 Fix votesite test 2026-03-14 11:50:30 -06:00
BenCodez bdb520af09 Refactor vote site validation and improve site key normalization
- Introduced a new method to validate vote site names for common issues.
- Enhanced normalization of vote site keys to replace spaces and dots
with underscores.
2026-03-14 11:46:51 -06:00
BenCodez 6891a79c66 Refactor vote site configuration handling and improve logging
- Simplify site name formatting by using regex to replace dots and
spaces.
- Return early if "VoteSites" configuration section is missing.
- Enhance logging to warn about invalid site names and spaces in site
names.
2026-03-12 18:05:40 -06:00
BenCodez 0e91c94cc8 Add support for directly defined caching for rewards in shop categories
Implemented functionality to add rewards directly defined in shop
categories. This includes methods for creating sections, saving data,
and setting values within the shop file configuration.
2026-03-10 20:35:52 -06:00
BenCodez f3d914e60c Remove unused MessageAPI import from VoteURL class 2026-03-09 19:18:06 -06:00
BenCodez a5758435f9 Refactor voting commands to use dialog method for user interactions
- Updated various command classes to replace GUI method with dialog
method.
- Added onDialog method implementations for better user experience.
- Configured shop settings to allow dialog usage for purchase
confirmations.
- Updated GUI and Shop YAML files to reflect new dialog options.
2026-03-08 20:04:38 -06:00
Ben e35bb0fe74 Update JDK version from 17 to 21 in workflow 2026-03-08 16:52:42 -06:00
BenCodez 1b96deb150 Update Maven configuration for compiler and Lombok plugin versions
- Replace deprecated Lombok Maven plugin with maven-compiler-plugin
- Upgrade Lombok version to 1.18.42 and set Java release to 21
2026-03-08 16:45:05 -06:00
BenCodez 1fe998afaf Update Java version in pom.xml and refactor VoteMilestonesManager test
- Changed maven.compiler.source, target, and release to 21 in pom.xml
- Replaced 'var' with explicit type for constructor in
VoteMilestonesManagerHandleVoteTest
2026-03-08 16:38:31 -06:00
BenCodez 4ea6abcd1a Implement VoteShop system with categories and item purchasing
- Added VoteShopManager to handle shop logic and item purchases.
- Introduced VoteShopCategory and VoteShopItem classes for structured
shop entries.
- Created GUI for VoteShop and VoteShopCategory to display items and
categories.
- Updated Shop.yml to support categories and new item definitions.
- Enhanced purchase validation and handling with
VoteShopPurchaseService.
2026-03-07 19:25:13 -06:00
BenCodez c49d040473 Refactor VoteToday and VotingPluginUser for improved readability
- Simplify placeholder handling in VoteToday for better clarity.
- Rename LastVotesList to lastVotesList for consistent naming
conventions.
- Enhance vote site validation logic in VotingPluginUser.
2026-03-07 17:05:43 -06:00
BenCodez 3cd181636b Add placeholders for shop and identifier in VoteShopConfirm gui title
- Introduced placeholders for shop and identifier to enhance inventory
display.
2026-03-07 14:58:19 -06:00
BenCodez 43494bef1d Add shop name placeholders to VoteShop and VoteShopConfirm
- Introduced placeholders for the shop name in both VoteShop and
VoteShopConfirm classes to enhance user experience.
2026-03-07 10:42:20 -06:00
BenCodez 6fe027223b Update configuration comments for AllowUnJoined
- Clarified the need to enable settings for proxy setups in Config.yml
- Removed outdated comment regarding PLUGINMESSAGING and SOCKETS in
bungeeconfig.yml
2026-03-03 17:09:05 -06:00
BenCodez d7dbcb4f44 Update JDBC driver requirements in configuration files
- Added detailed instructions for required JDBC drivers in Config.yml
and bungeeconfig.yml.
- Clarified default ports for MySQL/MariaDB and PostgreSQL.
- Included notes on driver installation and usage examples for better
clarity.
2026-02-17 16:24:12 -06:00
Ben f37a0671c7 Merge pull request #1493 from BenCodez/copilot/fix-javadoc-warnings-again
Add javadoc documentation for 56 missing methods across 15 files
2026-02-15 21:27:30 -06:00
copilot-swe-agent[bot]andBenCodez 47bdadfe27 Fix all 16 javadoc warnings in VoteParty.java
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 03:20:55 +00:00
copilot-swe-agent[bot]andBenCodez 10842a8d51 Fix 9 javadoc warnings in VoteMilestoneTotal enum
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 03:15:28 +00:00
copilot-swe-agent[bot]andBenCodez 8e1d0024db Fix 18 more javadoc warnings in event and reminder files
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 03:13:16 +00:00
copilot-swe-agent[bot]andBenCodez bd119f3ac1 Fix 13 javadoc warnings in 8 small files
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 03:11:10 +00:00
copilot-swe-agent[bot]andBenCodez d0a207606e Changes before error encountered
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 02:40:53 +00:00
copilot-swe-agent[bot]andCopilot e594b42000 Fix final batch of 100 javadoc warnings in 15 files
Add javadoc comments to all public/protected methods, constructors,
fields, and classes that were missing documentation:

- VoteCacheHandler.java (23 warnings)
- UserManager.java (19 warnings)
- TopVoterHandler.java (19 warnings)
- VelocityConfig.java (6 warnings)
- VoteHelp.java (5 warnings)
- VoteReminderCooldownStore.java (4 warnings)
- UserDataVoteReminderCooldownStore.java (4 warnings)
- TopVoterPlayer.java (4 warnings)
- VoteEventVelocity.java (3 warnings)
- VoteEventBungee.java (3 warnings)
- VelocityJsonVoteCache.java (2 warnings)
- VelocityJsonNonVotedPlayersCache.java (2 warnings)
- VoteGUI.java (2 warnings)
- VoteBest.java (2 warnings)
- VoteBroadcastType.java (2 warnings)

All changes are documentation-only with no code logic modifications.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-16 02:17:19 +00:00
copilot-swe-agent[bot]andCopilot f59b4cc0f1 Add javadoc comments to 9 files to fix 100 warnings
- ServerData.java: Added javadoc for 28 methods
- ShopFile.java: Added javadoc for class and 21 methods
- TopVoter.java: Added javadoc for enum, constants, and 13 methods
- SpecialRewardType.java: Added javadoc for enum, constants, and 2 methods
- SpecialRewardsConfig.java: Added javadoc for class and 11 methods
- TimeQueueHandler.java: Added javadoc for class and 7 methods
- SignHandler.java: Added javadoc for constructor and 4 methods
- SpecialRewards.java: Added javadoc for constructor and 3 methods
- Signs.java: Added javadoc for constructor

All warnings from these 9 files have been resolved.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-16 01:02:46 +00:00
copilot-swe-agent[bot]andCopilot 1aefbf77f5 Add javadoc comments to proxy cache table files
- Add javadoc to ProxyVoteCacheTable.java (26 warnings fixed)
- Add javadoc to ProxyOnlineVoteCacheTable.java (21 warnings fixed)
- Add javadoc to ProxyNonVotedPlayersTable.java (15 warnings fixed)
- Add javadoc to ProxyTimedVoteCacheTable.java (15 warnings fixed)

Total: Fixed 77 javadoc warnings across 4 files with no code logic changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-16 00:45:26 +00:00
copilot-swe-agent[bot]andBenCodez b84658d130 Fix javadoc warnings in 17 smaller files (23 warnings total)
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-16 00:38:12 +00:00
copilot-swe-agent[bot]andBenCodez 72348add0c Changes before error encountered
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-15 22:17:58 +00:00
copilot-swe-agent[bot]andCopilot b3c631db9c Add javadoc comments for 100 warnings in 11 files
Fixed javadoc warnings in:
- Config.java (1 warning)
- ConfigVoteSites.java (18 warnings)
- CoolDownCheck.java (15 warnings)
- GUI.java (9 warnings)
- DiscordHandler.java (5 warnings)
- INonVotedPlayersStorage.java (5 warnings)
- MultiProxyHandler.java (34 warnings)
- MultiProxyMethod.java (4 warnings)
- MultiProxyServerSocketConfiguration.java (4 warnings)
- DiscordWebhookPayloadBuilder.java (3 warnings)
- GsonDataNode.java (2 warnings)

All changes are documentation-only, no code logic modified.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-15 22:06:26 +00:00
copilot-swe-agent[bot]andBenCodez 46eb737296 Fix all 100 javadoc warnings across 16 files
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-15 21:59:26 +00:00
copilot-swe-agent[bot]andBenCodez 64c335bd3b Fix all 100 javadoc warnings
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-15 21:26:42 +00:00
copilot-swe-agent[bot] bde1f74223 Initial plan 2026-02-15 21:09:51 +00:00
Ben 42af35ae43 Merge pull request #1492 from BenCodez/copilot/fix-javadoc-warnings
Add missing javadoc comments to resolve build warnings
2026-02-15 14:43:54 -06:00
copilot-swe-agent[bot]andBenCodez ffa9234bf2 Add javadoc comments to fix all javadoc warnings
Co-authored-by: BenCodez <17074231+BenCodez@users.noreply.github.com>
2026-02-15 20:33:41 +00:00
BenCodez 398318d25f Bump version numbers to 4.2.0 in pom.xml
Updated the version from 4.1.2 to 4.2.0 for dependencies in the project.
2026-02-15 14:29:22 -06:00
copilot-swe-agent[bot] 498c323ce7 Initial plan 2026-02-15 20:27:53 +00:00
BenCodez eb73987ff0 Bump version number to 7.0.1-SNAPSHOT 2026-02-15 14:06:16 -06:00
BenCodez 0d7134e0e7 Handle invalid VoteStreakType gracefully and clean up configuration
- Added error handling for invalid VoteStreakType in VoteStreakHandler.
- Removed unused configuration entries from SpecialRewards.yml.
- Reformatted VoteStreakType declaration for consistency.
2026-02-14 17:49:20 -06:00
BenCodez 61ca4776e7 Update reload command in VotingPluginProxyCommand help text
Replaced the MySQL reload command with a more general reload command
to enhance user guidance in the plugin's command help section.
2026-02-14 14:38:50 -06:00
BenCodez 300f9fd928 Update version number to 7.0 2026-02-14 14:25:38 -06:00
BenCodez cc035116e3 Refactor VoteSite handling and improve test coverage
- Updated VoteMilestoneLimit to use TimeUnit for duration parsing.
- Removed unused VoteSiteTest class and added new tests for VoteSite and
VoteSiteManager.
- Introduced VoteSiteAdditionalTest and NextSiteTest for enhanced
coverage.
- Adjusted configuration handling in tests to ensure proper mocking.
2026-02-09 18:12:36 -06:00
BenCodez 583b510636 Refactor MySQL handling and improve reload functionality
- Consolidate MySQL configuration loading for Bungee and Velocity.
- Enhance reload process to support queued plugin messages during
reload.
- Update metrics handling and ensure proper shutdown of tasks.
- Improve logging for MySQL initialization and error handling.
2026-02-08 20:26:04 -06:00
BenCodez bfd3d69704 Remove unused import for SimplePie in VotingPluginBungee 2026-02-08 15:54:35 -06:00
BenCodez 8af2dc75cd Add bStats metrics for proxy broadcasts and vote logging configurations
- Implemented metrics for online mode, proxy broadcast settings, and
vote logging.
- Added custom charts to track proxy broadcast scope and offline modes.
- Introduced bucketing for counts and purge days to reduce high
cardinality in metrics.
2026-02-08 15:54:21 -06:00
BenCodez d85640ec3c Add bStats metrics for VoteBroadcast and VoteLogging configurations
- Implemented metrics for broadcast type and duration based on
VoteBroadcast settings.
- Added logging for VoteLogging metrics, including purge days and MySQL
usage.
- Enhanced configuration handling to ensure metrics are only registered
when applicable.
2026-02-08 14:35:49 -06:00
BenCodez a1def65f2d Refactor reward handling and update milestone commands
- Removed legacy cumulative reward handling and associated classes.
- Introduced new VoteMilestones handling with updated command structure.
- Updated configuration paths for milestones and vote milestones.
- Adjusted GUI elements to reflect new command names and structures.
2026-02-08 14:20:20 -06:00
BenCodez d7387a7182 Improve voting points messages and add configurable formats
- Updated user messages for voting points given and removed to use
  configurable formats from the config file.
- Added new configuration options in Config.java for
  PlayerGiven and PlayerRemoved messages.
- Updated Config.yml to include new message formats for admin vote
  point actions.
2026-02-07 20:37:37 -06:00
BenCodez 6d389c0408 Implement webhook support with Discord integration
- Added webhook management and execution classes for handling
  webhook requests asynchronously.
- Introduced configuration options for webhooks in Config.yml,
  including URL, method, headers, and retry settings.
- Implemented Discord-specific payload formatting and rate limit
  handling.
- Added utility classes for parsing webhook configurations and
  managing webhook definitions.
2026-02-06 19:24:07 -06:00
BenCodez 3a419b5250 Enhance user feedback for voting points changes
Added online user notifications when voting points are given or removed.
2026-02-06 16:08:44 -06:00
dependabot[bot] 0a5c731b55 Bump org.spongepowered:configurate-core in /VotingPlugin
Bumps [org.spongepowered:configurate-core](https://github.com/SpongePowered/Configurate) from 4.1.2 to 4.2.0.
- [Release notes](https://github.com/SpongePowered/Configurate/releases)
- [Commits](https://github.com/SpongePowered/Configurate/compare/4.1.2...4.2.0)

---
updated-dependencies:
- dependency-name: org.spongepowered:configurate-core
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-02 07:29:19 +00:00
dependabot[bot] eb6faba7a5 Bump org.spongepowered:configurate-gson in /VotingPlugin
Bumps [org.spongepowered:configurate-gson](https://github.com/SpongePowered/Configurate) from 4.1.2 to 4.2.0.
- [Release notes](https://github.com/SpongePowered/Configurate/releases)
- [Commits](https://github.com/SpongePowered/Configurate/compare/4.1.2...4.2.0)

---
updated-dependencies:
- dependency-name: org.spongepowered:configurate-gson
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-02 06:50:48 +00:00
BenCodez 6f828b6928 Refactor duration parsing to use TimeUnit for consistency
Updated duration parsing in BroadcastSettings and VoteRemindersManager
to utilize TimeUnit for improved clarity and consistency. This change
ensures that time values are handled uniformly across the codebase,
enhancing maintainability and reducing potential errors.
2026-02-01 15:44:45 -06:00
BenCodez c43eb697e3 Update dependencies and refactor configuration handling
- Replace deprecated configurate methods with updated ones
- Add relocations for new dependencies in pom.xml
- Update version to 3.4.0 and include new configurate dependencies
2026-02-01 15:41:06 -06:00
Ben 9917c85de4 Merge pull request #1483 from BenCodez/dependabot/maven/VotingPlugin/org.mockito-mockito-core-5.21.0
Bump org.mockito:mockito-core from 5.15.2 to 5.21.0 in /VotingPlugin
2026-02-01 13:43:13 -06:00
Ben 5796e0401b Merge pull request #1481 from BenCodez/dependabot/maven/VotingPlugin/com.discordsrv-discordsrv-1.30.4
Bump com.discordsrv:discordsrv from 1.30.3 to 1.30.4 in /VotingPlugin
2026-02-01 13:42:54 -06:00
Ben 3cc643e501 Merge pull request #1485 from BenCodez/dependabot/maven/VotingPlugin/org.projectlombok-lombok-1.18.42
Bump org.projectlombok:lombok from 1.18.38 to 1.18.42 in /VotingPlugin
2026-02-01 13:41:51 -06:00
BenCodez 99935133e1 Update delay configurations to use string format for time values 2026-01-31 17:49:38 -06:00
BenCodez cb90e607aa Add alias command filtering for VotingPlugin tab completion 2026-01-30 19:06:07 -06:00
BenCodez 0887810ce1 Remove PerServerMilestones configuration from BungeeSettings.yml 2026-01-29 16:20:44 -06:00
dependabot[bot] eef95ceea5 Bump org.projectlombok:lombok from 1.18.38 to 1.18.42 in /VotingPlugin
Bumps [org.projectlombok:lombok](https://github.com/projectlombok/lombok) from 1.18.38 to 1.18.42.
- [Changelog](https://github.com/projectlombok/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/projectlombok/lombok/compare/v1.18.38...v1.18.42)

---
updated-dependencies:
- dependency-name: org.projectlombok:lombok
  dependency-version: 1.18.42
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 07:40:18 +00:00
dependabot[bot] 1611fc6cd2 Bump org.mockito:mockito-core from 5.15.2 to 5.21.0 in /VotingPlugin
Bumps [org.mockito:mockito-core](https://github.com/mockito/mockito) from 5.15.2 to 5.21.0.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v5.15.2...v5.21.0)

---
updated-dependencies:
- dependency-name: org.mockito:mockito-core
  dependency-version: 5.21.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 06:55:57 +00:00
BenCodez 6591f3a625 Implement proxy broadcast routing configuration and logic 2026-01-24 18:11:08 -06:00
BenCodez b74820d1a8 Rename BungeeMessageData to VoteTotalsSnapshot and update data logic 2026-01-24 13:49:01 -06:00
BenCodez 3a1fdf1f35 Refactor MySQL messenger implementation on backend and proxy 2026-01-24 11:38:40 -06:00
BenCodez 00875b7e6f Improve service site management and update fetching logic 2026-01-24 11:12:57 -06:00
BenCodez 0bd2801825 Change proxy command to /votingpluginproxy
Refactor to remove BungeeVersion class and use
VotingPluginWire.SCHEMA_VERSION for versioning
2026-01-23 22:26:47 -06:00
BenCodez 71e7f5c753 Refactor proxy communication to use JsonEnvelope format exclusively 2026-01-23 22:16:23 -06:00
BenCodez 7392da2c04 Remove unused command aliases from plugin.yml 2026-01-20 16:03:10 -06:00
BenCodez e49c3f2476 Remove deprecated broadcast configuration options from Config.yml 2026-01-19 19:57:02 -06:00
dependabot[bot] e9e964ca7f Bump com.discordsrv:discordsrv from 1.30.3 to 1.30.4 in /VotingPlugin
Bumps com.discordsrv:discordsrv from 1.30.3 to 1.30.4.

---
updated-dependencies:
- dependency-name: com.discordsrv:discordsrv
  dependency-version: 1.30.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-19 07:59:26 +00:00
BenCodez 5f51ccb749 Bump version to 7.0-SNAPSHOT 2026-01-18 19:52:04 -06:00
BenCodez ce7ee1da3b Refactor VoteRemindersManager to use ScheduledExecutorService 2026-01-18 19:51:32 -06:00
BenCodez a8c57e1b78 Implement new vote reminder system, added config migrator 2026-01-18 19:08:49 -06:00
BenCodez 6c2ab687bf Enhance UUID lookup by normalizing offline player names in offline mode
Added command to convert to proper uuids
2026-01-12 18:00:48 -06:00
BenCodez 3af59056a7 Refactor vote broadcasting logic and migrate configuration handling 2026-01-12 17:41:51 -06:00
BenCodez dd3bcae15f Refactor ProxyOnlineVoteCacheTable to improve migration handling 2026-01-11 16:16:32 -06:00
BenCodez 499e4c9bd9 Refactor database migration handling 2026-01-11 16:12:25 -06:00
BenCodez 59bd7895d1 Refactor vote delay handling to use ParsedDuration 2026-01-11 14:39:55 -06:00
BenCodez be78d4a717 Refactor VoteSite handling to use VoteSiteManager 2026-01-11 13:24:22 -06:00
BenCodez 16fce5f132 Add commands to process votemilestones, remove older commands 2026-01-10 15:21:33 -06:00
BenCodez 0b1c192315 Refactor player login handling and improve UUID resolution 2026-01-10 12:43:48 -06:00
BenCodez 139122be62 Add unit tests for VoteStreaks 2026-01-10 10:52:29 -06:00
BenCodez de0f511e9e Move votestreak classes 2026-01-09 21:15:38 -06:00
BenCodez 73bba25977 Implement VoteMilestones system with configuration and logging support 2026-01-09 20:59:16 -06:00
BenCodez 83ca134649 Replace logger info calls with debug for Top Voters updates 2026-01-07 16:12:52 -06:00
BenCodez 06a74371e7 Disable failOnError and doclint in javadoc settings 2026-01-06 16:27:43 -06:00
BenCodez 365f08861f Rename field to fix javadoc 2026-01-06 16:21:25 -06:00
BenCodez 9fa553e417 Add method to update vote text in cache and database 2026-01-05 18:57:24 -06:00
BenCodez 8b2d3b7f63 Set default value of alwaysProcessAsyncPlaceholders to false 2026-01-04 18:44:01 -06:00
BenCodez 0f1ccea630 Add DiscordSRV check before executing Discord handler 2026-01-04 12:51:45 -06:00
BenCodez d116fa11f7 Add config option to always process async placeholders 2026-01-03 21:55:48 -06:00
BenCodez de75dff8df Don't check permission of offline player for not voted sites placeholder 2026-01-03 21:48:24 -06:00
BenCodez 1a5f8cdc0f Update Discord Top Voter message handling and improve formatting 2026-01-03 20:35:02 -06:00
BenCodez 9674921fe3 Add scheduled task to update Discord leaderboard every 10 minutes 2026-01-03 19:22:36 -06:00
BenCodez ff21a233fe Implement case-insensitive YML file handling with config option 2026-01-03 19:15:36 -06:00
BenCodez e19a50e64a Add server selection and stats for vote logs; Improve database handling 2026-01-03 12:27:47 -06:00
BenCodez d69d08461d Improve cooldown check logic and optimize user processing for vote sites 2026-01-03 08:59:41 -06:00
BenCodez d9aaeda303 Refactor user data handling to utilize UserDataFetchMode 2026-01-03 08:44:15 -06:00
BenCodez b3cc94965a Refactor VoteLogMysqlTable to enhance database column handling 2026-01-02 22:19:37 -06:00
BenCodez a1033555fb Refactor top voter loading and optimize database column types 2026-01-02 22:08:51 -06:00
BenCodez 8ef8aa26ff Refactor top voter handling and improve database configuration 2026-01-02 21:31:29 -06:00
BenCodez ad8699cf15 Move proxy mysql data to be under Database section
Will handle older style configs without issues
2026-01-02 20:25:55 -06:00
BenCodez 84705f29f5 Refactor user data handling to use callback-based forEachUserKeys
Improves performance
2026-01-02 18:42:29 -06:00
BenCodez 058fbdfd9e Improve handling of getting all user data with optimal method 2026-01-02 18:08:22 -06:00
BenCodez c3b7747cbc Cleanup configs of old options and improve overall look 2026-01-02 11:10:08 -06:00
BenCodez 2230bd45b9 Remove primary account handling from various components 2026-01-01 22:24:40 -06:00
BenCodez d7a35d845a Add server name handling to vote logging and update database schema 2026-01-01 22:12:38 -06:00
BenCodez 0e48aae457 Generate a new UUID for vote if not present in BungeeTextTotals 2026-01-01 21:36:29 -06:00
BenCodez 0c94ba89a5 Add Javadoc comment for return value in VoteLogMysqlTable 2025-12-31 20:15:02 -06:00
BenCodez 0b8ddaccdc Add Javadoc comments for parameters in VoteLogMysqlTable 2025-12-31 20:12:08 -06:00
BenCodez 68ee77eab3 Fix typo in VoteShopPurchaseLoggerListener registration 2025-12-31 20:09:16 -06:00
BenCodez 3c38932feb Add VoteShopPurchaseEvent and logging functionality for VoteShop 2025-12-31 20:09:02 -06:00
BenCodez 8594f0f51d Add new option NewMessageOnUpdate for discord top voters 2025-12-31 19:27:37 -06:00
BenCodez c77fdb1b69 Remove Jenkins site configuration and auto-download settings from config 2025-12-31 19:21:21 -06:00
BenCodez 236812bcac Enhance command output formatting for version info 2025-12-31 15:51:32 -06:00
BenCodez 0bb6d57494 Refactor update logic and improve performance in update task 2025-12-26 09:19:56 -06:00
Ben 5e5988d0b3 Merge pull request #1471 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-jar-plugin-3.5.0
Bump org.apache.maven.plugins:maven-jar-plugin from 3.4.2 to 3.5.0 in /VotingPlugin
2025-12-25 20:51:54 -06:00
Ben 77a190574d Merge pull request #1476 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-resources-plugin-3.4.0
Bump org.apache.maven.plugins:maven-resources-plugin from 3.3.1 to 3.4.0 in /VotingPlugin
2025-12-25 20:51:41 -06:00
Ben a8bf92786f Merge pull request #1477 from BenCodez/dependabot/maven/VotingPlugin/com.discordsrv-discordsrv-1.30.3
Bump com.discordsrv:discordsrv from 1.30.1 to 1.30.3 in /VotingPlugin
2025-12-25 20:51:30 -06:00
BenCodez 7510981f60 Add null check for VoteStreaks configuration section 2025-12-25 09:54:40 -06:00
BenCodez 5dfd9481bc Update nashorn-core dependency version to 15.7 2025-12-24 19:52:46 -06:00
BenCodez 403579d7bf Added PostgreSQL support 2025-12-24 19:42:50 -06:00
BenCodez d019e54860 Fix character encoding issues in ProxyVoteCacheTable comments 2025-12-24 13:50:08 -06:00
BenCodez 34b5b34a2f Fix character encoding issues in comments and message formatting 2025-12-24 12:55:10 -06:00
BenCodez 535e2201d5 Fix VoteParty error message formatting with color codes 2025-12-24 12:00:05 -06:00
BenCodez e305e6c97c Remove outdated comments from VoteStreakHandler 2025-12-24 11:55:40 -06:00
BenCodez 564de3d653 Update project encoding to UTF-8 for better compatibility 2025-12-24 11:52:28 -06:00
BenCodez 88050c903e Add vote logging tracking via vote id. Made vote logging all one command 2025-12-23 20:58:50 -06:00
BenCodez 901d900932 Add improved vote streak system 2025-12-22 19:28:02 -06:00
BenCodez d33063dd50 Refactor MySQL vote log schema: add auto-increment primary key 2025-12-21 16:04:00 -06:00
BenCodez a5d85f4cbc Refactor index creation logic to prevent duplicate index errors in MySQL 2025-12-20 21:17:46 -06:00
BenCodez 8e03f6e9c0 Fix vote logging condition to exclude Bungee events 2025-12-20 21:05:29 -06:00
BenCodez d761238eab Add admin GUI commands for vote logs: recent, player, service, and stats
Under /av votelog
2025-12-20 21:01:18 -06:00
BenCodez 7a4a7ec1b5 Implement automatic purging of old vote logs based on config settings 2025-12-20 20:09:48 -06:00
BenCodez fdb3793145 Add MySQL vote logging of all votes, more to be implemented 2025-12-20 20:01:47 -06:00
BenCodez 8c758a3410 Enable case-insensitive settings in configuration files 2025-12-13 17:07:30 -06:00
BenCodez 9564e00460 Bump version to 1.21.11-R0.1-SNAPSHOT in pom.xml 2025-12-13 16:44:59 -06:00
BenCodez 28d4f5482d Update comments in SpecialRewards.yml for clarity on command execution 2025-12-11 16:02:54 -06:00
dependabot[bot] 5fe9bd1377 Bump com.discordsrv:discordsrv from 1.30.1 to 1.30.3 in /VotingPlugin
Bumps com.discordsrv:discordsrv from 1.30.1 to 1.30.3.

---
updated-dependencies:
- dependency-name: com.discordsrv:discordsrv
  dependency-version: 1.30.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-08 06:18:11 +00:00
BenCodez 474553b4fe Refactor command execution to improve placeholder updates for points 2025-12-07 12:50:46 -06:00
BenCodez 609e31c16c Change Redis database index configuration from string to integer type 2025-12-02 16:22:35 -06:00
dependabot[bot] 71ed79b819 Bump org.apache.maven.plugins:maven-resources-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-resources-plugin](https://github.com/apache/maven-resources-plugin) from 3.3.1 to 3.4.0.
- [Release notes](https://github.com/apache/maven-resources-plugin/releases)
- [Commits](https://github.com/apache/maven-resources-plugin/compare/maven-resources-plugin-3.3.1...v3.4.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-resources-plugin
  dependency-version: 3.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-01 06:47:00 +00:00
BenCodez 7f1e1e1e72 Add Redis database index configuration support 2025-11-30 10:10:04 -06:00
BenCodez e22b1885ab Fix javadoc 2025-11-24 16:04:52 -06:00
BenCodez c3291e4f46 Add debug log for column type matching in ProxyMysqlUserTable 2025-11-23 16:22:57 -06:00
BenCodez 60a1428496 Implement non-voted players caching with MySQL support 2025-11-23 16:16:31 -06:00
BenCodez 17c098f1ee Add alias command filtering to hide commands when aliases are disabled 2025-11-22 17:58:23 -06:00
BenCodez fb78dc1313 Modify alias loading 2025-11-22 17:32:26 -06:00
BenCodez 382bba9990 Hide alias commands if loading is disabled 2025-11-22 17:01:28 -06:00
dependabot[bot] 8594cb8238 Bump org.apache.maven.plugins:maven-jar-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.4.2 to 3.5.0.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.4.2...maven-jar-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-jar-plugin
  dependency-version: 3.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-17 06:17:52 +00:00
BenCodez 1f3a4b84a1 Bump version number to 6.19.2-SNAPSHOT 2025-11-09 19:13:46 -06:00
BenCodez 17574f6c50 Bump version number to 6.19.1 2025-11-09 18:46:27 -06:00
BenCodez 60377deb44 Improve configuration comments for MySQL settings 2025-11-09 16:00:35 -06:00
Ben 34614e13fa Merge pull request #1469 from BoredManCodes/patch-1
Removed color codes from DiscordSRV messages
2025-11-03 16:17:07 -06:00
Trent Buckley bc98630388 Removed color codes from config yml 2025-11-04 09:12:04 +11:00
Trent Buckley 302cc980d8 Remove color codes from DiscordSRV messages 2025-11-04 09:10:46 +11:00
BenCodez 4342fc5458 Implement monthly reset for milestone data in proxy
Should reduce rare cases with counts being out of sync
2025-11-01 19:14:19 -06:00
BenCodez 90b981af7b Improve VoteCache null checks 2025-10-28 18:43:37 -06:00
BenCodez 32879956ec Refactor PlayerVoteListener to resolve Bedrock player names 2025-10-18 19:57:57 -06:00
Ben 2b166c7760 Update Maven CI workflow with permissions and comments 2025-10-13 08:10:14 -06:00
Ben 9848172a49 Update Maven workflow for JDK setup and build 2025-10-12 20:53:22 -06:00
BenCodez 9775d06ba9 Bump version number to 1.21.10-R0.1-SNAPSHOT 2025-10-12 20:51:10 -06:00
BenCodez 9584bc0e66 Prevent broadcasting for hidden vote sites 2025-10-10 21:05:25 -06:00
Ben 00ec202140 Merge pull request #1465 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-javadoc-plugin-3.12.0
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.11.3 to 3.12.0 in /VotingPlugin
2025-10-04 20:45:47 -06:00
Ben bd57f003dd Merge pull request #1463 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-shade-plugin-3.6.1
Bump org.apache.maven.plugins:maven-shade-plugin from 3.6.0 to 3.6.1 in /VotingPlugin
2025-10-04 20:45:39 -06:00
Ben 23788be684 Merge pull request #1462 from BenCodez/dependabot/maven/VotingPlugin/com.discordsrv-discordsrv-1.30.1
Bump com.discordsrv:discordsrv from 1.30.0 to 1.30.1 in /VotingPlugin
2025-10-04 20:45:27 -06:00
BenCodez 9b33b1cde7 Bump version numbers to 1.21.9-R0.1-SNAPSHOT and 1.21-R0.4 2025-10-04 20:32:53 -06:00
BenCodez 02fb353dac Fixed proxy votecache not using existing connection unless debug is on 2025-09-28 13:42:20 -06:00
dependabot[bot] a4c470887f Bump org.apache.maven.plugins:maven-javadoc-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.11.3 to 3.12.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.11.3...maven-javadoc-plugin-3.12.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-version: 3.12.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-22 06:09:54 +00:00
dependabot[bot] e844a1eb63 Bump org.apache.maven.plugins:maven-shade-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.6.0 to 3.6.1.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.6.0...v3.6.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-version: 3.6.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-15 06:38:19 +00:00
dependabot[bot] 1787595ea2 Bump com.discordsrv:discordsrv from 1.30.0 to 1.30.1 in /VotingPlugin
Bumps com.discordsrv:discordsrv from 1.30.0 to 1.30.1.

---
updated-dependencies:
- dependency-name: com.discordsrv:discordsrv
  dependency-version: 1.30.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-15 06:28:59 +00:00
BenCodez 79bea20039 Refactor vote caching: optimize cache handling 2025-09-14 14:37:53 -06:00
BenCodez 63905004b6 Remove commented-out code in VotingPluginProxyVoteCacheTest 2025-09-14 13:25:04 -06:00
BenCodez f326e2cbbb Refactor vote caching: streamline methods and improve performance 2025-09-11 19:04:17 -06:00
BenCodez 9f6edca531 Refactor proxy vote caching: remove VoteCache class 2025-09-11 17:45:16 -06:00
BenCodez 3e277a4a76 Update pom.xml to disable minimizeJar and add resource transformers 2025-09-06 17:58:06 -06:00
BenCodez 3b33e5e4a7 Adjust time calculation in PlaceHolders to account for timeWeekOffSet 2025-09-06 09:54:34 -06:00
BenCodez b5f35038fa Add support for timeWeekOffSet in Bungee and Velocity configurations 2025-09-06 09:52:02 -06:00
BenCodez b937d30213 Update shadedPattern in pom.xml to use simpleapi for Hikari 2025-09-05 15:52:58 -06:00
BenCodez d43cf53276 Remove unused documentation comments from vote cache table classes 2025-09-02 20:46:24 -06:00
BenCodez 6a7b677322 Fix casing for MySQL configuration in vote cache settings 2025-09-02 20:28:02 -06:00
BenCodez b309537f97 Add support for using mysql to handle proxy vote cache
Requires more testing
2025-09-02 20:25:43 -06:00
BenCodez 7e34dd89b8 Refactor player name retrieval to use proper casing from user manager 2025-08-31 14:30:31 -06:00
BenCodez 5dcc0a1b33 Improve player name retrieval to match casing from UUID cache 2025-08-31 14:04:12 -06:00
BenCodez 36f8b3fbe8 Update version number to 6.19.1-SNAPSHOT 2025-08-24 16:03:33 -06:00
BenCodez df298fd66c Temp revert version number for maven deploy 2025-08-24 16:00:05 -06:00
BenCodez c93aff6c20 Update version number to 6.19.1-SNAPSHOT 2025-08-24 15:57:21 -06:00
BenCodez b8acfe20ec Update version number to 6.19 2025-08-24 15:48:12 -06:00
BenCodez 110aaf096e Refactor player name retrieval to match casing from UUID cache 2025-08-24 13:30:53 -06:00
Ben 171975c3d3 Merge pull request #1457 from BenCodez/dependabot/maven/VotingPlugin/org.apache.maven.plugins-maven-javadoc-plugin-3.11.3
Bump org.apache.maven.plugins:maven-javadoc-plugin from 3.11.2 to 3.11.3 in /VotingPlugin
2025-08-18 18:47:52 -06:00
dependabot[bot] ac96d277c5 Bump org.apache.maven.plugins:maven-javadoc-plugin in /VotingPlugin
Bumps [org.apache.maven.plugins:maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.11.2 to 3.11.3.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.11.2...maven-javadoc-plugin-3.11.3)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-version: 3.11.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 09:18:02 +00:00
BenCodez b1ad952950 Add debug message for DiscordSRV leaderboard updates 2025-08-17 13:37:18 -06:00
BenCodez ca30bcb183 Fix clearing discord message id with command 2025-08-15 16:56:13 -06:00
BenCodez eecd975731 Add debug logging and minor changes for discord top voters 2025-08-13 15:52:53 -06:00
BenCodez aa55b10e50 Implement delay handling for global message sending on PLUGINMESSAGING
Added to handle cases where too many pluginmessages causes messages to
be skipped, subject to change
2025-08-10 14:16:08 -06:00
BenCodez 64f59f8195 Update WaitForUserOnline setting to true for consistent reward behavior 2025-08-10 13:09:43 -06:00
BenCodez a51e041430 Add command to clear Discord message ID for top voter
This will force a new discord message to be sent
2025-08-10 12:19:42 -06:00
BenCodez b39f768a46 Add support for multiple top voter types in DiscordSRV integration 2025-08-06 19:33:44 -06:00
BenCodez e98bc49add Parse placeholders on discord message reward 2025-08-05 17:00:00 -06:00
BenCodez 8b2209aa59 Attempt fixing player name casing in offline while player is offline 2025-08-03 15:02:21 -06:00
BenCodez 58a0e85d00 Prevent redundant updates to last vote time for a specific vote site 2025-08-03 13:31:53 -06:00
BenCodez 3febfa4056 Update vote times in all possible cases 2025-08-03 13:31:28 -06:00
BenCodez e5668c862a Fix player name casing in offline mode Bungee and Velocity proxies
Will attempt to correct while player is online
2025-08-01 16:26:54 -06:00
BenCodez fd4c6a3954 Restore bungeeVoteParty data on all methods on startup 2025-08-01 16:16:14 -06:00
BenCodez 9e9472680a Remove unused command aliases from plugin configuration 2025-07-31 16:55:56 -06:00
Ben cbecd7be30 Merge pull request #1452 from BenCodez/dependabot/maven/VotingPlugin/com.discordsrv-discordsrv-1.30.0
Bump com.discordsrv:discordsrv from 1.29.0 to 1.30.0 in /VotingPlugin
2025-07-28 16:26:03 -06:00
dependabot[bot] fcb1af77cf Bump com.discordsrv:discordsrv from 1.29.0 to 1.30.0 in /VotingPlugin
Bumps com.discordsrv:discordsrv from 1.29.0 to 1.30.0.

---
updated-dependencies:
- dependency-name: com.discordsrv:discordsrv
  dependency-version: 1.30.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-28 08:27:53 +00:00
BenCodez 5d9b5b7b6c Add configurable titles and rank display for DiscordSRV top voters 2025-07-26 20:26:04 -06:00
BenCodez d26d61a6f0 Fix formatting of vote count display in Discord embed 2025-07-24 15:55:15 -06:00
BenCodez 3f885aa358 Check DiscordSRV status on initialization 2025-07-22 18:45:19 -06:00
Ben d088f2e91a Merge pull request #1449 from BenCodez/dependabot/maven/VotingPlugin/com.discordsrv-discordsrv-1.29.0
Bump com.discordsrv:discordsrv from 1.26.0 to 1.29.0 in /VotingPlugin
2025-07-21 17:27:56 -06:00
dependabot[bot] a536c53dd9 Bump com.discordsrv:discordsrv from 1.26.0 to 1.29.0 in /VotingPlugin
Bumps com.discordsrv:discordsrv from 1.26.0 to 1.29.0.

---
updated-dependencies:
- dependency-name: com.discordsrv:discordsrv
  dependency-version: 1.29.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-21 08:06:43 +00:00
Ben 5d2d6f0763 Merge pull request #1440 from BenCodez/dependabot/maven/VotingPlugin/net.md-5-bungeecord-api-1.21-R0.3
Bump net.md-5:bungeecord-api from 1.21-R0.2 to 1.21-R0.3 in /VotingPlugin
2025-07-20 20:26:50 -06:00
BenCodez 0848ed83c2 Add DiscordSRV integration for top voter updates and injected reward 2025-07-20 16:08:08 -06:00
ben 1771fe0889 Update to 1.21.8 2025-07-19 21:23:35 -06:00
ben ce5b197e8b Don't always close inventory on VoteURL 2025-07-19 15:16:43 -06:00
ben 15489d9c64 Modify how slots are set in VoteURL GUI 2025-07-18 19:37:42 -06:00
ben 758632b5a5 Fix redis messages showing up in logs without debug enabled 2025-07-17 16:05:52 -06:00
ben 3dc45b6a63 Add extra items to VoteURL first 2025-07-15 19:02:55 -06:00
ben 26c9ad98bc Change MYSQL method to use MYSQL to communicate between servers
Works like PLUGINMESSAGING, SOCKETS, REDIS, or MQTT
2025-07-13 20:28:59 -06:00
BenCodez ee2531af1e Modify shutdown order 2025-07-06 16:16:16 -06:00
BenCodez 461e5f8413 Cancel more timers on velocity shutdown 2025-07-05 20:38:34 -06:00
BenCodez 1c5acbd1a1 Improve resource cleanup in VotingPluginProxy shutdown method
- Added socketHandler connection closure
- Added redisHandler resource cleanup
- Shutdown globalDataHandler if initialized
- Ensured proper cleanup of all handlers
- Maintained existing bungeeTimeChecker shutdown logic
- Set `enabled` to false after cleanup
2025-07-05 14:48:17 -06:00
BenCodez e855c01854 Stop timer on velocity shutdown 2025-07-05 08:57:30 -06:00
BenCodez aeec7d9d17 Shutdown bungeeTimeChecker during proxy disable process.
- Added `bungeeTimeChecker.shutdown()` in `VotingPluginProxy`.
- Ensures proper cleanup of `bungeeTimeChecker`.
- Prevents potential resource leaks during proxy shutdown.
- Maintains consistency in shutdown logic.
- Improves reliability of proxy disable functionality.
- Minor code enhancement for better resource management.
2025-07-04 15:46:30 -06:00
BenCodez 4861c041e4 Add ResetMilestonesMonthly to proxy 2025-07-01 08:58:23 -06:00
BenCodez d1c6752240 Update version number to 6.18.8-SNAPSHOT 2025-06-30 18:48:11 -06:00
dependabot[bot] 71ccf6a7b0 Bump net.md-5:bungeecord-api in /VotingPlugin
Bumps [net.md-5:bungeecord-api](https://github.com/SpigotMC/BungeeCord) from 1.21-R0.2 to 1.21-R0.3.
- [Commits](https://github.com/SpigotMC/BungeeCord/commits)

---
updated-dependencies:
- dependency-name: net.md-5:bungeecord-api
  dependency-version: 1.21-R0.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-16 06:57:36 +00:00
249 changed files with 36354 additions and 8407 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support documentation.
name: Java CI with Maven
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
permissions:
contents: write # required for dependency submission
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn -B -f VotingPlugin/pom.xml package
# Only submit dependency snapshot on push (not on pull_request)
- name: Submit Dependency Snapshot
if: github.event_name == 'push'
uses: advanced-security/maven-dependency-submission-action@v5
with:
directory: VotingPlugin # path to pom.xml
# optional: maven-args: "-DskipTests"
+2 -2
View File
@@ -16,9 +16,9 @@ jobs:
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
javadoc-branch: gh-pages
java-version: 17
java-version: 21
target-folder: ''
project: maven # or gradle
# subdirectories: moduleA moduleB #for subdirectories support, needs to be run with custom command
custom-command: mvn -f VotingPlugin/pom.xml deploy -P javadoc javadoc:aggregate
javadoc-source-folder: 'VotingPlugin/target/apidocs'
javadoc-source-folder: 'VotingPlugin/target/reports/apidocs'
+5
View File
@@ -0,0 +1,5 @@
---
description: Describe what this custom agent does and when to use it.
tools: []
---
Write instructions for this custom agent. These will guide Copilot on how to respond when this mode is selected.
+647 -614
View File
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,12 @@
// File: com/bencodez/votingplugin/BungeeHandler.java
package com.bencodez.votingplugin;
import java.io.File;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -21,13 +23,13 @@ import com.bencodez.advancedcore.api.time.TimeType;
import com.bencodez.advancedcore.api.user.UserStorage;
import com.bencodez.advancedcore.bungeeapi.globaldata.GlobalDataHandler;
import com.bencodez.advancedcore.bungeeapi.globaldata.GlobalMySQL;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.encryption.EncryptionHandler;
import com.bencodez.simpleapi.servercomm.codec.JsonEnvelope;
import com.bencodez.simpleapi.servercomm.global.GlobalMessageHandler;
import com.bencodez.simpleapi.servercomm.global.GlobalMessageListener;
import com.bencodez.simpleapi.servercomm.mqtt.MqttHandler;
import com.bencodez.simpleapi.servercomm.mqtt.MqttServerComm;
import com.bencodez.simpleapi.servercomm.mqtt.MqttHandler.MessageHandler;
import com.bencodez.simpleapi.servercomm.mysql.MySqlMessenger;
import com.bencodez.simpleapi.servercomm.pluginmessage.PluginMessageHandler;
import com.bencodez.simpleapi.servercomm.redis.RedisHandler;
import com.bencodez.simpleapi.servercomm.redis.RedisListener;
@@ -37,14 +39,17 @@ import com.bencodez.simpleapi.servercomm.sockets.SocketReceiver;
import com.bencodez.simpleapi.sql.data.DataValue;
import com.bencodez.simpleapi.sql.data.DataValueBoolean;
import com.bencodez.simpleapi.sql.mysql.config.MysqlConfigSpigot;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.proxy.BungeeMessageData;
import com.bencodez.votingplugin.proxy.BungeeMethod;
import com.bencodez.votingplugin.proxy.BungeeVersion;
import com.bencodez.votingplugin.proxy.VoteTotalsSnapshot;
import com.bencodez.votingplugin.proxy.VotingPluginWire;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
/**
* Handler for Bungee/proxy server integration.
*/
public class BungeeHandler implements Listener {
@Getter
private ClientHandler clientHandler;
@@ -78,13 +83,26 @@ public class BungeeHandler implements Listener {
private Thread redisThread;
@Getter
private MySqlMessenger backendMysqlMessenger;
@Getter
private MqttHandler mqttHandler;
/**
* Constructs a new BungeeHandler.
*
* @param plugin the main plugin instance
*/
public BungeeHandler(VotingPluginMain plugin) {
this.plugin = plugin;
}
/**
* Checks and processes global data from the global data handler.
*/
public void checkGlobalData() {
HashMap<String, DataValue> data = globalDataHandler.getExact(plugin.getBungeeSettings().getServer());
// plugin.debug(data.toString());
if (data.containsKey("ForceUpdate")) {
boolean b = checkGlobalDataTimeValue(data.get("ForceUpdate"));
@@ -119,15 +137,13 @@ public class BungeeHandler implements Listener {
}
}
/*
* @EventHandler public void onDateChange(DateChangedEvent event) { if
* (method.equals(BungeeMethod.PLUGINMESSAGING)) {
* plugin.getPluginMessaging().sendPluginMessage("timeupdate",
* plugin.getServerDataFile().getPrevMonth() + "//" +
* plugin.getServerDataFile().getPrevDay() + "//" +
* plugin.getServerDataFile().getPrevWeekDay()); } }
/**
* Checks global data for a time type change.
*
* @param type the time type to check
* @param data the global data map
* @return true if currently processing a time change
*/
public boolean checkGlobalDataTime(TimeType type, HashMap<String, DataValue> data) {
boolean isProcessing = false;
if (data.containsKey(type.toString())) {
@@ -150,13 +166,21 @@ public class BungeeHandler implements Listener {
plugin.debug("Detected time change from bungee: " + type.toString());
plugin.getTimeChecker().forceChanged(type, false, true, true);
globalDataHandler.setBoolean(plugin.getBungeeSettings().getServer(), type.toString(), false);
getGlobalMessageHandler().sendMessage("TimeChangeFinished",
"" + plugin.getBungeeSettings().getServer());
HashMap<String, Object> fields = new HashMap<>();
fields.put("server", plugin.getBungeeSettings().getServer());
sendSubChannel("TimeChangeFinished", fields);
}
}
return isProcessing;
}
/**
* Checks and extracts the boolean value from a DataValue.
*
* @param data the data value
* @return the boolean value
*/
public boolean checkGlobalDataTimeValue(DataValue data) {
if (data.isBoolean()) {
return data.getBoolean();
@@ -164,7 +188,14 @@ public class BungeeHandler implements Listener {
return Boolean.valueOf(data.getString());
}
/**
* Closes and cleans up all handlers and connections.
*/
public void close() {
if (backendMysqlMessenger != null) {
backendMysqlMessenger.shutdown();
}
if (socketHandler != null) {
socketHandler.closeConnection();
}
@@ -178,6 +209,9 @@ public class BungeeHandler implements Listener {
}
}
/**
* Loads and initializes the bungee handler with the configured method.
*/
public void load() {
plugin.debug("Loading bungee handler");
@@ -188,317 +222,194 @@ public class BungeeHandler implements Listener {
loadGlobalMysql();
globalMessageHandler = new GlobalMessageHandler() {
@Override
public void sendMessage(String subChannel, String... messageData) {
public void sendMessage(JsonEnvelope envelope) {
if (method.equals(BungeeMethod.MYSQL)) {
plugin.getPluginMessaging().sendPluginMessage(subChannel, messageData);
} else if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
plugin.getPluginMessaging().sendPluginMessage(subChannel, messageData);
} else if (method.equals(BungeeMethod.SOCKETS)) {
ArrayList<String> list = new ArrayList<>();
list.add(subChannel);
list.addAll(ArrayUtils.convert(messageData));
sendData(ArrayUtils.convert(list));
} else if (method.equals(BungeeMethod.REDIS)) {
ArrayList<String> list = new ArrayList<>();
list.add(subChannel);
list.addAll(ArrayUtils.convert(messageData));
redisHandler.sendMessage(plugin.getBungeeSettings().getRedisPrefix() + "VotingPlugin",
ArrayUtils.convert(list));
} else if (method.equals(BungeeMethod.MQTT)) {
ArrayList<String> list = new ArrayList<>();
list.add(subChannel);
list.addAll(ArrayUtils.convert(messageData));
try {
mqttHandler.publish(plugin.getBungeeSettings().getMqttPrefix() + "votingplugin/servers/proxy",
String.join(":", list));
backendMysqlMessenger.sendToProxy(envelope);
} catch (SQLException e) {
e.printStackTrace();
}
} else if (method.equals(BungeeMethod.PLUGINMESSAGING)) {
plugin.getPluginMessaging().sendEnvelope(envelope);
} else if (method.equals(BungeeMethod.SOCKETS)) {
sendEnvelopeSocket(envelope);
} else if (method.equals(BungeeMethod.REDIS)) {
redisHandler.publishEnvelope(plugin.getBungeeSettings().getRedisPrefix() + "VotingPlugin",
envelope);
} else if (method.equals(BungeeMethod.MQTT)) {
try {
mqttHandler.publishEnvelope(
plugin.getBungeeSettings().getMqttPrefix() + "votingplugin/servers/proxy", envelope);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
globalMessageHandler.addListener(new GlobalMessageListener("Vote") {
// ==========================
// Vote / VoteOnline (wire decode)
// ==========================
globalMessageHandler.addListener(new GlobalMessageListener(VotingPluginWire.SUB_VOTE) {
@Override
public void onReceive(ArrayList<String> args) {
if (args.size() > 8) {
int bungeeVersion = Integer.parseInt(args.get(8));
if (bungeeVersion != BungeeVersion.getPluginMessageVersion()) {
plugin.getLogger().warning("Incompatible version with bungee, please update all servers"
+ bungeeVersion + ":" + BungeeVersion.getPluginMessageVersion());
return;
}
String player = args.get(0);
String uuid = args.get(1);
String service = args.get(2);
long time = Long.parseLong(args.get(3));
plugin.debug("pluginmessaging vote received from " + player + "/" + uuid + " on " + service);
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), player);
boolean wasOnline = Boolean.valueOf(args.get(4));
BungeeMessageData text = new BungeeMessageData(args.get(6));
bungeeVotePartyCurrent = text.getVotePartyCurrent();
bungeeVotePartyRequired = text.getVotePartyRequired();
plugin.getPlaceholders().onBungeeVotePartyUpdate();
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
boolean setTotals = Boolean.valueOf(args.get(7));
user.cache();
boolean broadcast = true;
boolean bungeeBroadcast = false;
if (args.size() > 9) {
bungeeBroadcast = Boolean.valueOf(args.get(9));
}
int num = 1;
if (args.size() > 10) {
num = Integer.valueOf(args.get(10));
}
int numberOfVotes = 1;
if (args.size() > 11) {
numberOfVotes = Integer.valueOf(args.get(11));
}
if (!bungeeBroadcast) {
if (!plugin.getBungeeSettings().isBungeeBroadcast()
&& !plugin.getBungeeSettings().isDisableBroadcast()) {
if (wasOnline || plugin.getBungeeSettings().isBungeeBroadcastAlways()) {
if (plugin.getConfigFile().isFormatOnlyOneOfflineBroadcast() && !wasOnline) {
if (num == 1) {
user.offlineBroadcast(user, plugin.getBungeeSettings().isUseBungeecoord(),
numberOfVotes);
}
} else {
VoteSite site = plugin.getVoteSite(service, true);
if (site != null) {
site.broadcastVote(user, false);
broadcast = false;
} else {
plugin.getLogger().warning("No votesite for " + service);
}
}
}
}
} else {
broadcast = false;
}
user.bungeeVotePluginMessaging(service, time, text, !setTotals, wasOnline, broadcast, num);
if (plugin.getBungeeSettings().isPerServerPoints()) {
user.addPoints(plugin.getConfigFile().getPointsOnVote());
}
plugin.getSpecialRewards().bungeeAllSitesCheck(user, numberOfVotes, num);
if (Boolean.valueOf(args.get(5))) {
plugin.getServerData().addServiceSite(service);
}
} else {
plugin.getLogger().warning("Incompatible version with bungee, please update all servers");
}
public void onReceive(JsonEnvelope msg) {
handleWireVote(msg);
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VoteOnline") {
globalMessageHandler.addListener(new GlobalMessageListener(VotingPluginWire.SUB_VOTE_ONLINE) {
@Override
public void onReceive(ArrayList<String> args) {
if (args.size() > 8) {
int bungeeVersion = Integer.parseInt(args.get(8));
if (bungeeVersion != BungeeVersion.getPluginMessageVersion()) {
plugin.getLogger().warning("Incompatible version with bungee, please update all servers");
return;
}
String player = args.get(0);
String uuid = args.get(1);
String service = args.get(2);
long time = Long.parseLong(args.get(3));
BungeeMessageData text = new BungeeMessageData(args.get(6));
bungeeVotePartyCurrent = text.getVotePartyCurrent();
bungeeVotePartyRequired = text.getVotePartyRequired();
plugin.getPlaceholders().onBungeeVotePartyUpdate();
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
plugin.debug("pluginmessaging voteonline received from " + player + "/" + uuid + " on " + service);
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), player);
user.cache();
boolean setTotals = Boolean.valueOf(args.get(7));
boolean wasOnline = Boolean.valueOf(args.get(4));
boolean broadcast = true;
boolean bungeeBroadcast = false;
if (args.size() > 9) {
bungeeBroadcast = Boolean.valueOf(args.get(9));
}
int num = 1;
if (args.size() > 10) {
num = Integer.valueOf(args.get(10));
}
int numberOfVotes = 1;
if (args.size() > 11) {
numberOfVotes = Integer.valueOf(args.get(11));
}
if (!bungeeBroadcast) {
if (!plugin.getBungeeSettings().isBungeeBroadcast()
&& !plugin.getBungeeSettings().isDisableBroadcast()) {
if (wasOnline || plugin.getBungeeSettings().isBungeeBroadcastAlways()) {
if (plugin.getConfigFile().isFormatOnlyOneOfflineBroadcast() && !wasOnline) {
if (num == 1) {
user.offlineBroadcast(user, plugin.getBungeeSettings().isUseBungeecoord(),
numberOfVotes);
}
} else {
VoteSite site = plugin.getVoteSite(service, true);
if (site != null) {
site.broadcastVote(user, false);
broadcast = false;
} else {
plugin.getLogger().warning("No votesite for " + service);
}
}
}
}
} else {
broadcast = false;
}
user.bungeeVotePluginMessaging(service, time, text, !setTotals, wasOnline, broadcast, num);
if (plugin.getBungeeSettings().isPerServerPoints()) {
user.addPoints(plugin.getConfigFile().getPointsOnVote());
}
plugin.getSpecialRewards().bungeeAllSitesCheck(user, numberOfVotes, num);
if (Boolean.valueOf(args.get(5))) {
plugin.getServerData().addServiceSite(service);
}
} else {
plugin.getLogger().warning("Incompatible version with bungee, please update all servers");
}
public void onReceive(JsonEnvelope msg) {
handleWireVote(msg);
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VoteUpdate") {
globalMessageHandler.addListener(new GlobalMessageListener(VotingPluginWire.SUB_VOTE_UPDATE) {
@Override
public void onReceive(ArrayList<String> args) {
String player = args.get(0);
plugin.debug("pluginmessaging voteupdate received for " + player);
public void onReceive(JsonEnvelope msg) {
// Wire decode
VotingPluginWire.VoteUpdate v = VotingPluginWire.readVoteUpdate(msg);
String playerUuid = v.uuid;
if (playerUuid == null || playerUuid.isEmpty()) {
return;
}
plugin.debug("pluginmessaging voteupdate received for " + playerUuid + ": " + v.votePartyCurrent + "/"
+ v.votePartyRequired + " on " + v.service);
// Vote party cache update
if (v.votePartyCurrent >= 0 || bungeeVotePartyCurrent == -2) {
bungeeVotePartyCurrent = v.votePartyCurrent;
}
if (v.votePartyRequired >= 0 || bungeeVotePartyRequired == -2) {
bungeeVotePartyRequired = v.votePartyRequired;
}
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(player));
.getVotingPluginUser(UUID.fromString(playerUuid));
user.cache();
user.offVote();
if (args.size() > 3 && plugin.getBungeeSettings().isPerServerMilestones()) {
BungeeMessageData text = new BungeeMessageData(args.get(3));
plugin.getSpecialRewards().checkMilestone(user, text, true);
}
// Optional: update last vote time for a service
String service = v.service;
long time = v.time;
if (args.size() > 2) {
bungeeVotePartyCurrent = Integer.parseInt(args.get(1));
bungeeVotePartyRequired = Integer.parseInt(args.get(2));
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
if (service != null && !service.isEmpty() && time > 0) {
user.setTime(plugin.getVoteSiteManager().getVoteSite(service, true), time);
} else if (service != null && !service.isEmpty() && time <= 0
&& plugin.getBungeeSettings().isBungeeDebug()) {
plugin.debug("Invalid last vote time received from bungee: " + time);
}
plugin.setUpdate(true);
}
});
globalMessageHandler.addListener(new GlobalMessageListener("BungeeTimeChange") {
globalMessageHandler.addListener(new GlobalMessageListener(VotingPluginWire.SUB_BUNGEE_TIME_CHANGE) {
@Override
public void onReceive(ArrayList<String> args) {
public void onReceive(JsonEnvelope msg) {
checkGlobalData();
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VoteBroadcast") {
globalMessageHandler.addListener(new GlobalMessageListener(VotingPluginWire.SUB_VOTE_BROADCAST) {
@Override
public void onReceive(ArrayList<String> args) {
if (args.size() > 2) {
String uuid = args.get(0);
String service = args.get(2);
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), args.get(1));
VoteSite site = plugin.getVoteSite(service, true);
if (site != null) {
site.broadcastVote(user, false);
} else {
plugin.getLogger().warning("No votesite for " + service);
}
public void onReceive(JsonEnvelope msg) {
Map<String, String> f = msg.getFields();
final String uuidStr = nvl(f.get(VotingPluginWire.K_UUID));
final String playerNameRaw = nvl(f.get(VotingPluginWire.K_PLAYER));
final String service = nvl(f.get(VotingPluginWire.K_SERVICE));
if (uuidStr.isEmpty() || service.isEmpty()) {
return;
}
UUID javaUuid;
try {
javaUuid = UUID.fromString(uuidStr);
} catch (Exception e) {
plugin.getLogger().warning("Invalid UUID in VoteBroadcast: " + uuidStr);
return;
}
// New fields (May use later)
@SuppressWarnings("unused")
final long time = readLongSafe(f.get(VotingPluginWire.K_TIME), 0L);
@SuppressWarnings("unused")
final String totals = nvl(f.get(VotingPluginWire.K_TOTALS));
VoteSite voteSite = plugin.getVoteSiteManager()
.getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, service), true);
if (voteSite == null) {
plugin.getLogger().warning("No voting site with the service site: '" + service + "'");
return;
}
if (!voteSite.isEnabled()) {
plugin.debug("Votesite: " + voteSite.getKey() + " is not enabled (VoteBroadcast)");
return;
}
// Same user retrieval strategy: UUID + (possibly empty) name
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(javaUuid,
playerNameRaw);
// Keep cache/name current like normal vote path does
user.cache();
user.updateName(true);
// Same broadcast logic as PlayerVoteListener
if (plugin.getBroadcastHandler() == null) {
return;
}
if (user.isVanished()) {
plugin.debug("Not broadcasting vote for vanished user: " + user.getPlayerName());
return;
}
final boolean online = user.isOnline(); // same behavior as non-bungee vote path
plugin.getBroadcastHandler().broadcastVote(user.getJavaUUID(), user.getPlayerName(),
voteSite.getDisplayName(), online);
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VoteBroadcastOffline") {
@Override
public void onReceive(ArrayList<String> args) {
if (args.size() > 2) {
String uuid = args.get(0);
String votes = args.get(2);
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), args.get(1));
user.offlineBroadcast(user, false, Integer.parseInt(votes));
}
}
});
globalMessageHandler.addListener(new GlobalMessageListener("Status") {
@Override
public void onReceive(ArrayList<String> args) {
String server = args.get(0);
sendMessage(globalMessageHandler, "statusokay", server);
public void onReceive(JsonEnvelope msg) {
String server = nvl(msg.getFields().get("server"));
HashMap<String, Object> out = new HashMap<>();
out.put("server", server);
sendSubChannel("statusokay", out);
}
});
globalMessageHandler.addListener(new GlobalMessageListener("ServerName") {
globalMessageHandler.addListener(new GlobalMessageListener("ServerName") {
@Override
public void onReceive(ArrayList<String> args) {
String server = args.get(0);
public void onReceive(JsonEnvelope msg) {
String server = nvl(msg.getFields().get("server"));
if (!plugin.getOptions().getServer().equals(server)) {
plugin.getLogger().warning("Server name doesn't match in BungeeSettings.yml, should be " + server);
}
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VotePartyBungee") {
globalMessageHandler.addListener(new GlobalMessageListener("VotePartyBungee") {
@Override
public void onReceive(ArrayList<String> args) {
public void onReceive(JsonEnvelope msg) {
for (final String cmd : plugin.getBungeeSettings().getBungeeVotePartyGlobalCommands()) {
plugin.getBukkitScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
}
});
}
for (Player p : Bukkit.getOnlinePlayers()) {
@@ -506,21 +417,35 @@ public class BungeeHandler implements Listener {
}
}
});
globalMessageHandler.addListener(new GlobalMessageListener("VotePartyBroadcast") {
globalMessageHandler.addListener(new GlobalMessageListener("VotePartyBroadcast") {
@Override
public void onReceive(ArrayList<String> args) {
String broadcast = args.get(0);
public void onReceive(JsonEnvelope msg) {
String broadcast = nvl(msg.getFields().get("broadcast"));
MiscUtils.getInstance().broadcast(broadcast);
}
});
if (method.equals(BungeeMethod.MYSQL)) {
plugin.registerBungeeChannels(plugin.getBungeeSettings().getPluginMessagingChannel());
try {
backendMysqlMessenger = new MySqlMessenger("VotingPlugin",
plugin.getMysql().getMysql().getConnectionManager().getDataSource(),
MySqlMessenger.Mode.BACKEND, plugin.getOptions().getServer(), msg -> {
if (plugin.getBungeeSettings().isBungeeDebug()) {
plugin.debug("Proxy sent envelope: " + msg.envelope.getSubChannel() + " "
+ msg.envelope.getFields());
}
globalMessageHandler.onMessage(msg.envelope);
});
} catch (SQLException e) {
e.printStackTrace();
}
} else if (method.equals(BungeeMethod.REDIS)) {
redisHandler = new RedisHandler(plugin.getBungeeSettings().getRedisHost(),
plugin.getBungeeSettings().getRedisPort(), plugin.getBungeeSettings().getRedisUsername(),
plugin.getBungeeSettings().getRedisPassword()) {
plugin.getBungeeSettings().getRedisPassword(), plugin.getBungeeSettings().getRedisdbindex()) {
@Override
public void debug(String message) {
@@ -528,27 +453,17 @@ public class BungeeHandler implements Listener {
plugin.debug(message);
}
}
@Override
protected void onMessage(String channel, String[] message) {
plugin.getLogger().info(channel + ArrayUtils.makeStringList(ArrayUtils.convert(message)));
if (message.length > 0) {
ArrayList<String> list = new ArrayList<>();
for (int i = 1; i < message.length; i++) {
list.add(message[i]);
}
globalMessageHandler.onMessage(message[0], list);
}
}
};
redisThread = new Thread(new Runnable() {
redisThread = new Thread(new Runnable() {
@Override
public void run() {
if (plugin.isEnabled()) {
redisHandler.loadListener(
new RedisListener(redisHandler, plugin.getBungeeSettings().getRedisPrefix()
+ "VotingPlugin_" + plugin.getBungeeSettings().getServer()));
RedisListener listener = redisHandler.createEnvelopeListener(
plugin.getBungeeSettings().getRedisPrefix() + "VotingPlugin_"
+ plugin.getBungeeSettings().getServer(),
(ch, env) -> globalMessageHandler.onMessage(env));
redisHandler.loadListener(listener);
}
}
});
@@ -563,16 +478,12 @@ public class BungeeHandler implements Listener {
plugin.getPluginMessaging().setEncryptionHandler(encryptionHandler);
}
bungeeVotePartyCurrent = plugin.getServerData().getBungeeVotePartyCurrent();
bungeeVotePartyRequired = plugin.getServerData().getBungeeVotePartyRequired();
plugin.getPluginMessaging().setDebug(plugin.getBungeeSettings().isBungeeDebug());
plugin.getPluginMessaging().add(new PluginMessageHandler() {
@Override
public void onRecieve(String subChannel, ArrayList<String> args) {
globalMessageHandler.onMessage(subChannel, args);
public void onReceive(JsonEnvelope envelope) {
globalMessageHandler.onMessage(envelope);
}
});
@@ -584,7 +495,7 @@ public class BungeeHandler implements Listener {
plugin.getBungeeSettings().getBungeeServerPort(), encryptionHandler,
plugin.getBungeeSettings().isBungeeDebug());
socketHandler = new SocketHandler(plugin.getVersion(), plugin.getBungeeSettings().getSpigotServerHost(),
socketHandler = new SocketHandler("vp-socket", plugin.getBungeeSettings().getSpigotServerHost(),
plugin.getBungeeSettings().getSpigotServerPort(), encryptionHandler,
plugin.getBungeeSettings().isBungeeDebug()) {
@@ -595,10 +506,9 @@ public class BungeeHandler implements Listener {
};
socketHandler.add(new SocketReceiver() {
@Override
public void onReceive(String[] data) {
globalMessageHandler.onMessage(data[0], ArrayUtils.convertAndRemoveFirst(data));
public void onReceiveEnvelope(JsonEnvelope envelope) {
globalMessageHandler.onMessage(envelope);
}
});
@@ -608,38 +518,98 @@ public class BungeeHandler implements Listener {
if (id.isEmpty()) {
id = plugin.getOptions().getServer();
}
mqttHandler = new MqttHandler(new MqttServerComm(plugin.getBungeeSettings().getMqttClientID(),
plugin.getBungeeSettings().getMqttBrokerURL(), plugin.getBungeeSettings().getMqttUsername(),
plugin.getBungeeSettings().getMqttPassword()), 2);
mqttHandler.subscribe(plugin.getBungeeSettings().getMqttPrefix() + "votingplugin/servers/"
+ plugin.getOptions().getServer(), new MessageHandler() {
mqttHandler = new MqttHandler(new MqttServerComm(id, plugin.getBungeeSettings().getMqttBrokerURL(),
plugin.getBungeeSettings().getMqttUsername(), plugin.getBungeeSettings().getMqttPassword()), 2);
@Override
public void onMessage(String topic, String payload) {
String[] message = payload.split(":");
mqttHandler.subscribeEnvelopes(
plugin.getBungeeSettings().getMqttPrefix() + "votingplugin/servers/"
+ plugin.getOptions().getServer(),
(topic, envelope) -> globalMessageHandler.onMessage(envelope));
if (message.length > 0) {
globalMessageHandler.onMessage(message[0],
ArrayUtils.convertAndRemoveFirst(message));
}
}
});
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bungeeVotePartyCurrent = plugin.getServerData().getBungeeVotePartyCurrent();
bungeeVotePartyRequired = plugin.getServerData().getBungeeVotePartyRequired();
if (plugin.getOptions().getServer().equalsIgnoreCase("pleaseset")) {
plugin.getLogger().warning("Server name for bungee voting is not set, please set it");
}
}
@Getter
private MqttHandler mqttHandler;
private static long readLongSafe(String v, long def) {
if (v == null)
return def;
try {
return Long.parseLong(v);
} catch (Exception ignored) {
return def;
}
}
/**
* Wire vote handler (Vote + VoteOnline).
*/
private void handleWireVote(JsonEnvelope msg) {
// Strict schema check (wire uses envelope schema, not a "bungeeVersion" field)
int schema = msg.getSchema();
if (schema != VotingPluginWire.SCHEMA_VERSION) {
plugin.getLogger().warning("Incompatible version with bungee/proxy, please update all servers: " + schema
+ " != " + VotingPluginWire.SCHEMA_VERSION);
return;
}
VotingPluginWire.Vote v = VotingPluginWire.readVote(msg);
String uuidStr = v.uuid;
String player = v.player;
String service = v.service;
if (uuidStr == null || uuidStr.isEmpty()) {
return;
}
plugin.debug("wire vote received from " + player + "/" + uuidStr + " on " + service);
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuidStr),
player);
VoteTotalsSnapshot text = VoteTotalsSnapshot.parseStorage(v.totals == null ? "" : v.totals);
bungeeVotePartyCurrent = text.getVotePartyCurrent();
bungeeVotePartyRequired = text.getVotePartyRequired();
plugin.getServerData().setBungeeVotePartyCurrent(bungeeVotePartyCurrent);
plugin.getServerData().setBungeeVotePartyRequired(bungeeVotePartyRequired);
user.cache();
boolean bungeeBroadcast = v.broadcast;
// Wire has no "setTotals" flag; treat as always true (so doNotSetTotals =
// false)
boolean doNotSetTotals = false;
user.bungeeVotePluginMessaging(service, v.time, text, doNotSetTotals, v.wasOnline, bungeeBroadcast, v.num);
if (plugin.getBungeeSettings().isPerServerPoints()) {
user.addPoints(plugin.getConfigFile().getPointsOnVote());
}
if (v.manageTotals) {
plugin.getServerData().addServiceSite(service);
}
@SuppressWarnings("unused")
int _ignored = v.numberOfVotes;
}
/**
* Loads the global MySQL handler for cross-server data synchronization.
*/
public void loadGlobalMysql() {
if (plugin.getBungeeSettings().isGloblalDataEnabled()) {
if (timer != null) {
@@ -653,28 +623,27 @@ public class BungeeHandler implements Listener {
}
timer = Executors.newScheduledThreadPool(1);
timer.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
checkGlobalData();
}
}, 60, 10, TimeUnit.SECONDS);
timer.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
globalDataHandler.setString(plugin.getBungeeSettings().getServer(), "LastOnline",
"" + LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli());
}
}, 1, 60, TimeUnit.MINUTES);
if (globalDataHandler != null) {
globalDataHandler.getGlobalMysql().close();
}
if (plugin.getBungeeSettings().isGloblalDataUseMainMySQL()
&& plugin.getStorageType().equals(UserStorage.MYSQL)) {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", plugin.getMysql().getMysql()) {
@Override
public void debugEx(Exception e) {
plugin.debug(e);
@@ -704,7 +673,6 @@ public class BungeeHandler implements Listener {
globalDataHandler = new GlobalDataHandler(
new GlobalMySQL("VotingPlugin_GlobalData", new MysqlConfigSpigot(
plugin.getBungeeSettings().getData().getConfigurationSection("GlobalData"))) {
@Override
public void debugEx(Exception e) {
plugin.debug(e);
@@ -731,6 +699,7 @@ public class BungeeHandler implements Listener {
}
});
}
globalDataHandler.getGlobalMysql().alterColumnType("IgnoreTime", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("MONTH", "VARCHAR(5)");
globalDataHandler.getGlobalMysql().alterColumnType("WEEK", "VARCHAR(5)");
@@ -743,7 +712,23 @@ public class BungeeHandler implements Listener {
}
}
public void sendData(String... strings) {
clientHandler.sendMessage(strings);
private void sendEnvelopeSocket(JsonEnvelope envelope) {
if (clientHandler != null) {
clientHandler.sendEnvelope(envelope);
}
}
private void sendSubChannel(String subChannel, HashMap<String, Object> fields) {
JsonEnvelope.Builder b = JsonEnvelope.builder(subChannel).schema(VotingPluginWire.SCHEMA_VERSION);
if (fields != null) {
for (Map.Entry<String, Object> e : fields.entrySet()) {
b.put(e.getKey(), e.getValue());
}
}
globalMessageHandler.sendMessage(b.build());
}
private static String nvl(String s) {
return s == null ? "" : s;
}
}
File diff suppressed because it is too large. Load diff
@@ -2,24 +2,36 @@ package com.bencodez.votingplugin;
import java.util.concurrent.Callable;
import org.bukkit.configuration.ConfigurationSection;
import com.bencodez.simpleapi.metrics.BStatsMetrics;
/**
* Registers bStats charts for VotingPlugin.
* <p>
* Updated for VotingPlugin 7.0:
* <ul>
* <li>Broadcast: Always logs broadcast_type if VoteBroadcast.Type exists. If Type == NONE, ignores other broadcast
* settings.</li>
* <li>VoteLogging: Only logs VoteLogging charts when VoteLogging.Enabled is true.</li>
* <li>No "Unknown" values are emitted; charts are only registered when their data exists.</li>
* <li>VoteMilestones chart is bucketed to reduce cardinality.</li>
* </ul>
*/
public class VotingPluginMetrics {
public void load(VotingPluginMain plugin) {
BStatsMetrics metrics = new BStatsMetrics(plugin, 38);
/**
* Register bStats metrics.
*
* @param plugin VotingPlugin main instance
*/
public void load(final VotingPluginMain plugin) {
if (plugin == null) {
return;
}
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_firstvote", new Callable<String>() {
final BStatsMetrics metrics = new BStatsMetrics(plugin, 38);
@Override
public String call() throws Exception {
if (plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getFirstVoteRewardsPath())) {
return "True";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_everysite", new Callable<String>() {
@Override
@@ -31,32 +43,7 @@ public class VotingPluginMetrics {
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_allsites", new Callable<String>() {
@Override
public String call() throws Exception {
if (plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getAllSitesRewardPath())) {
return "True";
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_cumulative", new Callable<String>() {
@Override
public String call() throws Exception {
if (plugin.getSpecialRewardsConfig().getCumulativeVotes().size() == 0) {
return "False";
}
for (String cum : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
if (plugin.getSpecialRewardsConfig().getCumulativeRewardEnabled(Integer.parseInt(cum))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_voteparty", new Callable<String>() {
@Override
@@ -67,6 +54,7 @@ public class VotingPluginMetrics {
return "True";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("placeholder_cache_level", new Callable<String>() {
@Override
@@ -74,21 +62,16 @@ public class VotingPluginMetrics {
return plugin.getPlaceholders().getCacheLevel().toString();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_milestone", new Callable<String>() {
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_votemilestones", new Callable<String>() {
@Override
public String call() throws Exception {
if (plugin.getSpecialRewardsConfig().getMilestoneVotes().size() == 0) {
return "False";
}
for (String milestone : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
if (plugin.getSpecialRewardsConfig().getMilestoneRewardEnabled(Integer.parseInt(milestone))) {
return "True";
}
}
return "False";
int size = plugin.getVoteMilestonesManager().getConfig().getMilestones().size();
return bucketCount(size);
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_anysitereward", new Callable<String>() {
@Override
@@ -100,63 +83,15 @@ public class VotingPluginMetrics {
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_votestreakday", new Callable<String>() {
@Override
public String call() throws Exception {
for (String s : plugin.getSpecialRewardsConfig().getVoteStreakVotes("Day")) {
if (plugin.getSpecialRewardsConfig().getVoteStreakRewardEnabled("Day", s)
&& plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getVoteStreakRewardsPath("Day", s))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_votestreakweek", new Callable<String>() {
@Override
public String call() throws Exception {
for (String s : plugin.getSpecialRewardsConfig().getVoteStreakVotes("Week")) {
if (plugin.getSpecialRewardsConfig().getVoteStreakRewardEnabled("Week", s)
&& plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getVoteStreakRewardsPath("Week", s))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("extrarewards_votestreakmonth", new Callable<String>() {
@Override
public String call() throws Exception {
for (String s : plugin.getSpecialRewardsConfig().getVoteStreakVotes("Month")) {
if (plugin.getSpecialRewardsConfig().getVoteStreakRewardEnabled("Month", s)
&& plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
plugin.getSpecialRewardsConfig().getVoteStreakRewardsPath("Month", s))) {
return "True";
}
}
return "False";
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("numberofsites", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + plugin.getVoteSitesEnabled().size();
return "" + plugin.getVoteSiteManager().getVoteSitesEnabled().size();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("numberofrewards", new Callable<String>() {
@Override
@@ -164,6 +99,7 @@ public class VotingPluginMetrics {
return "" + plugin.getRewardHandler().getRewards().size();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("autocreatevotesites", new Callable<String>() {
@Override
@@ -172,6 +108,14 @@ public class VotingPluginMetrics {
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("config_onlinemode", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + plugin.getOptions().isOnlineMode();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("numberofusers", new Callable<String>() {
@Override
@@ -209,6 +153,7 @@ public class VotingPluginMetrics {
return plugin.getOptions().getStorageType().toString();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("DisableCheckOnWorldChange", new Callable<String>() {
@Override
@@ -216,13 +161,7 @@ public class VotingPluginMetrics {
return "" + plugin.getOptions().isDisableCheckOnWorldChange();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("votereminding_enabled", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + plugin.getConfigFile().isVoteRemindingEnabled();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("LoadTopVoter_Monthly", new Callable<String>() {
@Override
@@ -230,6 +169,7 @@ public class VotingPluginMetrics {
return "" + plugin.getConfigFile().isLoadTopVoterMonthly();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("LoadTopVoter_Weekly", new Callable<String>() {
@Override
@@ -237,6 +177,7 @@ public class VotingPluginMetrics {
return "" + plugin.getConfigFile().isLoadTopVoterWeekly();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("LoadTopVoter_Daily", new Callable<String>() {
@Override
@@ -244,6 +185,7 @@ public class VotingPluginMetrics {
return "" + plugin.getConfigFile().isLoadTopVoterDaily();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("bungeemethod", new Callable<String>() {
@Override
@@ -254,22 +196,8 @@ public class VotingPluginMetrics {
return "Disabled";
}
}));
if (plugin.getBungeeSettings().isUseBungeecoord()) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("bungeebroadcast", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + plugin.getBungeeSettings().isBungeeBroadcast();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("bungeebroadcastalways", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + plugin.getBungeeSettings().isBungeeBroadcastAlways();
}
}));
metrics.addCustomChart(new BStatsMetrics.SimplePie("perserverrewards", new Callable<String>() {
@Override
@@ -368,5 +296,188 @@ public class VotingPluginMetrics {
}
}));
}
/*
* ---------------------------------------------------------------------
* Broadcast metrics:
* - Always log broadcast_type if VoteBroadcast.Type exists (even if NONE)
* - If Type == NONE, ignore the rest of the broadcast settings
* ---------------------------------------------------------------------
*/
final ConfigurationSection root = safeConfig(plugin);
final ConfigurationSection voteBroadcast = getSection(root, "VoteBroadcast");
if (voteBroadcast != null && voteBroadcast.isString("Type")) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("broadcast_type", new Callable<String>() {
@Override
public String call() throws Exception {
return voteBroadcast.getString("Type");
}
}));
final String type = voteBroadcast.getString("Type", null);
if (type != null && !"NONE".equalsIgnoreCase(type)) {
if (voteBroadcast.isString("Duration")) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("broadcast_duration", new Callable<String>() {
@Override
public String call() throws Exception {
return voteBroadcast.getString("Duration");
}
}));
}
if (voteBroadcast.isInt("MaxSitesListed")) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("broadcast_max_sites_listed",
new Callable<String>() {
@Override
public String call() throws Exception {
return bucketMaxSites(voteBroadcast.getInt("MaxSitesListed"));
}
}));
}
}
}
/*
* ---------------------------------------------------------------------
* VoteLogging metrics:
* - Only log when VoteLogging.Enabled is true
* ---------------------------------------------------------------------
*/
final ConfigurationSection voteLogging = getSection(root, "VoteLogging");
if (voteLogging != null && voteLogging.getBoolean("Enabled", false)) {
if (voteLogging.isInt("PurgeDays")) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("votelogging_purgedays", new Callable<String>() {
@Override
public String call() throws Exception {
return bucketPurgeDays(voteLogging.getInt("PurgeDays"));
}
}));
}
if (voteLogging.isBoolean("UseMainMySQL")) {
metrics.addCustomChart(new BStatsMetrics.SimplePie("votelogging_usemainmysql", new Callable<String>() {
@Override
public String call() throws Exception {
return "" + voteLogging.getBoolean("UseMainMySQL");
}
}));
}
}
}
/**
* Safely gets the root configuration section.
*
* @param plugin plugin instance
* @return root config section, or null if inaccessible
*/
private ConfigurationSection safeConfig(final VotingPluginMain plugin) {
try {
return plugin.getConfigFile().getData();
} catch (Exception ignored) {
return null;
}
}
/**
* Gets a child section safely.
*
* @param root root section
* @param key child key
* @return child section or null
*/
private ConfigurationSection getSection(final ConfigurationSection root, final String key) {
if (root == null) {
return null;
}
try {
return root.getConfigurationSection(key);
} catch (Exception ignored) {
return null;
}
}
/**
* Buckets a milestone count to reduce bStats cardinality.
*
* @param count count
* @return bucket string
*/
private String bucketCount(final int count) {
if (count <= 0) {
return "0";
}
if (count == 1) {
return "1";
}
if (count <= 5) {
return "2-5";
}
if (count <= 10) {
return "6-10";
}
if (count <= 25) {
return "11-25";
}
if (count <= 50) {
return "26-50";
}
if (count <= 100) {
return "51-100";
}
return ">100";
}
/**
* Buckets MaxSitesListed to reduce bStats cardinality.
*
* @param maxSites max sites listed
* @return bucket string
*/
private String bucketMaxSites(final int maxSites) {
if (maxSites <= 0) {
return "0";
}
if (maxSites <= 5) {
return "1-5";
}
if (maxSites <= 10) {
return "6-10";
}
if (maxSites <= 25) {
return "11-25";
}
return ">25";
}
/**
* Buckets purge days to reduce bStats cardinality.
*
* @param purgeDays purge days
* @return bucket string
*/
private String bucketPurgeDays(final int purgeDays) {
if (purgeDays < 0) {
return "disabled";
}
if (purgeDays == 0) {
return "0";
}
if (purgeDays <= 7) {
return "1-7";
}
if (purgeDays <= 30) {
return "8-30";
}
if (purgeDays <= 90) {
return "31-90";
}
if (purgeDays <= 365) {
return "91-365";
}
return ">365";
}
}
@@ -0,0 +1,126 @@
package com.bencodez.votingplugin.broadcast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
/**
* Defines HOW vote broadcasts are rendered.
*
* Terminology:
* - BroadcastMsg : used when EXACTLY ONE item exists (single-site vote)
* - Header : used ONCE when MULTIPLE items exist (batch/interval)
* - ListLine : used ONCE PER ITEM when MULTIPLE items exist
*
* Placeholders (always available):
* - %player% : player name (or "Server" for interval summaries)
* - %site% : the current site/item for this line
* - %sites_count% : number of items in the list
* - %sites% : csv of items in the list
* - %reason% : internal reason string ("vote", "batch", "interval", etc)
*
* Extra context placeholders (INTERVAL_SUMMARY_GLOBAL):
* - %players% / %numberofplayers%
* - %sites% / %numberofsites% (note: %sites% is csv; %numberofsites% is count)
*/
public final class BroadcastFormat {
private final String broadcastMsg;
private final String header;
private final String listLine;
/**
* Constructor for BroadcastFormat.
*
* @param broadcastMsg the broadcast message template
* @param header the header template
* @param listLine the list line template
*/
public BroadcastFormat(String broadcastMsg, String header, String listLine) {
this.broadcastMsg = broadcastMsg == null ? "" : broadcastMsg;
this.header = header == null ? "" : header;
this.listLine = listLine == null ? "" : listLine;
}
/**
* Render the broadcast with player name, items, and reason.
*
* @param playerName the player name
* @param items the list of items
* @param reason the reason string
* @return the rendered list of strings
*/
public List<String> render(String playerName, List<String> items, String reason) {
return render(playerName, items, reason, Collections.<String, String>emptyMap());
}
/**
* Render the broadcast with player name, items, reason, and context.
*
* @param playerName the player name
* @param items the list of items
* @param reason the reason string
* @param context additional context placeholders
* @return the rendered list of strings
*/
public List<String> render(String playerName, List<String> items, String reason, Map<String, String> context) {
List<String> output = new ArrayList<String>();
int count = items == null ? 0 : items.size();
String csv = "";
if (count > 0) {
StringJoiner joiner = new StringJoiner(", ");
for (String s : items) {
if (s != null && !s.isEmpty()) {
joiner.add(s);
}
}
csv = joiner.toString();
}
// SINGLE ITEM → BroadcastMsg
if (count == 1 && !broadcastMsg.isEmpty()) {
output.add(apply(broadcastMsg, playerName, items.get(0), count, csv, reason, context));
return output;
}
// MULTI ITEM → Header + ListLine per item
if (!header.isEmpty()) {
output.add(apply(header, playerName, "", count, csv, reason, context));
}
if (count > 0 && !listLine.isEmpty()) {
for (String s : items) {
output.add(apply(listLine, playerName, s, count, csv, reason, context));
}
}
return output;
}
private String apply(String template,
String player,
String item,
int count,
String csv,
String reason,
Map<String, String> context) {
String out = template
.replace("%player%", player == null ? "" : player)
.replace("%site%", item == null ? "" : item)
.replace("%sites_count%", String.valueOf(count))
.replace("%sites%", csv == null ? "" : csv)
.replace("%reason%", reason == null ? "" : reason);
if (context != null && !context.isEmpty()) {
for (Map.Entry<String, String> e : context.entrySet()) {
out = out.replace("%" + e.getKey() + "%", e.getValue());
}
}
return out;
}
}
@@ -1,76 +1,443 @@
package com.bencodez.votingplugin.broadcast;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.misc.MiscUtils;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.simpleapi.time.ParsedDuration;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
public class BroadcastHandler {
private VotingPluginMain plugin;
private ScheduledExecutorService timer;
ConcurrentLinkedQueue<String> votedPlayers = new ConcurrentLinkedQueue<>();
/**
* Core broadcast logic.
*
* Decides WHEN to broadcast and builds lines/messages. Uses your existing
* "eligible online players" behavior (disable broadcast respected).
*
* NOTE: Backend servers only.
*/
public final class BroadcastHandler {
public BroadcastHandler(VotingPluginMain plugin, int delay) {
private final VotingPluginMain plugin;
/**
* Only used for day-boundary logic (FIRST_VOTE_OF_DAY).
*/
private final ZoneId zoneId;
private volatile BroadcastSettings settings;
// Per-player cooldown tracking
private final ConcurrentHashMap<UUID, Instant> lastBroadcastAt = new ConcurrentHashMap<UUID, Instant>();
// Batch window tracking
private final ConcurrentHashMap<UUID, LinkedHashSet<String>> pendingSites = new ConcurrentHashMap<UUID, LinkedHashSet<String>>();
private final ConcurrentHashMap<UUID, BukkitTask> pendingFlush = new ConcurrentHashMap<UUID, BukkitTask>();
// First vote of day tracking
private final ConcurrentHashMap<UUID, LocalDate> firstVoteDay = new ConcurrentHashMap<UUID, LocalDate>();
// Interval summary tracking (uuid -> set of sites during interval)
private final ConcurrentHashMap<UUID, LinkedHashSet<String>> intervalSites = new ConcurrentHashMap<UUID, LinkedHashSet<String>>();
private volatile BukkitTask intervalTask;
/**
* Constructs a new BroadcastHandler.
*
* @param plugin the main plugin instance
* @param settings the broadcast settings
* @param zoneId the time zone ID, or null to use system default
*/
public BroadcastHandler(VotingPluginMain plugin, BroadcastSettings settings, ZoneId zoneId) {
this.plugin = plugin;
schedule(delay);
this.settings = settings;
this.zoneId = zoneId == null ? ZoneId.systemDefault() : zoneId;
rescheduleIntervalIfNeeded();
}
public void check() {
int size = votedPlayers.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
votedPlayers.poll();
/**
* Updates the broadcast settings and reschedules interval task if needed.
*
* @param settings the new broadcast settings
*/
public void setSettings(BroadcastSettings settings) {
this.settings = settings;
rescheduleIntervalIfNeeded();
}
/**
* Call whenever a vote is received.
*
* @param uuid player's uuid
* @param playerName player name (optional; if null/empty, resolved from Bukkit)
* @param siteName vote site name (display name)
* @param wasOnline whether the player was online when the vote was received
*/
public void broadcastVote(UUID uuid, String playerName, String siteName, boolean wasOnline) {
BroadcastSettings s = settings;
if (s == null || s.isDisabled()) {
return;
}
// Always collect for interval summaries (even if Type isn't interval right
// now).
recordInterval(uuid, siteName);
String name = playerName == null || playerName.isEmpty() ? resolveName(uuid) : playerName;
VoteBroadcastType type = s.getType();
// New: types that only broadcast if the voting player is online
if (type == VoteBroadcastType.EVERY_VOTE_ONLINE_ONLY) {
if (!wasOnline) {
return;
}
String bc = MessageAPI.colorize(plugin.getConfigFile().getFormatAlternateBroadcastBroadcast());
String playersText = "";
while (!votedPlayers.isEmpty()) {
playersText += votedPlayers.remove();
if (!votedPlayers.isEmpty()) {
playersText += ", ";
}
}
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("numberofplayers", "" + size);
placeholders.put("players", playersText);
bc = PlaceholderUtils.replacePlaceHolder(bc, placeholders);
ArrayList<Player> players = new ArrayList<>();
for (Player p : Bukkit.getOnlinePlayers()) {
if (!plugin.getVotingPluginUserManager().getVotingPluginUser(p).getDisableBroadcast()) {
players.add(p);
}
broadcastNow(name, single(siteName), "vote_online_only", null);
return;
}
if (type == VoteBroadcastType.EVERY_VOTE) {
broadcastNow(name, single(siteName), "vote", null);
} else if (type == VoteBroadcastType.COOLDOWN_PER_PLAYER) {
if (checkAndMarkCooldown(uuid, s.getDuration())) {
broadcastNow(name, single(siteName), "cooldown", null);
}
MiscUtils.getInstance().broadcast(bc, players);
} else if (type == VoteBroadcastType.BATCH_WINDOW_PER_PLAYER) {
bufferBatch(uuid, name, siteName, s.getDuration());
} else if (type == VoteBroadcastType.FIRST_VOTE_OF_DAY) {
if (markFirstVoteOfDay(uuid)) {
broadcastNow(name, single(siteName), "first_day", null);
}
} else if (type == VoteBroadcastType.INTERVAL_SUMMARY_GLOBAL) {
// handled by scheduled task
}
}
public void onVote(String player) {
votedPlayers.add(player);
}
/*
* ======================= Broadcast helpers =======================
*/
public void schedule(int delay) {
if (timer != null) {
timer.shutdownNow();
timer = Executors.newScheduledThreadPool(1);
private void broadcastNow(String playerName, List<String> sites, String reason, Map<String, String> extraContext) {
BroadcastSettings s = settings;
if (s == null || s.isDisabled()) {
return;
}
List<String> cleaned = applyMaxSites(sites, s);
cleaned.sort(new Comparator<String>() {
@Override
public int compare(String a, String b) {
String aa = a == null ? "" : a.toLowerCase(Locale.ROOT);
String bb = b == null ? "" : b.toLowerCase(Locale.ROOT);
return aa.compareTo(bb);
}
});
List<String> lines;
if (extraContext == null) {
lines = s.getFormat().render(playerName, cleaned, reason);
} else {
timer = Executors.newScheduledThreadPool(1);
lines = s.getFormat().render(playerName, cleaned, reason, extraContext);
}
timer.scheduleWithFixedDelay(new Runnable() {
for (String line : lines) {
broadcastToEligiblePlayers(line);
}
}
/**
* Your reliable broadcast style: - only sends to online players - respects
* per-player disable broadcast toggle - runs PlaceholderAPI style per-player
* placeholders (if your PlaceholderUtils does) - supports %newline% / %NewLine%
* splitting
*/
private void broadcastToEligiblePlayers(String broadcastMsg) {
if (broadcastMsg == null || broadcastMsg.isEmpty()) {
return;
}
ArrayList<Player> players = new ArrayList<Player>();
for (Player p : Bukkit.getOnlinePlayers()) {
VotingPluginUser u = plugin.getVotingPluginUserManager().getVotingPluginUser(p);
if (u != null && !u.getDisableBroadcast()) {
players.add(p);
}
}
// If you prefer your manual loop, keep it here (not in main)
MiscUtils.getInstance().broadcast(broadcastMsg, players);
Bukkit.getServer().getConsoleSender().sendMessage(MessageAPI.colorize(broadcastMsg));
}
/*
* ======================= Cooldown logic (fixed millis) =======================
*/
private boolean checkAndMarkCooldown(UUID uuid, ParsedDuration cooldown) {
if (cooldown == null || cooldown.isEmpty()) {
return true;
}
Instant now = Instant.now();
Instant last = lastBroadcastAt.get(uuid);
if (last == null) {
lastBroadcastAt.put(uuid, now);
return true;
}
Instant next = cooldown.addTo(last);
if (!now.isBefore(next)) {
lastBroadcastAt.put(uuid, now);
return true;
}
return false;
}
/*
* ======================= Batch window logic (fixed millis)
* =======================
*/
private void bufferBatch(UUID uuid, String playerName, String siteName, ParsedDuration window) {
if (siteName != null && !siteName.isEmpty()) {
LinkedHashSet<String> set = pendingSites.get(uuid);
if (set == null) {
LinkedHashSet<String> created = new LinkedHashSet<String>();
set = pendingSites.putIfAbsent(uuid, created);
if (set == null) {
set = created;
}
}
synchronized (set) {
set.add(siteName);
}
}
if (!pendingFlush.containsKey(uuid)) {
BukkitTask task = scheduleBatchFlush(uuid, playerName, window);
BukkitTask prev = pendingFlush.putIfAbsent(uuid, task);
if (prev != null) {
task.cancel();
}
}
}
private BukkitTask scheduleBatchFlush(final UUID uuid, final String playerName, ParsedDuration window) {
long delayMs = window == null ? 1L : window.delayMillisFromNow();
long ticks = Math.max(1L, delayMs / 50L);
return Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
check();
try {
flushBatch(uuid, playerName);
} finally {
pendingFlush.remove(uuid);
}
}
}, 60, 60 * delay, TimeUnit.SECONDS);
}, ticks);
}
private void flushBatch(UUID uuid, String playerName) {
Set<String> set = pendingSites.remove(uuid);
if (set == null || set.isEmpty()) {
return;
}
List<String> list;
synchronized (set) {
list = new ArrayList<String>(set);
}
broadcastNow(playerName, list, "batch", null);
}
/*
* ======================= First vote of day (calendar) =======================
*/
private boolean markFirstVoteOfDay(UUID uuid) {
LocalDate today = LocalDate.now(zoneId);
LocalDate last = firstVoteDay.putIfAbsent(uuid, today);
if (last == null) {
return true;
}
if (!last.equals(today)) {
firstVoteDay.put(uuid, today);
return true;
}
return false;
}
/*
* ======================= Interval summary =======================
*/
private void rescheduleIntervalIfNeeded() {
if (intervalTask != null) {
intervalTask.cancel();
intervalTask = null;
}
BroadcastSettings s = settings;
if (s == null || s.getType() != VoteBroadcastType.INTERVAL_SUMMARY_GLOBAL) {
return;
}
long delayMs = s.getDuration() == null ? 1L : s.getDuration().delayMillisFromNow();
long ticks = Math.max(1L, delayMs / 50L);
intervalTask = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
broadcastIntervalSummary();
}
}, ticks, ticks);
}
private void recordInterval(UUID uuid, String siteName) {
if (siteName == null || siteName.isEmpty()) {
return;
}
LinkedHashSet<String> set = intervalSites.get(uuid);
if (set == null) {
LinkedHashSet<String> created = new LinkedHashSet<String>();
set = intervalSites.putIfAbsent(uuid, created);
if (set == null) {
set = created;
}
}
synchronized (set) {
set.add(siteName);
}
}
/**
* Interval summary supports extra context placeholders: - %players% /
* %numberofplayers% - %sites% / %numberofsites%
*/
private void broadcastIntervalSummary() {
BroadcastSettings s = settings;
if (s == null || s.isDisabled() || s.getType() != VoteBroadcastType.INTERVAL_SUMMARY_GLOBAL) {
return;
}
ConcurrentHashMap<UUID, LinkedHashSet<String>> snapshot = new ConcurrentHashMap<UUID, LinkedHashSet<String>>(
intervalSites);
intervalSites.clear();
if (snapshot.isEmpty()) {
return;
}
List<String> entries = new ArrayList<String>();
List<String> players = new ArrayList<String>();
LinkedHashSet<String> uniqueSites = new LinkedHashSet<String>();
for (Map.Entry<UUID, LinkedHashSet<String>> entry : snapshot.entrySet()) {
LinkedHashSet<String> siteSet = entry.getValue();
if (siteSet == null || siteSet.isEmpty()) {
continue;
}
String name = resolveName(entry.getKey());
players.add(name);
int siteCount;
synchronized (siteSet) {
siteCount = siteSet.size();
for (String site : siteSet) {
if (site != null && !site.isEmpty()) {
uniqueSites.add(site);
}
}
}
entries.add(name + " (" + siteCount + ")");
}
if (entries.isEmpty()) {
return;
}
String playersCsv = join(players);
String sitesCsv = join(new ArrayList<String>(uniqueSites));
ConcurrentHashMap<String, String> context = new ConcurrentHashMap<String, String>();
context.put("players", playersCsv);
context.put("numberofplayers", String.valueOf(players.size()));
context.put("sites", sitesCsv);
context.put("numberofsites", String.valueOf(uniqueSites.size()));
broadcastNow("Server", entries, "interval", context);
}
/*
* ======================= Utilities =======================
*/
private List<String> single(String site) {
List<String> list = new ArrayList<String>();
if (site != null && !site.isEmpty()) {
list.add(site);
}
return list;
}
private List<String> applyMaxSites(List<String> sites, BroadcastSettings s) {
if (sites == null) {
return new ArrayList<String>();
}
int max = s.getMaxSitesListed();
if (max <= 0 || sites.size() <= max) {
return new ArrayList<String>(sites);
}
return new ArrayList<String>(sites.subList(0, max));
}
private String resolveName(UUID uuid) {
try {
OfflinePlayer op = Bukkit.getOfflinePlayer(uuid);
String name = op == null ? null : op.getName();
return name == null || name.isEmpty() ? "Player" : name;
} catch (Exception e) {
return "Player";
}
}
private String join(List<String> list) {
StringJoiner joiner = new StringJoiner(", ");
for (String s : list) {
if (s != null && !s.isEmpty()) {
joiner.add(s);
}
}
return joiner.toString();
}
}
@@ -0,0 +1,112 @@
package com.bencodez.votingplugin.broadcast;
import java.util.concurrent.TimeUnit;
import org.bukkit.configuration.ConfigurationSection;
import com.bencodez.simpleapi.time.ParsedDuration;
/**
* Immutable broadcast configuration.
*
* Type: NONE disables broadcasting.
*/
public final class BroadcastSettings {
private final VoteBroadcastType type;
private final ParsedDuration duration;
private final int maxSitesListed;
private final BroadcastFormat format;
/**
* Constructs a BroadcastSettings with the specified parameters.
*
* @param type the broadcast type
* @param duration the broadcast duration
* @param maxSitesListed the maximum number of sites to list
* @param format the broadcast format
*/
public BroadcastSettings(VoteBroadcastType type, ParsedDuration duration, int maxSitesListed,
BroadcastFormat format) {
this.type = type == null ? VoteBroadcastType.NONE : type;
this.duration = duration == null ? ParsedDuration.empty() : duration;
this.maxSitesListed = Math.max(0, maxSitesListed);
this.format = format == null ? new BroadcastFormat("", "", "") : format;
}
/**
* Returns the broadcast type.
*
* @return the broadcast type
*/
public VoteBroadcastType getType() {
return type;
}
/**
* Returns the broadcast duration.
*
* @return the broadcast duration
*/
public ParsedDuration getDuration() {
return duration;
}
/**
* Returns the maximum number of sites to list.
*
* @return the maximum number of sites to list
*/
public int getMaxSitesListed() {
return maxSitesListed;
}
/**
* Returns the broadcast format.
*
* @return the broadcast format
*/
public BroadcastFormat getFormat() {
return format;
}
/**
* Returns whether broadcasting is disabled.
*
* @return true if broadcasting is disabled
*/
public boolean isDisabled() {
return type == VoteBroadcastType.NONE;
}
/**
* Loads VoteBroadcast settings from config.yml.
*
* Expected structure: VoteBroadcast: Type: EVERY_VOTE Duration: 2m
* MaxSitesListed: 0 Format: BroadcastMsg: '...' Header: '...' ListLine: '...'
*
* @param sec the configuration section to load from
* @return the loaded broadcast settings
*/
public static BroadcastSettings load(ConfigurationSection sec) {
VoteBroadcastType type = VoteBroadcastType.parse(sec == null ? null : sec.getString("Type"),
VoteBroadcastType.NONE);
ParsedDuration duration = ParsedDuration.parse(sec == null ? "2m" : sec.getString("Duration", "2m"),
TimeUnit.MINUTES);
int maxSites = sec == null ? 0 : sec.getInt("MaxSitesListed", 0);
ConfigurationSection fmt = sec == null ? null : sec.getConfigurationSection("Format");
String broadcastMsg = fmt == null ? "&6[Vote] &aThanks &e%player% &afor voting on &e%site%&a!"
: fmt.getString("BroadcastMsg", "&6[Vote] &aThanks &e%player% &afor voting on &e%site%&a!");
String header = fmt == null ? "&6[Vote] &a%player% voted! &7(%sites_count%)"
: fmt.getString("Header", "&6[Vote] &a%player% voted! &7(%sites_count%)");
String listLine = fmt == null ? " &7- &e%site%" : fmt.getString("ListLine", " &7- &e%site%");
return new BroadcastSettings(type, duration, maxSites, new BroadcastFormat(broadcastMsg, header, listLine));
}
}
@@ -0,0 +1,69 @@
package com.bencodez.votingplugin.broadcast;
import java.util.Locale;
/**
* Defines WHEN vote broadcasts occur.
*
* Set Type: NONE to disable broadcasting entirely.
*/
public enum VoteBroadcastType {
/**
* No vote broadcasting.
*/
NONE,
/**
* Broadcast on every vote (even if the player is offline). Uses
* Format.BroadcastMsg (+ optional header/list if you choose).
*/
EVERY_VOTE,
/**
* Broadcast on every vote ONLY if the voting player is online. Useful when
* processing offline votes but you don't want global spam for them.
*/
EVERY_VOTE_ONLINE_ONLY,
/**
* Broadcast at most once per Duration per player. (Even if they vote multiple
* sites inside the cooldown.)
*/
COOLDOWN_PER_PLAYER,
/**
* Batch sites per player for Duration, then broadcast one message listing
* sites.
*/
BATCH_WINDOW_PER_PLAYER,
/**
* Broadcast only the first vote of the day per player (calendar day).
*/
FIRST_VOTE_OF_DAY,
/**
* Every Duration, broadcast a global summary of who voted and how many sites.
* Uses context placeholders: %players%, %numberofplayers%, %sites%,
* %numberofsites%.
*/
INTERVAL_SUMMARY_GLOBAL;
/**
* Parses a vote broadcast type from a string.
* @param s the string to parse
* @param def the default value if parsing fails
* @return the parsed broadcast type or default
*/
public static VoteBroadcastType parse(String s, VoteBroadcastType def) {
if (s == null || s.trim().isEmpty()) {
return def;
}
try {
return VoteBroadcastType.valueOf(s.trim().toUpperCase(Locale.ROOT));
} catch (Exception ignored) {
return def;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -16,6 +16,11 @@ public class CommandAdminVote implements CommandExecutor {
private VotingPluginMain plugin;
/**
* Constructs a new CommandAdminVote instance.
*
* @param plugin the main plugin instance
*/
public CommandAdminVote(VotingPluginMain plugin) {
this.plugin = plugin;
}
@@ -25,6 +25,12 @@ public class CommandAliases implements CommandExecutor {
/** The plugin. */
private VotingPluginMain plugin = VotingPluginMain.plugin;
/**
* Constructs a new CommandAliases instance.
*
* @param cmdHandle the command handler
* @param adminCommand whether this is an admin command
*/
public CommandAliases(CommandHandler cmdHandle, boolean adminCommand) {
this.cmdHandle = cmdHandle;
this.adminCommand = adminCommand;
@@ -19,26 +19,32 @@ import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueLi
import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueNumber;
import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.valuerequest.InputMethod;
import com.bencodez.advancedcore.api.valuerequest.ValueRequest;
import com.bencodez.advancedcore.api.valuerequest.ValueRequestBuilder;
import com.bencodez.advancedcore.api.valuerequest.listeners.StringListener;
import com.bencodez.simpleapi.valuerequest.InputMethod;
import com.bencodez.simpleapi.valuerequest.StringListener;
import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.advancedcore.api.yml.editor.ConfigEditor;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.player.PlayerUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.commands.gui.admin.AdminVoteVoteParty;
import com.bencodez.votingplugin.commands.gui.admin.cumulative.AdminVoteCumulative;
import com.bencodez.votingplugin.commands.gui.admin.milestones.AdminVoteMilestones;
import com.bencodez.votingplugin.commands.gui.admin.milestones.AdminVoteVoteMilestones;
import com.bencodez.votingplugin.commands.gui.admin.voteshop.AdminVoteVoteShop;
import com.bencodez.votingplugin.events.PlayerVoteEvent;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.votesites.VoteSite;
/**
* Admin GUI handler for the voting plugin.
*/
public class AdminGUI {
private VotingPluginMain plugin;
/**
* Constructor for AdminGUI.
*
* @param plugin the VotingPluginMain instance
*/
public AdminGUI(VotingPluginMain plugin) {
this.plugin = plugin;
}
@@ -58,14 +64,14 @@ public class AdminGUI {
public void onClick(ClickEvent event) {
Player player = event.getPlayer();
if (event.getClick().equals(ClickType.MIDDLE)) {
new ValueRequest().requestString(player, new StringListener() {
new ValueRequest(plugin, plugin.getDialogService(), null).requestString(player, "", null, true, "Enter vote site", new StringListener() {
@Override
public void onInput(Player player, String value) {
plugin.getConfigVoteSites().generateVoteSite(value);
player.sendMessage("Generated site");
plugin.reload();
openAdminGUIVoteSiteSite(player, plugin.getVoteSite(value, true));
openAdminGUIVoteSiteSite(player, plugin.getVoteSiteManager().getVoteSite(value, true));
}
});
} else {
@@ -82,19 +88,11 @@ public class AdminGUI {
}
});
buttons.add(new BInventoryButton(new ItemBuilder(Material.DIAMOND_BLOCK, 1).setName("&cEdit Milestones")) {
buttons.add(new BInventoryButton(new ItemBuilder(Material.DIAMOND_BLOCK, 1).setName("&cEdit VoteMilestones")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteMilestones(plugin, clickEvent.getPlayer()).open(GUIMethod.CHEST);
}
});
buttons.add(new BInventoryButton(new ItemBuilder(Material.COBBLESTONE, 1).setName("&cEdit Cumulative")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteCumulative(plugin, clickEvent.getPlayer()).open(GUIMethod.CHEST);
new AdminVoteVoteMilestones(plugin, clickEvent.getPlayer()).open(GUIMethod.CHEST);
}
});
@@ -226,6 +224,9 @@ public class AdminGUI {
return buttons;
}
/**
* Load hook to add admin GUI buttons.
*/
public void loadHook() {
for (BInventoryButton b : adminGUIButtons()) {
com.bencodez.advancedcore.command.gui.AdminGUI.getInstance().addButton(b);
@@ -240,7 +241,7 @@ public class AdminGUI {
public void openAdminGUIVoteSites(Player player) {
BInventory inv = new BInventory("VoteSites");
int count = 0;
for (VoteSite voteSite : plugin.getVoteSites()) {
for (VoteSite voteSite : plugin.getVoteSiteManager().getVoteSites()) {
ArrayList<String> lore = new ArrayList<>();
lore.add("Enabled: " + voteSite.isEnabled());
lore.add("Priority: " + voteSite.getPriority());
@@ -249,7 +250,6 @@ public class AdminGUI {
lore.add("ServiceSite: " + voteSite.getServiceSite());
lore.add("VoteURL: " + voteSite.getVoteURL());
lore.add("VoteDelay: " + voteSite.getVoteDelay());
lore.add("VoteDelayMin: " + voteSite.getVoteDelayMin());
inv.addButton(count,
new BInventoryButton(voteSite.getKey(), ArrayUtils.convert(lore), new ItemStack(Material.STONE)) {
@@ -285,25 +285,25 @@ public class AdminGUI {
for (Player p : Bukkit.getOnlinePlayers()) {
playerNames.add(p.getName());
}
new ValueRequestBuilder(new StringListener() {
new ValueRequest(plugin, plugin.getDialogService(), InputMethod.INVENTORY).requestString(
event.getWhoClicked(), "", playerNames, true, "Select player", new StringListener() {
@Override
public void onInput(Player player, String value) {
Object ob = PlayerUtils.getPlayerMeta(plugin, player, "VoteSite");
if (ob != null) {
VoteSite site = (VoteSite) ob;
PlayerVoteEvent voteEvent = new PlayerVoteEvent(site, value, site.getServiceSite(), false);
plugin.getVoteTimer().submit(new Runnable() {
@Override
public void onInput(Player player, String value) {
Object ob = PlayerUtils.getPlayerMeta(plugin, player, "VoteSite");
if (ob != null) {
VoteSite site = (VoteSite) ob;
PlayerVoteEvent voteEvent = new PlayerVoteEvent(site, value, site.getServiceSite(), false);
plugin.getVoteTimer().submit(new Runnable() {
@Override
public void run() {
plugin.getServer().getPluginManager().callEvent(voteEvent);
@Override
public void run() {
plugin.getServer().getPluginManager().callEvent(voteEvent);
}
});
}
});
}
}
}, ArrayUtils.convert(playerNames)).usingMethod(InputMethod.INVENTORY).allowCustomOption(true)
.request(event.getWhoClicked());
}
});
}
});
@@ -349,24 +349,13 @@ public class AdminGUI {
}
}));
inv.addButton(new EditGUIButton(new EditGUIValueNumber("VoteDelay", voteSite.getVoteDelay()) {
inv.addButton(new EditGUIButton(new EditGUIValueString("VoteDelay", voteSite.getVoteDelay()) {
@Override
public void setValue(Player player, Number num) {
public void setValue(Player player, String value) {
VoteSite voteSite = (VoteSite) getInv().getMeta(player, "VoteSite");
String siteName = voteSite.getKey();
plugin.getConfigVoteSites().setVoteDelay(siteName, num.intValue());
plugin.reload();
}
}));
inv.addButton(new EditGUIButton(new EditGUIValueNumber("VoteDelayMin", voteSite.getVoteDelay()) {
@Override
public void setValue(Player player, Number num) {
VoteSite voteSite = (VoteSite) getInv().getMeta(player, "VoteSite");
String siteName = voteSite.getKey();
plugin.getConfigVoteSites().setVoteDelay(siteName, num.intValue());
plugin.getConfigVoteSites().setVoteDelay(siteName, value);
plugin.reload();
}
}));
@@ -377,7 +366,7 @@ public class AdminGUI {
public void setValue(Player player, Number num) {
VoteSite voteSite = (VoteSite) getInv().getMeta(player, "VoteSite");
String siteName = voteSite.getKey();
plugin.getConfigVoteSites().setVoteDelay(siteName, num.intValue());
plugin.getConfigVoteSites().setVoteDelayDailyHour(siteName, num.intValue());
plugin.reload();
}
}));
@@ -463,4 +452,4 @@ public class AdminGUI {
inv.openInventory(player);
}
}
}
@@ -14,12 +14,22 @@ import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Abstract class for admin vote confirmation dialogs.
*/
public abstract class AdminVoteConfirmation extends GUIHandler {
@SuppressWarnings("unused")
private VotingPluginMain plugin;
private String title;
/**
* Constructor for AdminVoteConfirmation.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param title the title of the confirmation dialog
*/
public AdminVoteConfirmation(VotingPluginMain plugin, CommandSender player, String title) {
super(plugin, player);
this.plugin = plugin;
@@ -31,6 +41,11 @@ public abstract class AdminVoteConfirmation extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
}
@@ -60,8 +75,18 @@ public abstract class AdminVoteConfirmation extends GUIHandler {
inv.openInventory(player);
}
/**
* Called when the user confirms the action.
*
* @param p the player who confirmed
*/
public abstract void onConfirm(Player p);
/**
* Called when the user denies the action.
*
* @param p the player who denied
*/
public abstract void onDeny(Player p);
@Override
@@ -15,11 +15,21 @@ import com.bencodez.votingplugin.VotingPluginMain;
import net.md_5.bungee.api.chat.TextComponent;
/**
* Admin help GUI handler.
*/
public class AdminVoteHelp extends GUIHandler {
private int page;
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteHelp.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param page the page number to display
*/
public AdminVoteHelp(VotingPluginMain plugin, CommandSender player, int page) {
super(plugin, player);
this.plugin = plugin;
@@ -54,6 +64,11 @@ public class AdminVoteHelp extends GUIHandler {
return msg;
}
@Override
public void onDialog(Player player) {
}
/**
* Admin help text.
*
@@ -15,18 +15,36 @@ import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin permissions GUI handler.
*/
public class AdminVotePerms extends GUIHandler {
private int page;
private String playerName;
private VotingPluginMain plugin;
/**
* Constructor for AdminVotePerms.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param page the page number
*/
public AdminVotePerms(VotingPluginMain plugin, CommandSender player, int page) {
super(plugin, player);
this.plugin = plugin;
this.page = page;
}
/**
* Constructor for AdminVotePerms with player name.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param page the page number
* @param playerName the player name to check
*/
public AdminVotePerms(VotingPluginMain plugin, CommandSender player, int page, String playerName) {
super(plugin, player);
this.plugin = plugin;
@@ -39,6 +57,17 @@ public class AdminVotePerms extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
/**
* List permissions for a sender.
*
* @param sender the command sender
* @return array of permission strings
*/
public String[] listPerms(CommandSender sender) {
ArrayList<String> msg = new ArrayList<>();
@@ -113,6 +142,14 @@ public class AdminVotePerms extends GUIHandler {
return ArrayUtils.convert(text);
}
/**
* List permissions for a specific player.
*
* @param sender the command sender
* @param player the player name
* @param page the page number
* @return list of permission strings
*/
public ArrayList<String> listPerms(CommandSender sender, String player, int page) {
Player p = Bukkit.getPlayer(player);
ArrayList<String> text = new ArrayList<>();
@@ -179,6 +216,12 @@ public class AdminVotePerms extends GUIHandler {
}
/**
* List permissions in developer format.
*
* @param sender the command sender
* @return array of permission strings in developer format
*/
public String[] listPermsDev(CommandSender sender) {
ArrayList<String> msg = new ArrayList<>();
msg.add("Command");
@@ -18,10 +18,19 @@ import com.bencodez.votingplugin.user.VotingPluginUser;
import xyz.upperlevel.spigot.book.BookUtil;
/**
* Admin placeholders GUI handler.
*/
public class AdminVotePlaceholders extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVotePlaceholders.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVotePlaceholders(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
@@ -32,6 +41,11 @@ public class AdminVotePlaceholders extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
BookWrapper book = new BookWrapper("Placeholders");
@@ -18,11 +18,21 @@ import com.bencodez.votingplugin.user.VotingPluginUser;
import xyz.upperlevel.spigot.book.BookUtil;
/**
* Admin placeholders player GUI handler.
*/
public class AdminVotePlaceholdersPlayer extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructor for AdminVotePlaceholdersPlayer.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param user the voting plugin user
*/
public AdminVotePlaceholdersPlayer(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -34,6 +44,11 @@ public class AdminVotePlaceholdersPlayer extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
BookWrapper book = new BookWrapper("Placeholders");
@@ -73,9 +88,6 @@ public class AdminVotePlaceholdersPlayer extends GUIHandler {
ArrayList<String> msg = new ArrayList<>();
msg.add("&cPlaceholders:");
VotingPluginUser placeholderUser = user;
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders() && user.hasPrimaryAccount()) {
placeholderUser = plugin.getVotingPluginUserManager().getVotingPluginUser(user.getPrimaryAccount());
}
for (PlaceHolder<VotingPluginUser> placeholder : plugin.getPlaceholders().getPlaceholders()) {
String identifier = placeholder.getIdentifier().toLowerCase();
if (identifier.endsWith("_")) {
@@ -21,11 +21,15 @@ import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.commands.gui.player.VoteGUI;
import com.bencodez.votingplugin.topvoter.TopVoterPlayer;
import com.bencodez.votingplugin.user.VotingPluginUser;
/**
* Admin top points GUI handler.
*/
public class AdminVoteTopPoints extends GUIHandler {
@SuppressWarnings("unused")
@@ -33,6 +37,14 @@ public class AdminVoteTopPoints extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructor for AdminVoteTopPoints.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param user the voting plugin user
* @param page the page number
*/
public AdminVoteTopPoints(VotingPluginMain plugin, CommandSender player, VotingPluginUser user, int page) {
super(plugin, player);
this.plugin = plugin;
@@ -45,6 +57,11 @@ public class AdminVoteTopPoints extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
}
@@ -63,7 +80,7 @@ public class AdminVoteTopPoints extends GUIHandler {
for (String uuid : plugin.getVotingPluginUserManager().getAllUUIDs()) {
VotingPluginUser vpUser = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid));
vpUser.dontCache();
vpUser.userDataFetechMode(UserDataFetchMode.NO_CACHE);
int points = vpUser.getPoints();
if (points > 0) {
topPoints1.put(vpUser.getTopVoterPlayer(), points);
@@ -17,15 +17,25 @@ import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueLi
import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueNumber;
import com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.valuerequest.ValueRequestBuilder;
import com.bencodez.advancedcore.api.valuerequest.listeners.NumberListener;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.simpleapi.valuerequest.InputMethod;
import com.bencodez.simpleapi.valuerequest.NumberListener;
import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin vote party GUI handler.
*/
public class AdminVoteVoteParty extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteParty.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteParty(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
@@ -45,12 +55,16 @@ public class AdminVoteVoteParty extends GUIHandler {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
EditGUI inv = new EditGUI("Edit VoteParty");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.VoteParty");
// to add
inv.addButton(new EditGUIButton(new ItemBuilder(Material.PAPER, 1),
new EditGUIValueBoolean("Enabled", plugin.getSpecialRewardsConfig().isVotePartyEnabled()) {
@@ -83,15 +97,21 @@ public class AdminVoteVoteParty extends GUIHandler {
@Override
public void onClick(ClickEvent clickEvent) {
new ValueRequestBuilder(new NumberListener() {
ArrayList<Number> options = new ArrayList<Number>();
options.add(Integer.valueOf(0));
options.add(Integer.valueOf(10));
options.add(Integer.valueOf(50));
options.add(Integer.valueOf(100));
@Override
public void onInput(Player player, Number value) {
plugin.getServerData().setVotePartyExtraRequired(value.intValue());
}
}, new Number[] { 0, 10, 50, 100 })
.currentValue("" + plugin.getServerData().getVotePartyExtraRequired()).allowCustomOption(true)
.request(clickEvent.getPlayer());
new ValueRequest(plugin, plugin.getDialogService(), InputMethod.INVENTORY).requestNumber(
clickEvent.getPlayer(), Integer.valueOf(plugin.getServerData().getVotePartyExtraRequired()),
options, true, "Set extra votes", new NumberListener() {
@Override
public void onInput(Player player, Number value) {
plugin.getServerData().setVotePartyExtraRequired(value.intValue());
}
});
}
});
@@ -215,8 +235,6 @@ public class AdminVoteVoteParty extends GUIHandler {
}
});
// implement item reward?
inv.openInventory(player);
}
@@ -231,4 +249,4 @@ public class AdminVoteVoteParty extends GUIHandler {
plugin.reload();
}
}
}
@@ -12,13 +12,23 @@ import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.inventory.editgui.EditGUI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.events.PlayerVoteEvent;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.votesites.VoteSite;
/**
* Admin vote player GUI handler.
*/
public class AdminVoteVotePlayer extends GUIHandler {
private String playerName;
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVotePlayer.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param playerName the player name
*/
public AdminVoteVotePlayer(VotingPluginMain plugin, CommandSender player, String playerName) {
super(plugin, player);
this.plugin = plugin;
@@ -44,7 +54,7 @@ public class AdminVoteVotePlayer extends GUIHandler {
EditGUI inv = new EditGUI("Trigger vote for " + playerName);
inv.requirePermission("VotingPlugin.Commands.AdminVote.Vote|VotingPlugin.Admin");
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
inv.addButton(new BInventoryButton(site.getItem().setName(site.getKey())) {
@Override
@@ -71,6 +81,11 @@ public class AdminVoteVotePlayer extends GUIHandler {
inv.openInventory(player);
}
@Override
public void onDialog(Player player) {
}
@Override
public void open() {
@@ -1,109 +0,0 @@
package com.bencodez.votingplugin.commands.gui.admin.cumulative;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.valuerequest.InputMethod;
import com.bencodez.advancedcore.api.valuerequest.ValueRequest;
import com.bencodez.advancedcore.api.valuerequest.ValueRequestBuilder;
import com.bencodez.advancedcore.api.valuerequest.listeners.NumberListener;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
public class AdminVoteCumulative extends GUIHandler {
private VotingPluginMain plugin;
public AdminVoteCumulative(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
BInventory inv = new BInventory("Edit Cumulative");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.Cumulative");
inv.addButton(
new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&cEdit existing cumulative rewards")) {
@Override
public void onClick(ClickEvent clickEvent) {
ArrayList<Integer> nums = new ArrayList<>();
for (String num : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
if (MessageAPI.isInt(num)) {
nums.add(Integer.parseInt(num));
}
}
Number[] options = new Number[nums.size()];
for (int i = 0; i < nums.size(); i++) {
options[i] = nums.get(i);
}
new ValueRequestBuilder(new NumberListener() {
@Override
public void onInput(Player player, Number value) {
RewardEditGUI.getInstance().openRewardGUI(clickEvent.getPlayer(),
plugin.getRewardHandler()
.getDirectlyDefined("Cumulative." + value.intValue() + ".Rewards"));
}
}, options).allowCustomOption(false).usingMethod(InputMethod.INVENTORY)
.request(clickEvent.getPlayer());
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.EMERALD_BLOCK).setName("&aAdd cumulative reward")) {
@Override
public void onClick(ClickEvent clickEvent) {
new ValueRequest().requestNumber(player, new NumberListener() {
@Override
public void onInput(Player player, Number value) {
plugin.getSpecialRewardsConfig().setCumulative(value.intValue());
plugin.reload();
}
});
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.REDSTONE_BLOCK).setName("&cRemove cumulative")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteCumulativeRemove(plugin, clickEvent.getPlayer()).open();
}
});
inv.openInventory(player);
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -1,77 +0,0 @@
package com.bencodez.votingplugin.commands.gui.admin.cumulative;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.commands.gui.admin.AdminVoteConfirmation;
public class AdminVoteCumulativeRemove extends GUIHandler {
private VotingPluginMain plugin;
public AdminVoteCumulativeRemove(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
BInventory inv = new BInventory("Remove cumulative");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.Cumulative");
for (final String votes : plugin.getSpecialRewardsConfig().getCumulativeVotes()) {
inv.addButton(new BInventoryButton(
new ItemBuilder(Material.PAPER, 1).setName(votes).addLoreLine("&c&lClick to remove")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteConfirmation(plugin, clickEvent.getPlayer(), "Remove cumulative " + votes + "?") {
@Override
public void onConfirm(Player p) {
plugin.getSpecialRewardsConfig().removeCumulative(votes);
p.sendMessage("Removed cumulative " + votes);
plugin.reload();
}
@Override
public void onDeny(Player p) {
new AdminVoteCumulative(plugin, p);
}
}.open();
}
});
}
inv.openInventory(player);
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -1,109 +0,0 @@
package com.bencodez.votingplugin.commands.gui.admin.milestones;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.valuerequest.InputMethod;
import com.bencodez.advancedcore.api.valuerequest.ValueRequest;
import com.bencodez.advancedcore.api.valuerequest.ValueRequestBuilder;
import com.bencodez.advancedcore.api.valuerequest.listeners.NumberListener;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
public class AdminVoteMilestones extends GUIHandler {
private VotingPluginMain plugin;
public AdminVoteMilestones(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
BInventory inv = new BInventory("Edit MileStones");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.MileStones");
inv.addButton(
new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&cEdit existing milestone rewards")) {
@Override
public void onClick(ClickEvent clickEvent) {
ArrayList<Integer> nums = new ArrayList<>();
for (String num : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
if (MessageAPI.isInt(num)) {
nums.add(Integer.parseInt(num));
}
}
Number[] options = new Number[nums.size()];
for (int i = 0; i < nums.size(); i++) {
options[i] = nums.get(i);
}
new ValueRequestBuilder(new NumberListener() {
@Override
public void onInput(Player player, Number value) {
RewardEditGUI.getInstance().openRewardGUI(clickEvent.getPlayer(),
plugin.getRewardHandler()
.getDirectlyDefined("MileStones." + value.intValue() + ".Rewards"));
}
}, options).allowCustomOption(false).usingMethod(InputMethod.INVENTORY)
.request(clickEvent.getPlayer());
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.EMERALD_BLOCK).setName("&aAdd milestone")) {
@Override
public void onClick(ClickEvent clickEvent) {
new ValueRequest().requestNumber(player, new NumberListener() {
@Override
public void onInput(Player player, Number value) {
plugin.getSpecialRewardsConfig().setMilestone(value.intValue());
plugin.reload();
}
});
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.REDSTONE_BLOCK).setName("&cRemove milestone")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteMilestoneRemove(plugin, clickEvent.getPlayer()).open();
}
});
inv.openInventory(player);
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -15,11 +15,20 @@ import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.commands.gui.admin.AdminVoteConfirmation;
public class AdminVoteMilestoneRemove extends GUIHandler {
/**
* Admin vote milestone remove GUI handler.
*/
public class AdminVoteVoteMilestoneRemove extends GUIHandler {
private VotingPluginMain plugin;
public AdminVoteMilestoneRemove(VotingPluginMain plugin, CommandSender player) {
/**
* Constructor for AdminVoteVoteMilestoneRemove.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteMilestoneRemove(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@@ -38,11 +47,16 @@ public class AdminVoteMilestoneRemove extends GUIHandler {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
BInventory inv = new BInventory("Remove milestones");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.MileStones");
for (final String votes : plugin.getSpecialRewardsConfig().getMilestoneVotes()) {
BInventory inv = new BInventory("Remove VoteMilestones");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.VoteMilestones");
for (final String votes : plugin.getVoteMilestonesManager().getConfig().getMilestones().keySet()) {
inv.addButton(new BInventoryButton(
new ItemBuilder(Material.PAPER, 1).setName(votes).addLoreLine("&c&lClick to remove")) {
@@ -52,14 +66,14 @@ public class AdminVoteMilestoneRemove extends GUIHandler {
@Override
public void onConfirm(Player p) {
plugin.getSpecialRewardsConfig().removeMilestone(votes);
plugin.getSpecialRewardsConfig().removeVoteMilestone(votes);
p.sendMessage("Removed milestone " + votes);
plugin.reload();
}
@Override
public void onDeny(Player p) {
new AdminVoteMilestones(plugin, p);
new AdminVoteVoteMilestones(plugin, p);
}
}.open();
@@ -0,0 +1,120 @@
package com.bencodez.votingplugin.commands.gui.admin.milestones;
import java.util.ArrayList;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.simpleapi.valuerequest.InputMethod;
import com.bencodez.simpleapi.valuerequest.NumberListener;
import com.bencodez.simpleapi.valuerequest.StringListener;
import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin vote milestones GUI handler.
*/
public class AdminVoteVoteMilestones extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteMilestones.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteMilestones(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
BInventory inv = new BInventory("Edit VoteMilestones");
inv.requirePermission("VotingPlugin.Commands.AdminVote.Edit.VoteMilestones");
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER)
.setName("&cEdit existing vote milestone rewards (Legacy milestones not included)")) {
@Override
public void onClick(ClickEvent clickEvent) {
Set<String> keys = plugin.getVoteMilestonesManager().getConfig().getMilestones().keySet();
ArrayList<String> milestoneKeys = new ArrayList<String>();
for (String key : keys) {
if (!key.startsWith("Legacy_")) {
milestoneKeys.add(key);
}
}
new ValueRequest(plugin, plugin.getDialogService(), InputMethod.INVENTORY).requestString(
clickEvent.getPlayer(), "", milestoneKeys, false, "Select milestone", new StringListener() {
@Override
public void onInput(Player player, String value) {
RewardEditGUI.getInstance().openRewardGUI(clickEvent.getPlayer(),
plugin.getRewardHandler().getDirectlyDefined("VoteMilestones." + value + ".Rewards"));
}
});
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.EMERALD_BLOCK).setName("&aAdd milestone")) {
@Override
public void onClick(ClickEvent clickEvent) {
new ValueRequest(plugin, plugin.getDialogService(), null).requestNumber(player, 0, null, true,
"Enter milestone", new NumberListener() {
@Override
public void onInput(Player player, Number value) {
plugin.getSpecialRewardsConfig().setVoteMilestone(value.intValue());
plugin.reload();
}
});
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.REDSTONE_BLOCK).setName("&cRemove milestone")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteVoteMilestoneRemove(plugin, clickEvent.getPlayer()).open();
}
});
inv.openInventory(player);
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,169 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select an event filter, then open AdminVoteLogRecent (filtered).
*/
public class AdminVoteLogEventSelect extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogEventSelect.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
*/
public AdminVoteLogEventSelect(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days) {
this(plugin, sender, table, user, days, 0);
}
@Override
public void onDialog(Player player) {
}
/**
* Constructor for AdminVoteLogEventSelect with page.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogEventSelect(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = days;
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Events";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
List<VoteLogMysqlTable.VoteLogEvent> events = Arrays.asList(VoteLogMysqlTable.VoteLogEvent.values());
int start = page * PAGE_SIZE;
int end = Math.min(events.size(), start + PAGE_SIZE);
if (start >= events.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo events")
.addLoreLine("&7No events on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
} else {
for (int i = start; i < end; i++) {
VoteLogMysqlTable.VoteLogEvent ev = events.get(i);
inv.addButton(makeEventButton(ev));
}
}
// back button
if (user != null && plugin.getGui().isChestVoteTopBackButton()) {
inv.getPageButtons().add(plugin.getCommandLoader().getBackButton(user).setSlot(7));
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeEventButton(VoteLogMysqlTable.VoteLogEvent ev) {
ItemBuilder item = new ItemBuilder(Material.BOOK).setName("&a" + ev.name())
.addLoreLine("&7Click to view recent logs filtered by this event")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days, ev).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,125 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.Material;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Helper class for admin vote log GUI operations.
*/
public class AdminVoteLogHelpers {
/**
* Get the material icon for a vote log event.
*
* @param event the vote log event
* @param status the status of the vote
* @return the material to use for the icon
*/
public static Material getMaterialForEvent(VoteLogMysqlTable.VoteLogEvent event, String status) {
// Cached entries still override to chest (keeps your current behavior)
if ("CACHED".equalsIgnoreCase(status)) {
return Material.CHEST;
}
if (event == null) {
return Material.PAPER;
}
switch (event) {
case VOTE_RECEIVED:
return Material.EMERALD;
case VOTEMILESTONE:
return Material.ANVIL;
case VOTE_STREAK_REWARD:
return Material.FIREWORK_ROCKET;
case TOP_VOTER_REWARD:
return Material.GOLD_BLOCK;
default:
return Material.PAPER;
}
}
/**
* Get the color code for a vote log event.
*
* @param event the vote log event
* @return the color code string
*/
public static String getEventColor(VoteLogMysqlTable.VoteLogEvent event) {
if (event == null) {
return "&7";
}
switch (event) {
case VOTE_RECEIVED:
return "&a";
case VOTEMILESTONE:
return "&6";
case VOTE_STREAK_REWARD:
return "&d";
case TOP_VOTER_REWARD:
return "&c";
default:
return "&7";
}
}
/**
* Returns a safe string, converting null to empty string.
*
* @param s the string to check
* @return the string or empty string if null
*/
public static String safe(String s) {
return s == null ? "" : s;
}
/**
* Checks if a string is not null and not empty.
*
* @param s the string to check
* @return true if the string is not empty
*/
public static boolean notEmpty(String s) {
return s != null && !s.trim().isEmpty();
}
/**
* Formats a timestamp in milliseconds to a readable date string.
*
* @param millis the timestamp in milliseconds
* @return the formatted date string
*/
public static String formatTime(long millis) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date(millis));
} catch (Exception e) {
return String.valueOf(millis);
}
}
/**
* Returns a shortened version of a UUID string.
*
* @param uuid the UUID string
* @return the first 8 characters of the UUID or "unknown"
*/
public static String shortUuid(String uuid) {
if (uuid == null || uuid.isEmpty()) {
return "unknown";
}
return uuid.length() > 8 ? uuid.substring(0, 8) : uuid;
}
}
@@ -0,0 +1,208 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin vote log menu GUI handler.
*/
public class AdminVoteLogMenu extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days; // window used by selectors/stats (0 = all time)
// Default to "voting" (Vote received)
private final VoteLogMysqlTable.VoteLogEvent defaultEvent = VoteLogMysqlTable.VoteLogEvent.VOTE_RECEIVED;
/**
* Constructor for AdminVoteLogMenu.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param days the number of days to filter
*/
public AdminVoteLogMenu(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, int days) {
this(plugin, sender, table, null, days);
}
@Override
public void onDialog(Player player) {
}
/**
* Constructor for AdminVoteLogMenu with user.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
*/
public AdminVoteLogMenu(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
this.days = Math.max(0, days);
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Admin";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
inv.addButton(new BInventoryButton(new ItemBuilder(Material.NAME_TAG).setName("&aVotes by Player")
.addLoreLine("&7List stored player names").addLoreLine("&7Click a player to view their votelog")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogPlayerSelect(plugin, clickEvent.getPlayer(), table, user, days, 0).open();
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.NAME_TAG).setName("&aVotes by Player (Online)")
.addLoreLine("&7List online players").addLoreLine("&7Click a player to view their votelog")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogPlayerSelectOnline(plugin, clickEvent.getPlayer(), table, user, days, 0).open();
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&aVotes by Service")
.addLoreLine("&7List all services found").addLoreLine("&7Click a service to view votelog")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogServiceSelect(plugin, clickEvent.getPlayer(), table, user, days, 0).open();
}
});
// NEW: Votes by Server
inv.addButton(new BInventoryButton(new ItemBuilder(Material.COMPASS).setName("&aVotes by Server")
.addLoreLine("&7List all servers found").addLoreLine("&7Click a server to view votelog")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogServerSelect(plugin, clickEvent.getPlayer(), table, user, days, 0).open();
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.MAP).setName("&aStats")
.addLoreLine("&7Overview counts/uniques/top services")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogStats(plugin, clickEvent.getPlayer(), table, user, days, 10).open();
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(Material.CLOCK).setName("&aRecent Logs")
.addLoreLine("&7Recent logs filtered by event").addLoreLine("&7Default: &f" + defaultEvent.name())
.addLoreLine("&8(Use bottom buttons to switch event)")) {
@Override
public void onClick(ClickEvent clickEvent) {
// Open recent with default event filter
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days, defaultEvent).open();
}
});
addEventSwitchButtons(inv);
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private void addEventSwitchButtons(BInventory inv) {
inv.getPageButtons().add(new BInventoryButton(new ItemBuilder(Material.LIME_DYE)
.setName("&aEvent: &fVOTE_RECEIVED").addLoreLine("&7Show recent vote received events")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days,
VoteLogMysqlTable.VoteLogEvent.VOTE_RECEIVED).open();
}
}.setSlot(3));
// More... (open selector)
inv.getPageButtons().add(new BInventoryButton(
new ItemBuilder(Material.BOOK).setName("&aEvent: &fMore...").addLoreLine("&7Pick any event filter")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogEventSelect(plugin, clickEvent.getPlayer(), table, user, days).open();
}
}.setSlot(4));
// All events
inv.getPageButtons().add(new BInventoryButton(new ItemBuilder(Material.GRAY_DYE).setName("&aEvent: &fALL")
.addLoreLine("&7Show recent logs for all events")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days, null).open();
}
}.setSlot(5));
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,185 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: VoteLog entries for a given player (paged).
*
* Uses VoteLogMysqlTable instance passed in from CommandLoader.
*
* Supports input as player name OR uuid string (you decide in CommandLoader
* which constructor to call).
*/
public class AdminVoteLogPlayer extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private final int page;
private final String playerName;
private final int days;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogPlayer.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param playerName the player name or UUID
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogPlayer(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, String playerName,
int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.playerName = playerName;
this.days = days;
this.page = Math.max(0, page);
}
@Override
public void onDialog(Player player) {
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Player";
if (playerName != null && !playerName.isEmpty()) {
title += " &7(" + playerName + ")";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<VoteLogMysqlTable.VoteLogEntry> rows = table.getByPlayerName(playerName, days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(rows.size(), start + PAGE_SIZE);
if (start >= rows.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo entries")
.addLoreLine("&7No vote log entries on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
inv.addButton(makeEntryButton(rows.get(i)));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeEntryButton(final VoteLogMysqlTable.VoteLogEntry entry) {
Material mat = "CACHED".equalsIgnoreCase(entry.status) ? Material.CHEST : Material.EMERALD;
String timeStr = AdminVoteLogHelpers.formatTime(entry.voteTime);
String uuidShort = AdminVoteLogHelpers.shortUuid(entry.playerUuid);
String voteShort = AdminVoteLogHelpers.shortUuid(entry.voteId);
// keep same name/lore layout you already have
ItemBuilder item = new ItemBuilder(mat)
.setName("&a" + AdminVoteLogHelpers.safe(entry.event) + " &7(" + voteShort + ")");
if (AdminVoteLogHelpers.notEmpty(entry.playerName) || AdminVoteLogHelpers.notEmpty(entry.playerUuid)) {
item.addLoreLine("&7Player: &f" + AdminVoteLogHelpers.safe(entry.playerName) + " &7(" + uuidShort + ")");
}
if (entry.voteTime > 0) {
item.addLoreLine("&7Time: &f" + timeStr);
}
if (AdminVoteLogHelpers.notEmpty(entry.service)) {
item.addLoreLine("&7Service: &f" + AdminVoteLogHelpers.safe(entry.service));
}
if (AdminVoteLogHelpers.notEmpty(entry.context)) {
item.addLoreLine("&7Context: &f" + AdminVoteLogHelpers.safe(entry.context));
}
if (AdminVoteLogHelpers.notEmpty(entry.status)) {
item.addLoreLine("&7Status: &f" + AdminVoteLogHelpers.safe(entry.status));
}
if (entry.proxyCachedTotal != 0) {
item.addLoreLine("&7Cached Total: &f" + entry.proxyCachedTotal);
}
if (AdminVoteLogHelpers.notEmpty(entry.voteId)) {
item.addLoreLine("&7VoteId: &f" + AdminVoteLogHelpers.safe(entry.voteId));
}
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
// vote_id is now the correlation id entry.voteId
new AdminVoteLogVoteId(plugin, clickEvent.getPlayer(), table, entry.voteId, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,155 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select an ONLINE player, then open AdminVoteLogPlayer.
*/
public class AdminVoteLogPlayerSelect extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogPlayerSelect.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogPlayerSelect(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = Math.max(0, days);
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Players";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
List<Player> online = new ArrayList<>(Bukkit.getOnlinePlayers());
int start = page * PAGE_SIZE;
int end = Math.min(online.size(), start + PAGE_SIZE);
if (start >= online.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo players")
.addLoreLine("&7No online players on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
Player p = online.get(i);
inv.addButton(makePlayerButton(p));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makePlayerButton(final Player target) {
String name = target.getName();
ItemBuilder item = new ItemBuilder(Material.NAME_TAG).setName("&a" + name)
.addLoreLine("&7Click to open votelog for this player")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogPlayer(plugin, clickEvent.getPlayer(), table, name, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,151 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select an ONLINE player, then open AdminVoteLogPlayer.
*/
public class AdminVoteLogPlayerSelectOnline extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogPlayerSelectOnline.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogPlayerSelectOnline(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = days;
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public void onDialog(Player player) {
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Players";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
List<Player> online = new ArrayList<>(Bukkit.getOnlinePlayers());
int start = page * PAGE_SIZE;
int end = Math.min(online.size(), start + PAGE_SIZE);
if (start >= online.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo players")
.addLoreLine("&7No online players on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
} else {
for (int i = start; i < end; i++) {
Player p = online.get(i);
inv.addButton(makePlayerButton(p));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makePlayerButton(Player target) {
String name = target.getName();
ItemBuilder item = new ItemBuilder(Material.NAME_TAG).setName("&a" + name)
.addLoreLine("&7Click to open votelog for this player")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogPlayer(plugin, clickEvent.getPlayer(), table, name, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,255 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Recent VoteLog entries (paged).
*
* Now supports optional event filter + days window.
*/
public class AdminVoteLogRecent extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int page;
private final int days; // 0 = all time
private final VoteLogMysqlTable.VoteLogEvent event; // null = all events
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogRecent.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param page the page number
*/
public AdminVoteLogRecent(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, int page) {
this(plugin, sender, table, null, page, 0, null);
}
/**
* Constructor for AdminVoteLogRecent with user.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param page the page number
*/
public AdminVoteLogRecent(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int page) {
this(plugin, sender, table, user, page, 0, null);
}
/**
* Constructor for AdminVoteLogRecent with full parameters.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param page the page number
* @param days the number of days to filter
* @param event the event type to filter
*/
// NEW constructor used by Menu/EventSelect
public AdminVoteLogRecent(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int page, int days, VoteLogMysqlTable.VoteLogEvent event) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
this.page = Math.max(0, page);
this.days = Math.max(0, days);
this.event = event;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Recent";
if (event != null) {
title += " &7(" + event.name() + ")";
}
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<VoteLogMysqlTable.VoteLogEntry> rows;
if (event == null) {
rows = (days > 0) ? table.getRecentAll(days, needed) : table.getRecent(needed);
} else {
rows = table.getRecentByEvent(event, days, needed);
}
int start = page * PAGE_SIZE;
int end = Math.min(rows.size(), start + PAGE_SIZE);
if (start >= rows.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo entries")
.addLoreLine("&7No vote log entries on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
} else {
for (int i = start; i < end; i++) {
inv.addButton(makeEntryButton(rows.get(i)));
}
}
addEventSwitchButtons(inv);
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private void addEventSwitchButtons(BInventory inv) {
inv.getPageButtons().add(new BInventoryButton(new ItemBuilder(Material.LIME_DYE)
.setName("&aEvent: &fVOTE_RECEIVED").addLoreLine("&7Show recent vote received events")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days,
VoteLogMysqlTable.VoteLogEvent.VOTE_RECEIVED).open();
}
}.setSlot(3));
// More... (open selector)
inv.getPageButtons().add(new BInventoryButton(
new ItemBuilder(Material.BOOK).setName("&aEvent: &fMore...").addLoreLine("&7Pick any event filter")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogEventSelect(plugin, clickEvent.getPlayer(), table, user, days).open();
}
}.setSlot(4));
// All events
inv.getPageButtons().add(new BInventoryButton(new ItemBuilder(Material.GRAY_DYE).setName("&aEvent: &fALL")
.addLoreLine("&7Show recent logs for all events")) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogRecent(plugin, clickEvent.getPlayer(), table, user, 0, days, null).open();
}
}.setSlot(5));
}
private BInventoryButton makeEntryButton(final VoteLogMysqlTable.VoteLogEntry entry) {
VoteLogMysqlTable.VoteLogEvent event = entry.event != null ? VoteLogMysqlTable.VoteLogEvent.valueOf(entry.event)
: null;
Material mat = AdminVoteLogHelpers.getMaterialForEvent(event, entry.status);
String eventColor = AdminVoteLogHelpers.getEventColor(event);
String timeStr = AdminVoteLogHelpers.formatTime(entry.voteTime);
String uuidShort = AdminVoteLogHelpers.shortUuid(entry.playerUuid);
String voteShort = AdminVoteLogHelpers.shortUuid(entry.voteId);
ItemBuilder item = new ItemBuilder(mat)
.setName(eventColor + AdminVoteLogHelpers.safe(entry.event) + " &7(" + voteShort + ")");
if (AdminVoteLogHelpers.notEmpty(entry.playerName) || AdminVoteLogHelpers.notEmpty(entry.playerUuid)) {
item.addLoreLine("&7Player: &f" + AdminVoteLogHelpers.safe(entry.playerName) + " &7(" + uuidShort + ")");
}
if (entry.voteTime > 0) {
item.addLoreLine("&7Time: &f" + timeStr);
}
if (AdminVoteLogHelpers.notEmpty(entry.service)) {
item.addLoreLine("&7Service: &f" + AdminVoteLogHelpers.safe(entry.service));
}
if (AdminVoteLogHelpers.notEmpty(entry.context)) {
item.addLoreLine("&7Context: &f" + AdminVoteLogHelpers.safe(entry.context));
}
if (AdminVoteLogHelpers.notEmpty(entry.status)) {
item.addLoreLine("&7Status: &f" + AdminVoteLogHelpers.safe(entry.status));
}
if (entry.proxyCachedTotal != 0) {
item.addLoreLine("&7Cached Total: &f" + entry.proxyCachedTotal);
}
if (AdminVoteLogHelpers.notEmpty(entry.voteId)) {
item.addLoreLine("&7VoteId: &f" + AdminVoteLogHelpers.safe(entry.voteId));
}
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogVoteId(plugin, clickEvent.getPlayer(), table, entry.voteId, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,204 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: VoteLog entries for a given server (paged).
*
* Uses VoteLogMysqlTable instance passed in from CommandLoader.
*/
public class AdminVoteLogServer extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int page;
private final String server;
private final int days;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogServer.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param server the server name
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogServer(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, String server,
int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.server = server;
this.days = Math.max(0, days);
this.page = Math.max(0, page);
if (sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
/**
* Constructor for AdminVoteLogServer with user.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param server the server name
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogServer(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, String server, int days, int page) {
this(plugin, sender, table, server, days, page);
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
BInventory inv = new BInventory("&aVoteLog - Server &7(" + AdminVoteLogHelpers.safe(server) + ")");
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<VoteLogMysqlTable.VoteLogEntry> rows = table.getByServer(server, days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(rows.size(), start + PAGE_SIZE);
if (start >= rows.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo entries")
.addLoreLine("&7No vote log entries on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
inv.addButton(makeEntryButton(rows.get(i)));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeEntryButton(final VoteLogMysqlTable.VoteLogEntry entry) {
VoteLogMysqlTable.VoteLogEvent event = entry.event != null ? VoteLogMysqlTable.VoteLogEvent.valueOf(entry.event)
: null;
Material mat = AdminVoteLogHelpers.getMaterialForEvent(event, entry.status);
String eventColor = AdminVoteLogHelpers.getEventColor(event);
String timeStr = AdminVoteLogHelpers.formatTime(entry.voteTime);
String uuidShort = AdminVoteLogHelpers.shortUuid(entry.playerUuid);
String voteShort = AdminVoteLogHelpers.shortUuid(entry.voteId);
ItemBuilder item = new ItemBuilder(mat)
.setName(eventColor + AdminVoteLogHelpers.safe(entry.event) + " &7(" + voteShort + ")");
if (AdminVoteLogHelpers.notEmpty(entry.playerName) || AdminVoteLogHelpers.notEmpty(entry.playerUuid)) {
item.addLoreLine("&7Player: &f" + AdminVoteLogHelpers.safe(entry.playerName) + " &7(" + uuidShort + ")");
}
if (entry.voteTime > 0) {
item.addLoreLine("&7Time: &f" + timeStr);
}
if (AdminVoteLogHelpers.notEmpty(entry.server)) {
item.addLoreLine("&7Server: &f" + AdminVoteLogHelpers.safe(entry.server));
}
if (AdminVoteLogHelpers.notEmpty(entry.service)) {
item.addLoreLine("&7Service: &f" + AdminVoteLogHelpers.safe(entry.service));
}
if (AdminVoteLogHelpers.notEmpty(entry.context)) {
item.addLoreLine("&7Context: &f" + AdminVoteLogHelpers.safe(entry.context));
}
if (AdminVoteLogHelpers.notEmpty(entry.status)) {
item.addLoreLine("&7Status: &f" + AdminVoteLogHelpers.safe(entry.status));
}
if (entry.proxyCachedTotal != 0) {
item.addLoreLine("&7Cached Total: &f" + entry.proxyCachedTotal);
}
if (AdminVoteLogHelpers.notEmpty(entry.voteId)) {
item.addLoreLine("&7VoteId: &f" + AdminVoteLogHelpers.safe(entry.voteId));
}
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
// vote_id is the correlation id
new AdminVoteLogVoteId(plugin, clickEvent.getPlayer(), table, entry.voteId, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,152 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select a server (distinct list), then open AdminVoteLogServer.
*/
public class AdminVoteLogServerSelect extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogServerSelect.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogServerSelect(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = Math.max(0, days);
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Servers";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<String> servers = table.getDistinctServers(days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(servers.size(), start + PAGE_SIZE);
if (start >= servers.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo servers")
.addLoreLine("&7No servers on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
String srv = servers.get(i);
inv.addButton(makeServerButton(srv));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeServerButton(final String server) {
ItemBuilder item = new ItemBuilder(Material.PAPER).setName("&a" + AdminVoteLogHelpers.safe(server))
.addLoreLine("&7Click to open votelog for this server")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogServer(plugin, clickEvent.getPlayer(), table, server, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,204 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: VoteLog entries for a given service/site (paged).
*
* Uses VoteLogMysqlTable instance passed in from CommandLoader.
*/
public class AdminVoteLogService extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int page;
private final String service;
private final int days;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogService.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param service the service name
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogService(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, String service,
int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.service = service;
this.days = days;
this.page = Math.max(0, page);
if (sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
/**
* Constructor for AdminVoteLogService with user.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param service the service name
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogService(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, String service, int days, int page) {
this(plugin, sender, table, service, days, page);
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
BInventory inv = new BInventory("&aVoteLog - Service &7(" + AdminVoteLogHelpers.safe(service) + ")");
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<VoteLogMysqlTable.VoteLogEntry> rows = table.getByService(service, days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(rows.size(), start + PAGE_SIZE);
if (start >= rows.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo entries")
.addLoreLine("&7No vote log entries on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
inv.addButton(makeEntryButton(rows.get(i)));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeEntryButton(final VoteLogMysqlTable.VoteLogEntry entry) {
VoteLogMysqlTable.VoteLogEvent event = entry.event != null ? VoteLogMysqlTable.VoteLogEvent.valueOf(entry.event)
: null;
Material mat = AdminVoteLogHelpers.getMaterialForEvent(event, entry.status);
String eventColor = AdminVoteLogHelpers.getEventColor(event);
String timeStr = AdminVoteLogHelpers.formatTime(entry.voteTime);
String uuidShort = AdminVoteLogHelpers.shortUuid(entry.playerUuid);
String voteShort = AdminVoteLogHelpers.shortUuid(entry.voteId);
ItemBuilder item = new ItemBuilder(mat)
.setName(eventColor + AdminVoteLogHelpers.safe(entry.event) + " &7(" + voteShort + ")");
if (AdminVoteLogHelpers.notEmpty(entry.playerName) || AdminVoteLogHelpers.notEmpty(entry.playerUuid)) {
item.addLoreLine("&7Player: &f" + AdminVoteLogHelpers.safe(entry.playerName) + " &7(" + uuidShort + ")");
}
if (entry.voteTime > 0) {
item.addLoreLine("&7Time: &f" + timeStr);
}
if (AdminVoteLogHelpers.notEmpty(entry.service)) {
item.addLoreLine("&7Service: &f" + AdminVoteLogHelpers.safe(entry.service));
}
if (AdminVoteLogHelpers.notEmpty(entry.context)) {
item.addLoreLine("&7Context: &f" + AdminVoteLogHelpers.safe(entry.context));
}
if (AdminVoteLogHelpers.notEmpty(entry.status)) {
item.addLoreLine("&7Status: &f" + AdminVoteLogHelpers.safe(entry.status));
}
if (entry.proxyCachedTotal != 0) {
item.addLoreLine("&7Cached Total: &f" + entry.proxyCachedTotal);
}
if (AdminVoteLogHelpers.notEmpty(entry.voteId)) {
item.addLoreLine("&7VoteId: &f" + AdminVoteLogHelpers.safe(entry.voteId));
}
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
// vote_id is the correlation id
new AdminVoteLogVoteId(plugin, clickEvent.getPlayer(), table, entry.voteId, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,152 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select a service (distinct list), then open AdminVoteLogService.
*/
public class AdminVoteLogServiceSelect extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogServiceSelect.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogServiceSelect(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = Math.max(0, days);
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Services";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<String> services = table.getDistinctServices(days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(services.size(), start + PAGE_SIZE);
if (start >= services.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo services")
.addLoreLine("&7No services on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
String svc = services.get(i);
inv.addButton(makeServiceButton(svc));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeServiceButton(final String service) {
ItemBuilder item = new ItemBuilder(Material.PAPER).setName("&a" + AdminVoteLogHelpers.safe(service))
.addLoreLine("&7Click to open votelog for this service")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogService(plugin, clickEvent.getPlayer(), table, service, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,150 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: Select a service from DB (distinct services), then open
* AdminVoteLogService.
*/
public class AdminVoteLogServiceSelectAll extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int page;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogServiceSelectAll.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogServiceSelectAll(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
this.days = days;
this.page = Math.max(0, page);
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Services";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
List<String> services = table.getDistinctServices(days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(services.size(), start + PAGE_SIZE);
if (start >= services.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo services")
.addLoreLine("&7No services on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
}
});
} else {
for (int i = start; i < end; i++) {
String svc = services.get(i);
inv.addButton(makeServiceButton(svc));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeServiceButton(String service) {
ItemBuilder item = new ItemBuilder(Material.PAPER).setName("&a" + AdminVoteLogHelpers.safe(service))
.addLoreLine("&7Click to open votelog for this service")
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time");
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
new AdminVoteLogService(plugin, clickEvent.getPlayer(), table, service, days, 0).open();
}
};
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,239 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: VoteLog stats overview.
*
* Uses VoteLogMysqlTable instance passed in from CommandLoader.
*
* Shows: - total / immediate / cached counts (VoteLogCounts) - unique voters -
* top services - top servers
*/
public class AdminVoteLogStats extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int days;
private final int topServicesLimit;
private final int topServersLimit;
/**
* Constructor for AdminVoteLogStats.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param days the number of days to filter
*/
public AdminVoteLogStats(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, int days) {
this(plugin, sender, table, null, days, 10, 10);
}
/**
* Constructor for AdminVoteLogStats with user and top services limit.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param topServicesLimit the maximum number of top services to display
*/
public AdminVoteLogStats(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int topServicesLimit) {
this(plugin, sender, table, user, days, topServicesLimit, 10);
}
/**
* Constructor for AdminVoteLogStats with full parameters.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param days the number of days to filter
* @param topServicesLimit the maximum number of top services to display
* @param topServersLimit the maximum number of top servers to display
*/
public AdminVoteLogStats(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, int days, int topServicesLimit, int topServersLimit) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
this.days = Math.max(0, days);
this.topServicesLimit = topServicesLimit <= 0 ? 10 : topServicesLimit;
this.topServersLimit = topServersLimit <= 0 ? 10 : topServersLimit;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - Stats";
if (days > 0) {
title += " &7(" + days + "d)";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
// counts
VoteLogMysqlTable.VoteLogCounts counts = table.getCounts(days);
long uniques = table.getUniqueVoters(days);
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BOOK).setName("&aOverview")
.addLoreLine("&7Total Votes: &f" + counts.total).addLoreLine("&7Immediate: &f" + counts.immediate)
.addLoreLine("&7Cached: &f" + counts.cached).addLoreLine("&7Unique Voters: &f" + uniques)
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
// top services header
inv.addButton(new BInventoryButton(new ItemBuilder(Material.MAP).setName("&aTop Services")
.addLoreLine("&7Top " + topServicesLimit + " services/sites:")
.addLoreLine("&8(Click does nothing)")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
int shownServices = 0;
for (VoteLogMysqlTable.ServiceCount sc : table.getTopServices(days, topServicesLimit)) {
shownServices++;
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER)
.setName("&a#" + shownServices + " &f" + AdminVoteLogHelpers.safe(sc.service))
.addLoreLine("&7Votes: &f" + sc.votes)
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op (could open AdminVoteLogService in future)
}
});
}
if (shownServices == 0) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo service data")
.addLoreLine("&7No services found in the log.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
}
// top servers header
inv.addButton(new BInventoryButton(new ItemBuilder(Material.COMPASS).setName("&aTop Servers")
.addLoreLine("&7Top " + topServersLimit + " servers:").addLoreLine("&8(Click does nothing)")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
int shownServers = 0;
for (VoteLogMysqlTable.ServerCount sc : table.getTopServers(days, topServersLimit)) {
shownServers++;
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER)
.setName("&a#" + shownServers + " &f" + AdminVoteLogHelpers.safe(sc.server))
.addLoreLine("&7Votes: &f" + sc.votes)
.addLoreLine(days > 0 ? "&7Window: &fLast " + days + " days" : "&7Window: &fAll time")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op (could open AdminVoteLogServer in future)
}
});
}
if (shownServers == 0) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo server data")
.addLoreLine("&7No servers found in the log.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -0,0 +1,257 @@
package com.bencodez.votingplugin.commands.gui.admin.votelog;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votelog.VoteLogMysqlTable;
/**
* Admin GUI: VoteLog entries for a given voteId (paged).
*
* vote_id is NOT unique; this shows ALL rows for the correlation id.
*/
public class AdminVoteLogVoteId extends GUIHandler {
private final VotingPluginMain plugin;
private final VoteLogMysqlTable table;
private VotingPluginUser user;
private final int page;
private final String voteId;
private final int days;
private static final int PAGE_SIZE = 45;
/**
* Constructor for AdminVoteLogVoteId.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param voteId the vote ID to filter
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogVoteId(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table, String voteId,
int days, int page) {
super(plugin, sender);
this.plugin = plugin;
this.table = table;
this.voteId = voteId;
this.days = days;
this.page = Math.max(0, page);
if (sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
/**
* Constructor for AdminVoteLogVoteId with user.
*
* @param plugin the VotingPluginMain instance
* @param sender the command sender
* @param table the vote log table
* @param user the voting plugin user
* @param voteId the vote ID to filter
* @param days the number of days to filter
* @param page the page number
*/
public AdminVoteLogVoteId(VotingPluginMain plugin, CommandSender sender, VoteLogMysqlTable table,
VotingPluginUser user, String voteId, int days, int page) {
this(plugin, sender, table, voteId, days, page);
this.user = user;
if (this.user == null && sender instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) sender);
}
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
try {
String title = "&aVoteLog - VoteId";
if (voteId != null && !voteId.isEmpty()) {
title += " &7(" + shortId(voteId) + ")";
}
BInventory inv = new BInventory(title);
inv.requirePermission("VotingPlugin.Commands.AdminVote.VoteLog");
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
if (table == null) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.BARRIER).setName("&cVoteLog unavailable")
.addLoreLine("&7VoteLog MySQL table is not loaded/enabled.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
if (voteId == null || voteId.isEmpty()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo voteId provided")
.addLoreLine("&7Missing voteId.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
return;
}
int needed = (page + 1) * PAGE_SIZE;
// vote_id is not unique -> show ALL rows for it (paged)
List<VoteLogMysqlTable.VoteLogEntry> rows = table.getByVoteIdAll(voteId, days, needed);
int start = page * PAGE_SIZE;
int end = Math.min(rows.size(), start + PAGE_SIZE);
if (start >= rows.size()) {
inv.addButton(new BInventoryButton(new ItemBuilder(Material.PAPER).setName("&eNo entries")
.addLoreLine("&7No vote log entries on this page.").addLoreLine("&7Try going back a page.")) {
@Override
public void onClick(ClickEvent clickEvent) {
// no-op
}
});
} else {
for (int i = start; i < end; i++) {
inv.addButton(makeEntryButton(rows.get(i)));
}
}
inv.setPages(true);
inv.setMaxInvSize(54);
inv.openInventory(player);
} catch (Exception e) {
e.printStackTrace();
}
}
private BInventoryButton makeEntryButton(VoteLogMysqlTable.VoteLogEntry entry) {
VoteLogMysqlTable.VoteLogEvent event = entry.event != null ? VoteLogMysqlTable.VoteLogEvent.valueOf(entry.event)
: null;
Material mat = AdminVoteLogHelpers.getMaterialForEvent(event, entry.status);
String eventColor = AdminVoteLogHelpers.getEventColor(event);
String timeStr = formatTime(entry.voteTime);
String uuidShort = shortId(entry.playerUuid);
String voteShort = shortId(entry.voteId);
ItemBuilder item = new ItemBuilder(mat)
.setName(eventColor + AdminVoteLogHelpers.safe(entry.event) + " &7(" + voteShort + ")");
// Only add lore lines when the value is actually set / meaningful
// (prevents blank/0/default noise)
if (notEmpty(entry.playerName) || notEmpty(entry.playerUuid)) {
item.addLoreLine("&7Player: &f" + safe(entry.playerName) + " &7(" + uuidShort + ")");
}
if (entry.voteTime > 0) {
item.addLoreLine("&7Time: &f" + timeStr);
}
if (notEmpty(entry.service)) {
item.addLoreLine("&7Service: &f" + safe(entry.service));
}
if (notEmpty(entry.context)) {
item.addLoreLine("&7Context: &f" + safe(entry.context));
}
if (notEmpty(entry.status)) {
item.addLoreLine("&7Status: &f" + safe(entry.status));
}
if (entry.proxyCachedTotal != 0) {
item.addLoreLine("&7Cached Total: &f" + entry.proxyCachedTotal);
}
if (notEmpty(entry.voteId)) {
item.addLoreLine("&7VoteId: &f" + safe(entry.voteId));
}
return new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
// read-only
}
};
}
private String formatTime(long millis) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date(millis));
} catch (Exception e) {
return String.valueOf(millis);
}
}
private boolean notEmpty(String s) {
return s != null && !s.trim().isEmpty();
}
private String shortId(String s) {
if (s == null || s.isEmpty()) {
return "unknown";
}
return s.length() > 8 ? s.substring(0, 8) : s;
}
private String safe(String s) {
return s == null ? "" : s;
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -12,14 +12,23 @@ import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.valuerequest.ValueRequest;
import com.bencodez.advancedcore.api.valuerequest.listeners.StringListener;
import com.bencodez.simpleapi.valuerequest.StringListener;
import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin vote shop GUI handler.
*/
public class AdminVoteVoteShop extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteShop.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteShop(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
@@ -30,6 +39,11 @@ public class AdminVoteVoteShop extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
@Override
public void onBook(Player player) {
}
@@ -55,14 +69,15 @@ public class AdminVoteVoteShop extends GUIHandler {
@Override
public void onClick(ClickEvent clickEvent) {
new ValueRequest().requestString(player, new StringListener() {
new ValueRequest(plugin, plugin.getDialogService(), null).requestString(player, "", null, true,
"Enter item name", new StringListener() {
@Override
public void onInput(Player player, String value) {
plugin.getShopFile().createShop(value);
plugin.reload();
}
});
@Override
public void onInput(Player player, String value) {
plugin.getShopFile().createShop(value);
plugin.reload();
}
});
}
});
@@ -81,4 +96,4 @@ public class AdminVoteVoteShop extends GUIHandler {
open(GUIMethod.CHEST);
}
}
}
@@ -22,17 +22,32 @@ import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.command.gui.RewardEditGUI;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin vote shop item GUI handler.
*/
public class AdminVoteVoteShopItem extends GUIHandler {
private String identifier;
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteShopItem.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
* @param identifier the item identifier
*/
public AdminVoteVoteShopItem(VotingPluginMain plugin, CommandSender player, String identifier) {
super(plugin, player);
this.plugin = plugin;
this.identifier = identifier;
}
@Override
public void onDialog(Player player) {
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
@@ -14,15 +14,29 @@ import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.commands.gui.admin.AdminVoteConfirmation;
/**
* Admin vote shop item remove GUI handler.
*/
public class AdminVoteVoteShopItemRemove extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteShopItemRemove.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteShopItemRemove(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public void onDialog(Player player) {
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
@@ -13,15 +13,29 @@ import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Admin vote shop items GUI handler.
*/
public class AdminVoteVoteShopItems extends GUIHandler {
private VotingPluginMain plugin;
/**
* Constructor for AdminVoteVoteShopItems.
*
* @param plugin the VotingPluginMain instance
* @param player the command sender
*/
public AdminVoteVoteShopItems(VotingPluginMain plugin, CommandSender player) {
super(plugin, player);
this.plugin = plugin;
}
@Override
public void onDialog(Player player) {
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
@@ -18,11 +18,21 @@ import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
/**
* GUI handler for vote best/streak display.
*/
public class VoteBest extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructs a new vote best GUI.
*
* @param plugin the plugin instance
* @param player the command sender
* @param user the voting plugin user
*/
public VoteBest(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -47,6 +57,41 @@ public class VoteBest extends GUIHandler {
return ArrayUtils.colorize(msg);
}
@Override
public void onDialog(Player player) {
plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("HighestDailyTotal", "" + user.getHighestDailyTotal())
.placeholder("HighestWeeklyTotal", "" + user.getHighestWeeklyTotal())
.placeholder("HighestMonthlyTotal", "" + user.getHighestMonthlyTotal())
.title(plugin.getGui().getChestVoteBestName())
.body(plugin.getConfigFile().getFormatCommandsVoteBestTitle())
.columns(2)
.button(plugin.getGui().getChestVoteBestDayBestItem().getName(),
"&7Best daily total: &e%HighestDailyTotal%",
payload -> {
})
.button(plugin.getGui().getChestVoteBestWeekBestItem().getName(),
"&7Best weekly total: &e%HighestWeeklyTotal%",
payload -> {
})
.button(plugin.getGui().getChestVoteBestMonthBestItem().getName(),
"&7Best monthly total: &e%HighestMonthlyTotal%",
payload -> {
})
.button(plugin.getGui().isChestVoteBestBackButton() ? "&eBack" : "",
plugin.getGui().isChestVoteBestBackButton() ? "&7Return to previous menu" : "",
payload -> {
if (plugin.getGui().isChestVoteBestBackButton()) {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
}
})
.open();
}
@Override
public void onBook(Player player) {
// TODO
@@ -19,11 +19,21 @@ import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
/**
* GUI handler for vote interface.
*/
public class VoteGUI extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructs a new vote GUI.
*
* @param plugin the plugin instance
* @param player the command sender
* @param user the voting plugin user
*/
public VoteGUI(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -35,6 +45,58 @@ public class VoteGUI extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
if (this.user == null) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
}
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("points", "" + user.getPoints()).placeholder("player", user.getPlayerName())
.placeholder("top", plugin.getConfigFile().getVoteTopDefault())
.placeholder("sitesavailable", "" + user.getSitesNotVotedOn())
.title(plugin.getGui().getChestVoteGUIName()).body("&7Select an option").columns(2);
for (final String slot : plugin.getGui().getChestVoteGUISlots()) {
ItemBuilder builder = getItemSlot(slot, player);
String buttonText = builder.getName();
String tooltip = "";
if (builder.getLore() != null && !builder.getLore().isEmpty()) {
tooltip = builder.getLore().get(0);
}
dialog.button(buttonText, tooltip, payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked == null) {
return;
}
String cmd = plugin.getGui().getChestVoteGUISlotCommand(slot);
if (cmd.equalsIgnoreCase("none")) {
return;
}
if (!cmd.equals("")) {
clicked.performCommand(cmd);
} else {
plugin.getCommandLoader().processSlotClick(clicked, user, slot);
}
});
}
dialog.open();
}
/**
* Gets the item for a specific GUI slot.
*
* @param slot the slot name
* @param player the player
* @return the item builder for the slot
*/
private ItemBuilder getItemSlot(String slot, Player player) {
ItemBuilder builder = new ItemBuilder(plugin.getGui().getChestVoteGUISlotSection(slot));
@@ -207,6 +269,7 @@ public class VoteGUI extends GUIHandler {
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
}
@@ -11,17 +11,26 @@ import com.bencodez.advancedcore.api.command.CommandHandler;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.simpleapi.nms.NMSManager;
import com.bencodez.votingplugin.VotingPluginMain;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.TextComponent;
/**
* GUI handler for vote help display.
*/
public class VoteHelp extends GUIHandler {
private int page;
private VotingPluginMain plugin;
/**
* Constructs a new vote help GUI.
*
* @param plugin the plugin instance
* @param player the command sender
* @param page the page number
*/
public VoteHelp(VotingPluginMain plugin, CommandSender player, int page) {
super(plugin, player);
this.plugin = plugin;
@@ -33,6 +42,17 @@ public class VoteHelp extends GUIHandler {
return null;
}
@Override
public void onDialog(Player player) {
}
/**
* Generates help text with hover support.
*
* @param sender the command sender
* @return list of text components for help
*/
public ArrayList<TextComponent> helpText(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<>();
HashMap<String, TextComponent> unsorted = new HashMap<>();
@@ -64,6 +84,12 @@ public class VoteHelp extends GUIHandler {
return msg;
}
/**
* Generates legacy help text without hover support.
*
* @param sender the command sender
* @return list of text components for help
*/
public ArrayList<TextComponent> helpTextLegacy(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<>();
HashMap<String, TextComponent> unsorted = new HashMap<>();
@@ -106,15 +132,17 @@ public class VoteHelp extends GUIHandler {
open(GUIMethod.CHAT);
}
/**
* Generates vote help text with pagination.
*
* @param sender the command sender
* @return list of text components for help
*/
public ArrayList<TextComponent> voteHelpText(CommandSender sender) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<TextComponent> msg = new ArrayList<>();
ArrayList<TextComponent> text = new ArrayList<>();
if (NMSManager.getInstance().isVersion("1.12")) {
text = helpTextLegacy(sender);
} else {
text = helpText(sender);
}
text = helpText(sender);
int maxPage = text.size() / pagesize;
if ((text.size() % pagesize) != 0) {
@@ -1,6 +1,7 @@
package com.bencodez.votingplugin.commands.gui.player;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -17,14 +18,24 @@ import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
/**
* GUI handler for displaying last vote information.
*/
public class VoteLast extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructs a new VoteLast GUI handler.
*
* @param plugin the main plugin instance
* @param player the command sender
* @param user the voting plugin user
*/
public VoteLast(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -40,7 +51,7 @@ public class VoteLast extends GUIHandler {
msg.add(MessageAPI.replaceIgnoreCase(plugin.getConfigFile().getFormatCommandsVoteLastTitle(), "%player%",
playerName));
for (VoteSite voteSite : plugin.getVoteSitesEnabled()) {
for (VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!voteSite.isHidden()) {
msg.add(user.voteCommandLastLine(voteSite));
}
@@ -49,6 +60,50 @@ public class VoteLast extends GUIHandler {
return ArrayUtils.colorize(msg);
}
@Override
public void onDialog(Player player) {
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName()).title(plugin.getGui().getChestVoteLastName())
.body(plugin.getConfigFile().getFormatCommandsVoteLastTitle()).columns(2);
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (site.isHidden()) {
continue;
}
dialog.placeholder("sitename", site.getDisplayName()).button(site.getDisplayName(),
user.voteCommandLastLine(site), payload -> {
if (plugin.getGui().isChestVoteLastClickableLinks()) {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
VotingPluginUser clickedUser = plugin.getVotingPluginUserManager()
.getVotingPluginUser(clicked);
HashMap<String, String> placeholders = new HashMap<String, String>();
placeholders.put("voteurl", site.getVoteURL());
placeholders.put("sitename", site.getDisplayName());
placeholders.put("player", clicked.getName());
clickedUser.sendMessage(plugin.getGui().getChestVoteURLURLText(), placeholders);
}
}
});
}
if (plugin.getGui().isChestVoteLastBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public void onBook(Player player) {
// TODO
@@ -63,7 +118,7 @@ public class VoteLast extends GUIHandler {
public void onChest(Player player) {
BInventory inv = new BInventory(plugin.getGui().getChestVoteLastName());
inv.addPlaceholder("player", user.getPlayerName());
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!site.isHidden()) {
inv.addButton(inv.getNextSlot(),
new UpdatingBInventoryButton(plugin, site.getItem().setName(site.getDisplayName())
@@ -19,16 +19,26 @@ import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import xyz.upperlevel.spigot.book.BookUtil;
/**
* GUI handler for displaying next vote information.
*/
public class VoteNext extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Constructs a new VoteNext GUI handler.
*
* @param plugin the main plugin instance
* @param player the command sender
* @param user the voting plugin user
*/
public VoteNext(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -44,7 +54,7 @@ public class VoteNext extends GUIHandler {
msg.add(MessageAPI.colorize(MessageAPI
.replaceIgnoreCase(plugin.getConfigFile().getFormatCommandsVoteNextTitle(), "%player%", playerName)));
for (VoteSite voteSite : plugin.getVoteSitesEnabled()) {
for (VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!voteSite.isHidden()) {
String msgLine = plugin.getConfigFile().getFormatCommandsVoteNextLayout();
@@ -57,12 +67,53 @@ public class VoteNext extends GUIHandler {
return msg;
}
@Override
public void onDialog(Player player) {
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName()).title(plugin.getGui().getChestVoteNextName())
.body(plugin.getConfigFile().getFormatCommandsVoteNextTitle()).columns(2);
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (site.isHidden()) {
continue;
}
String siteNameDisplay = plugin.getGui().getChestVoteNextCustomSiteNamesDisplays(site.getKey());
if (siteNameDisplay.isEmpty()) {
siteNameDisplay = site.getDisplayName();
}
dialog.placeholder("sitename", site.getDisplayName()).placeholder("SiteName", site.getDisplayName())
.placeholder("info", user.voteCommandNextInfo(site))
.button(siteNameDisplay, user.voteCommandNextInfo(site), payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
clicked.sendMessage(user.voteCommandNextInfo(site));
}
});
}
if (plugin.getGui().isChestVoteNextBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public void onBook(Player player) {
BookWrapper book = new BookWrapper(plugin.getGui().getBookVoteURLBookGUITitle());
// add colors/config options
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!site.isHidden()) {
Layout nextLayout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
nextLayout.replaceTextComponent("[Json]",
@@ -86,7 +137,7 @@ public class VoteNext extends GUIHandler {
public void onChest(Player player) {
BInventory inv = new BInventory(plugin.getGui().getChestVoteNextName());
inv.addPlaceholder("player", user.getPlayerName());
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!site.isHidden()) {
String siteNameDisplay = plugin.getGui().getChestVoteNextCustomSiteNamesDisplays(site.getKey());
if (siteNameDisplay.isEmpty()) {
@@ -1,7 +1,6 @@
package com.bencodez.votingplugin.commands.gui.player;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -12,18 +11,35 @@ import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.advancedcore.api.rewards.RewardOptions;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.voteshop.VoteShopManager;
import com.bencodez.votingplugin.voteshop.service.VoteShopPurchaseResult;
import com.bencodez.votingplugin.voteshop.shop.VoteShopCategory;
import com.bencodez.votingplugin.voteshop.shop.VoteShopCategoryButton;
import com.bencodez.votingplugin.voteshop.shop.VoteShopDefinition;
import com.bencodez.votingplugin.voteshop.shop.VoteShopEntry;
import com.bencodez.votingplugin.voteshop.shop.VoteShopExtraItem;
import com.bencodez.votingplugin.voteshop.shop.VoteShopItem;
/**
* Main vote shop GUI.
*/
public class VoteShop extends GUIHandler {
private VotingPluginMain plugin;
private VotingPluginUser user;
/**
* Creates the GUI.
*
* @param plugin the plugin
* @param player the sender
* @param user the user
*/
public VoteShop(VotingPluginMain plugin, CommandSender player, VotingPluginUser user) {
super(plugin, player);
this.plugin = plugin;
@@ -31,7 +47,7 @@ public class VoteShop extends GUIHandler {
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@@ -41,180 +57,204 @@ public class VoteShop extends GUIHandler {
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
if (!plugin.getShopFile().isVoteShopEnabled()) {
player.sendMessage(MessageAPI.colorize(plugin.getShopFile().getVoteShopDisabled()));
VoteShopManager manager = plugin.getVoteShopManager();
VoteShopDefinition definition = manager.getDefinition();
if (!definition.isEnabled()) {
player.sendMessage(MessageAPI.colorize(definition.getDisabledMessage()));
return;
}
if (this.user == null) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
}
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
/*
* if (!plugin.getConfigFile().isExtraVoteShopCheck()) { user.cacheAsync(); }
*/
BInventory inv = new BInventory(plugin.getShopFile().getVoteShopName());
inv.addPlaceholder("points", "" + user.getPoints());
inv.addPlaceholder("sitesavailable", "" + user.getSitesNotVotedOn());
VotingPluginUser currentUser = getUser(player);
BInventory inv = new BInventory(definition.getTitle());
inv.addPlaceholder("points", String.valueOf(currentUser.getPoints()));
inv.addPlaceholder("sitesavailable", String.valueOf(currentUser.getSitesNotVotedOn()));
inv.dontClose();
for (final String identifier : plugin.getShopFile().getShopIdentifiers()) {
String perm = plugin.getShopFile().getVoteShopPermission(identifier);
boolean hasPerm = false;
if (perm.isEmpty()) {
hasPerm = true;
} else {
String p = "";
if (perm.startsWith("!")) {
p = PlaceholderUtils.replacePlaceHolders(player, perm.substring(1));
hasPerm = !player.hasPermission(p);
} else {
p = PlaceholderUtils.replacePlaceHolders(player, perm);
hasPerm = player.hasPermission(p);
}
if (!hasPerm) {
plugin.extraDebug("VoteShop: " + player.getName() + "/" + player.getUniqueId()
+ " does not have permission `" + p + "` for " + identifier);
}
}
int limit = plugin.getShopFile().getShopIdentifierLimit(identifier);
boolean limitPass = true;
if (limit > 0) {
if (user.getVoteShopIdentifierLimit(identifier) >= limit) {
limitPass = false;
}
}
if (!plugin.getShopFile().getVoteShopNotBuyable(identifier)) {
if ((hasPerm || !plugin.getShopFile().getVoteShopHideOnNoPermission(identifier))
&& (limitPass || !plugin.getShopFile().isVoteShopHideLimitedReached())) {
ItemBuilder builder = new ItemBuilder(plugin.getShopFile().getShopIdentifierSection(identifier));
inv.addButton(new BInventoryButton(builder) {
@Override
public void onClick(ClickEvent event) {
Player player = event.getWhoClicked();
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
if (plugin.getConfigFile().isExtraVoteShopCheck()) {
user.cache();
}
String identifier = (String) getData("identifier");
int limit = (int) getData("Limit");
int points = plugin.getShopFile().getShopIdentifierCost(identifier);
if (identifier != null) {
// if (plugin.getGui().getChestVoteShopCloseGUI(identifier)) {
// event.closeInventory();
// }
// limit fail-safe, should never be needed, except in rare cases
boolean limitPass = true;
if (limit > 0) {
if (user.getVoteShopIdentifierLimit(identifier) >= limit) {
limitPass = false;
}
}
if (limitPass) {
if (!plugin.getShopFile().isVoteShopRequireConfirmation(identifier)) {
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("identifier",
plugin.getShopFile().getShopIdentifierIdentifierName(identifier));
placeholders.put("points", "" + points);
placeholders.put("limit", "" + limit);
if (user.removePoints(points, true)) {
plugin.getLogger().info("VoteShop: " + user.getPlayerName() + "/"
+ user.getUUID() + " bought " + identifier + " for " + points);
if (plugin.getConfigFile().isTrackShopPurchases()) {
plugin.getServerData().addVoteShopPurchase(identifier);
}
plugin.getRewardHandler().giveReward(user, plugin.getShopFile().getData(),
plugin.getShopFile().getShopIdentifierRewardsPath(identifier),
new RewardOptions().setPlaceholders(placeholders));
user.sendMessage(PlaceholderUtils.replacePlaceHolder(
plugin.getShopFile().getVoteShopPurchase(identifier),
placeholders));
if (limit > 0) {
user.setVoteShopIdentifierLimit(identifier,
user.getVoteShopIdentifierLimit(identifier) + 1);
}
} else {
user.sendMessage(PlaceholderUtils.replacePlaceHolder(
plugin.getConfigFile().getFormatShopFailedMsg(), placeholders));
}
} else {
plugin.getBukkitScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
new VoteShopConfirm(plugin, player, user, identifier)
.open(GUIMethod.CHEST);
}
});
}
} else {
user.sendMessage(plugin.getShopFile().getVoteShopLimitReached());
}
plugin.getCommandLoader().processSlotClick(player, user, identifier);
if (plugin.getShopFile().isVoteShopReopenGUIOnPurchase()) {
plugin.getCommandLoader().processSlotClick(player, user, "shop");
}
}
}
}.addData("identifier", identifier).addData("Limit", limit));
}
} else {
if (hasPerm) {
ItemBuilder builder = new ItemBuilder(plugin.getShopFile().getShopIdentifierSection(identifier));
inv.addButton(new BInventoryButton(builder) {
@Override
public void onClick(ClickEvent event) {
user.sendMessage(plugin.getConfigFile().getFormatShopNotPurchasable());
}
}.addData("identifier", identifier).addData("Limit", limit));
}
for (VoteShopEntry entry : definition.getMainEntries().values()) {
if (entry instanceof VoteShopItem) {
addItemButton(inv, player, currentUser, (VoteShopItem) entry, null);
} else if (entry instanceof VoteShopCategoryButton) {
addCategoryButton(inv, player, currentUser, (VoteShopCategoryButton) entry);
}
}
for (final String str : plugin.getShopFile().getVoteShopExtraItems()) {
inv.addButton(new BInventoryButton(new ItemBuilder(plugin.getShopFile().getGUIVoteShopExtraItems(str))) {
@Override
public void onClick(ClickEvent clickEvent) {
plugin.getCommandLoader().processSlotClick(player, user, str);
new RewardBuilder(plugin.getShopFile().getData(),
"ExtraItems." + str + "." + clickEvent.getButton().getLastRewardsPath(player))
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
for (VoteShopExtraItem extraItem : definition.getExtraItems().values()) {
addExtraItemButton(inv, player, currentUser, extraItem);
}
if (plugin.getShopFile().isVoteShopBackButton()) {
inv.addButton(plugin.getCommandLoader().getBackButton(user));
if (definition.isBackButton()) {
inv.addButton(plugin.getCommandLoader().getBackButton(currentUser));
}
inv.openInventory(player);
}
/**
* Adds an item button.
*
* @param inv the inventory
* @param player the player
* @param currentUser the user
* @param item the item
* @param category the category, null for main shop
*/
protected void addItemButton(BInventory inv, final Player player, final VotingPluginUser currentUser,
final VoteShopItem item, final VoteShopCategory category) {
VoteShopPurchaseResult validation = plugin.getVoteShopManager().getPurchaseService().validatePurchase(player,
currentUser, item);
boolean hasPermission = plugin.getVoteShopManager().getPurchaseService().hasPermission(player,
item.getPermission());
if ((!hasPermission && item.isHideOnNoPermission()) || (validation == VoteShopPurchaseResult.LIMIT_REACHED
&& plugin.getVoteShopManager().getDefinition().isHideLimitedReached())) {
return;
}
inv.addButton(new BInventoryButton(new ItemBuilder(item.getDisplaySection())) {
@Override
public void onClick(ClickEvent event) {
VotingPluginUser clickedUser = getUser(event.getPlayer());
if (plugin.getConfigFile().isExtraVoteShopCheck()) {
clickedUser.cache();
}
if (item.isNotBuyable()) {
clickedUser.sendMessage(plugin.getConfigFile().getFormatShopNotPurchasable());
return;
}
VoteShopPurchaseResult clickValidation = plugin.getVoteShopManager().getPurchaseService()
.validatePurchase(event.getPlayer(), clickedUser, item);
if (clickValidation != VoteShopPurchaseResult.SUCCESS) {
plugin.getVoteShopManager().getPurchaseService().sendFailureMessage(event.getPlayer(), clickedUser,
item, clickValidation);
return;
}
if (item.isRequireConfirmation()) {
if (plugin.getShopFile().isShopConfirmPurchaseUseDialog()) {
new VoteShopConfirm(plugin, event.getPlayer(), clickedUser, item, category)
.open(GUIMethod.DIALOG);
return;
} else {
new VoteShopConfirm(plugin, event.getPlayer(), clickedUser, item, category)
.open(GUIMethod.CHEST);
return;
}
}
handlePurchase(event.getPlayer(), clickedUser, item, category);
}
}.addData("identifier", item.getIdentifier()));
}
/**
* Adds a category button.
*
* @param inv the inventory
* @param player the player
* @param currentUser the user
* @param button the button
*/
protected void addCategoryButton(BInventory inv, final Player player, final VotingPluginUser currentUser,
final VoteShopCategoryButton button) {
boolean hasPermission = plugin.getVoteShopManager().getPurchaseService().hasPermission(player,
button.getPermission());
if (!hasPermission && button.isHideOnNoPermission()) {
return;
}
final VoteShopCategory category = plugin.getVoteShopManager().getCategory(button.getCategoryId());
if (category == null) {
plugin.extraDebug(
"VoteShop: missing category '" + button.getCategoryId() + "' for entry " + button.getIdentifier());
return;
}
inv.addButton(new BInventoryButton(new ItemBuilder(button.getDisplaySection())) {
@Override
public void onClick(ClickEvent event) {
new VoteShopCategoryMenu(plugin, event.getPlayer(), currentUser, category).open(GUIMethod.CHEST);
}
}.addData("identifier", button.getIdentifier()));
}
/**
* Adds an extra item button.
*
* @param inv the inventory
* @param player the player
* @param currentUser the user
* @param extraItem the extra item
*/
protected void addExtraItemButton(BInventory inv, final Player player, final VotingPluginUser currentUser,
final VoteShopExtraItem extraItem) {
inv.addButton(new BInventoryButton(new ItemBuilder(extraItem.getDisplaySection())) {
@Override
public void onClick(ClickEvent clickEvent) {
plugin.getCommandLoader().processSlotClick(player, currentUser, extraItem.getIdentifier());
new RewardBuilder(plugin.getShopFile().getData(),
"ExtraItems." + extraItem.getIdentifier() + "."
+ clickEvent.getButton().getLastRewardsPath(player))
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
}
/**
* Handles a completed purchase.
*
* @param player the player
* @param currentUser the user
* @param item the item
* @param category the category or null
*/
protected void handlePurchase(Player player, VotingPluginUser currentUser, VoteShopItem item,
VoteShopCategory category) {
VoteShopPurchaseResult result = plugin.getVoteShopManager().purchase(player, currentUser, item);
if (result != VoteShopPurchaseResult.SUCCESS) {
plugin.getVoteShopManager().getPurchaseService().sendFailureMessage(player, currentUser, item, result);
return;
}
plugin.getCommandLoader().processSlotClick(player, currentUser, item.getIdentifier());
if (plugin.getVoteShopManager().getDefinition().isReopenGuiOnPurchase()) {
if (category != null) {
new VoteShopCategoryMenu(plugin, player, currentUser, category).open(GUIMethod.CHEST);
} else {
plugin.getCommandLoader().processSlotClick(player, currentUser, "shop");
}
}
}
/**
* Gets the current user.
*
* @param player the player
* @return the user
*/
protected VotingPluginUser getUser(Player player) {
if (user == null) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
}
return plugin.getVotingPluginUserManager().getVotingPluginUser(player);
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
}
@@ -0,0 +1,167 @@
package com.bencodez.votingplugin.commands.gui.player;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.gui.GUIHandler;
import com.bencodez.advancedcore.api.gui.GUIMethod;
import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.voteshop.shop.VoteShopCategory;
import com.bencodez.votingplugin.voteshop.shop.VoteShopCategoryButton;
import com.bencodez.votingplugin.voteshop.shop.VoteShopEntry;
import com.bencodez.votingplugin.voteshop.shop.VoteShopItem;
/**
* Vote shop category GUI.
*/
public class VoteShopCategoryMenu extends GUIHandler {
private VoteShopCategory category;
private VotingPluginMain plugin;
@SuppressWarnings("unused")
private VotingPluginUser user;
/**
* Creates the GUI.
*
* @param plugin the plugin
* @param player the sender
* @param user the user
* @param category the category
*/
public VoteShopCategoryMenu(VotingPluginMain plugin, CommandSender player, VotingPluginUser user,
VoteShopCategory category) {
super(plugin, player);
this.plugin = plugin;
this.user = user;
this.category = category;
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@Override
public void onBook(Player player) {
}
@Override
public void onChat(CommandSender sender) {
}
@Override
public void onDialog(Player player) {
}
@Override
public void onChest(Player player) {
if (!plugin.getVoteShopManager().getDefinition().isEnabled()) {
player.sendMessage(MessageAPI.colorize(plugin.getVoteShopManager().getDefinition().getDisabledMessage()));
return;
}
VotingPluginUser currentUser = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
BInventory inv = new BInventory(category.getName());
inv.addPlaceholder("points", String.valueOf(currentUser.getPoints()));
inv.addPlaceholder("sitesavailable", String.valueOf(currentUser.getSitesNotVotedOn()));
inv.dontClose();
for (VoteShopEntry entry : category.getEntries().values()) {
if (entry instanceof VoteShopItem) {
addItemButton(inv, player, currentUser, (VoteShopItem) entry);
} else if (entry instanceof VoteShopCategoryButton) {
addCategoryButton(inv, player, currentUser, (VoteShopCategoryButton) entry);
}
}
if (category.isBackButton()) {
addBackButton(inv, player, currentUser, category.getId());
}
inv.openInventory(player);
}
private void addBackButton(BInventory inv, Player player, VotingPluginUser user, String category) {
if (!plugin.getShopFile().isCategoryBackButtonEnabled(category)) {
return;
}
ConfigurationSection section = plugin.getShopFile().getCategoryBackButtonItem(category);
if (section == null) {
section = plugin.getShopFile().getDefaultBackButtonItem();
}
ItemBuilder builder;
if (section != null) {
builder = new ItemBuilder(section);
} else {
builder = new ItemBuilder(Material.ARROW);
builder.setName("&cBack");
}
inv.addButton(new BInventoryButton(builder) {
@Override
public void onClick(ClickEvent event) {
new VoteShop(plugin, player, user).open();
}
});
}
/**
* Adds an item button.
*
* @param inv the inventory
* @param player the player
* @param currentUser the user
* @param item the item
*/
protected void addItemButton(BInventory inv, final Player player, final VotingPluginUser currentUser,
final VoteShopItem item) {
new VoteShop(plugin, player, currentUser).addItemButton(inv, player, currentUser, item, category);
}
/**
* Adds a category button.
*
* @param inv the inventory
* @param player the player
* @param currentUser the user
* @param button the button
*/
protected void addCategoryButton(BInventory inv, final Player player, final VotingPluginUser currentUser,
final VoteShopCategoryButton button) {
inv.addButton(new BInventoryButton(new ItemBuilder(button.getDisplaySection())) {
@Override
public void onClick(ClickEvent event) {
VoteShopCategory target = plugin.getVoteShopManager().getCategory(button.getCategoryId());
if (target != null) {
new VoteShopCategoryMenu(plugin, event.getPlayer(), currentUser, target).open(GUIMethod.CHEST);
}
}
});
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
@@ -1,7 +1,6 @@
package com.bencodez.votingplugin.commands.gui.player;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -12,27 +11,46 @@ import com.bencodez.advancedcore.api.inventory.BInventory;
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.RewardOptions;
import com.bencodez.simpleapi.player.PlayerUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.voteshop.service.VoteShopPurchaseResult;
import com.bencodez.votingplugin.voteshop.shop.VoteShopCategory;
import com.bencodez.votingplugin.voteshop.shop.VoteShopItem;
/**
* Confirmation GUI for vote shop purchases.
*/
public class VoteShopConfirm extends GUIHandler {
private String identifier;
private VoteShopCategory category;
private VoteShopItem item;
private VotingPluginMain plugin;
private VotingPluginUser user;
public VoteShopConfirm(VotingPluginMain plugin, CommandSender player, VotingPluginUser user, String identifier) {
/**
* Creates the GUI.
*
* @param plugin the plugin
* @param player the sender
* @param user the user
* @param item the item
* @param category the category or null
*/
public VoteShopConfirm(VotingPluginMain plugin, CommandSender player, VotingPluginUser user, VoteShopItem item,
VoteShopCategory category) {
super(plugin, player);
this.plugin = plugin;
this.user = user;
this.identifier = identifier;
this.item = item;
this.category = category;
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
public ArrayList<String> getChat(CommandSender sender) {
return null;
}
@@ -45,8 +63,8 @@ public class VoteShopConfirm extends GUIHandler {
}
@Override
public void onChest(Player player) {
PlayerUtils.setPlayerMeta(plugin, player, "ident", identifier);
public void onChest(final Player player) {
PlayerUtils.setPlayerMeta(plugin, player, "ident", item.getIdentifier());
BInventory inv = new BInventory(plugin.getShopFile().getShopConfirmPurchaseTitle());
inv.dontClose();
inv.addButton(new BInventoryButton(new ItemBuilder(plugin.getShopFile().getShopConfirmPurchaseYesItem())) {
@@ -54,57 +72,87 @@ public class VoteShopConfirm extends GUIHandler {
@Override
public void onClick(ClickEvent event) {
user.cache();
int points = plugin.getShopFile().getShopIdentifierCost(identifier);
int limit = plugin.getShopFile().getShopIdentifierLimit(identifier);
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("identifier", identifier);
placeholders.put("points", "" + points);
placeholders.put("limit", "" + limit);
if (user.removePoints(points, true)) {
plugin.getLogger().info("VoteShop: " + user.getPlayerName() + "/" + user.getUUID() + " bought "
+ identifier + " for " + points);
if (plugin.getConfigFile().isTrackShopPurchases()) {
plugin.getServerData().addVoteShopPurchase(identifier);
}
plugin.getRewardHandler().giveReward(user, plugin.getShopFile().getData(),
plugin.getShopFile().getShopIdentifierRewardsPath(identifier),
new RewardOptions().setPlaceholders(placeholders));
user.sendMessage(PlaceholderUtils
.replacePlaceHolder(plugin.getShopFile().getVoteShopPurchase(identifier), placeholders));
if (limit > 0) {
user.setVoteShopIdentifierLimit(identifier, user.getVoteShopIdentifierLimit(identifier) + 1);
}
} else {
user.sendMessage(PlaceholderUtils
.replacePlaceHolder(plugin.getConfigFile().getFormatShopFailedMsg(), placeholders));
}
if (plugin.getShopFile().getVoteShopCloseGUI(identifier)) {
event.getButton().getInv().closeInv(player, null);
} else {
new VoteShop(plugin, event.getPlayer(), user).open();
VoteShopPurchaseResult result = plugin.getVoteShopManager().purchase(player, user, item);
if (result != VoteShopPurchaseResult.SUCCESS) {
plugin.getVoteShopManager().getPurchaseService().sendFailureMessage(player, user, item, result);
returnToPrevious(event.getPlayer());
return;
}
plugin.getCommandLoader().processSlotClick(player, user, item.getIdentifier());
if (item.isCloseGUI()) {
event.closeInventory();
} else {
returnToPrevious(event.getPlayer());
}
}
});
inv.addButton(new BInventoryButton(new ItemBuilder(plugin.getShopFile().getShopConfirmPurchaseNoItem())) {
@Override
public void onClick(ClickEvent event) {
if (plugin.getShopFile().getVoteShopCloseGUI(identifier)) {
event.getButton().getInv().closeInv(player, null);
if (item.isCloseGUI()) {
event.closeInventory();
} else {
new VoteShop(plugin, event.getPlayer(), user).open();
returnToPrevious(event.getPlayer());
}
}
});
inv.openInventory(player);
}
@Override
public void onDialog(Player player) {
PlayerUtils.setPlayerMeta(plugin, player, "ident", item.getIdentifier());
plugin.getDialogService().confirmation(player).placeholder("player", user.getPlayerName())
.placeholder("identifier", item.getIdentifier())
.title(plugin.getShopFile().getShopConfirmPurchaseTitle())
.body("&7Confirm purchase of &e%identifier%&7?")
.yesText(new ItemBuilder(plugin.getShopFile().getShopConfirmPurchaseYesItem()).getName())
.noText(new ItemBuilder(plugin.getShopFile().getShopConfirmPurchaseNoItem()).getName())
.onYes(payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked == null) {
return;
}
user.cache();
VoteShopPurchaseResult result = plugin.getVoteShopManager().purchase(clicked, user, item);
if (result != VoteShopPurchaseResult.SUCCESS) {
plugin.getVoteShopManager().getPurchaseService().sendFailureMessage(clicked, user, item,
result);
returnToPrevious(clicked);
return;
}
plugin.getCommandLoader().processSlotClick(clicked, user, item.getIdentifier());
if (!item.isCloseGUI()) {
returnToPrevious(clicked);
}
}).onNo(payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
returnToPrevious(clicked);
}
}).open();
}
/**
* Returns to the previous GUI.
*
* @param player the player
*/
protected void returnToPrevious(Player player) {
if (category != null) {
new VoteShopCategoryMenu(plugin, player, user, category).open(GUIMethod.CHEST);
} else {
new VoteShop(plugin, player, user).open(GUIMethod.CHEST);
}
}
@Override
public void open() {
open(GUIMethod.CHEST);
}
}
}
@@ -29,6 +29,57 @@ public class VoteStreak extends GUIHandler {
this.plugin = plugin;
this.user = user;
}
@Override
public void onDialog(Player player) {
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("DailyStreak", "" + user.getDayVoteStreak())
.placeholder("WeeklyStreak", "" + user.getWeekVoteStreak())
.placeholder("MonthlyStreak", "" + user.getMonthVoteStreak())
.placeholder("BestDailyStreak", "" + user.getBestDayVoteStreak())
.placeholder("BestWeeklyStreak", "" + user.getBestWeekVoteStreak())
.placeholder("BestMonthlyStreak", "" + user.getBestMonthVoteStreak())
.title(plugin.getGui().getChestVoteStreakName())
.body(plugin.getConfigFile().getFormatCommandsVoteStreakTitle())
.columns(2);
dialog.button(plugin.getGui().getChestVoteStreakCurrentDayStreakItem().getName(),
"&7Current daily streak: &e%DailyStreak%",
payload -> {
});
dialog.button(plugin.getGui().getChestVoteStreakCurrentWeekStreakItem().getName(),
"&7Current weekly streak: &e%WeeklyStreak%",
payload -> {
});
dialog.button(plugin.getGui().getChestVoteStreakCurrentMonthStreakItem().getName(),
"&7Current monthly streak: &e%MonthlyStreak%",
payload -> {
});
dialog.button(plugin.getGui().getChestVoteStreakHighestDayStreakItem().getName(),
"&7Best daily streak: &e%BestDailyStreak%",
payload -> {
});
dialog.button(plugin.getGui().getChestVoteStreakHighestWeekStreakItem().getName(),
"&7Best weekly streak: &e%BestWeeklyStreak%",
payload -> {
});
dialog.button(plugin.getGui().getChestVoteStreakHighestMonthStreakItem().getName(),
"&7Best monthly streak: &e%BestMonthlyStreak%",
payload -> {
});
if (plugin.getGui().isChestVoteStreakBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
@@ -19,11 +19,10 @@ import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.nms.NMSManager;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.topvoter.TopVoterPlayer;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
public class VoteToday extends GUIHandler {
@@ -38,6 +37,49 @@ public class VoteToday extends GUIHandler {
this.page = page;
}
@Override
public void onDialog(Player player) {
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName()).placeholder("page", "" + page)
.title(plugin.getGui().getChestVoteTodayName())
.body(String.join("\n", plugin.getConfigFile().getFormatCommandsVoteTodayTitle())).columns(2);
for (TopVoterPlayer topPlayer : plugin.getVoteToday().keySet()) {
for (VoteSite voteSite : plugin.getVoteToday().get(topPlayer).keySet()) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(plugin.getConfigFile().getFormatTimeFormat());
String timeString = plugin.getVoteToday().get(topPlayer).get(voteSite).format(formatter);
final UUID uuid = topPlayer.getUuid();
dialog.placeholder("player", topPlayer.getPlayerName()).placeholder("votesite", voteSite.getKey())
.placeholder("sitename", voteSite.getDisplayName())
.placeholder("SiteName", voteSite.getDisplayName())
.placeholder("VoteSite", voteSite.getDisplayName()).placeholder("time", timeString)
.placeholder("Time", timeString).button("&e" + topPlayer.getPlayerName(),
plugin.getConfigFile().getFormatCommandsVoteTodayLine(), payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
VotingPluginUser clickedUser = plugin.getVotingPluginUserManager()
.getVotingPluginUser(uuid);
new VoteGUI(plugin, clicked, clickedUser).open(
GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
});
}
}
if (plugin.getGui().isChestVoteTodayBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
int pagesize = plugin.getConfigFile().getFormatPageSize();
@@ -85,28 +127,38 @@ public class VoteToday extends GUIHandler {
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
for (TopVoterPlayer user : plugin.getVoteToday().keySet()) {
for (TopVoterPlayer user : plugin.getVoteToday().keySet()) {
for (VoteSite voteSite : plugin.getVoteToday().get(user).keySet()) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(plugin.getConfigFile().getFormatTimeFormat());
String timeString = plugin.getVoteToday().get(user).get(voteSite).format(formatter);
String msg = plugin.getGui().getChestVoteTodayLine();
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesite", voteSite.getKey());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("SiteName", voteSite.getDisplayName());
placeholders.put("VoteSite", voteSite.getDisplayName());
placeholders.put("time", timeString);
placeholders.put("Time", timeString);
msg = PlaceholderUtils.replacePlaceHolder(msg, placeholders);
ItemBuilder item = null;
if (plugin.getGui().isChestVoteTodayUseSkull() && !NMSManager.getInstance().isVersion("1.12")) {
ItemBuilder item;
if (plugin.getGui().isChestVoteTodayUseSkull()) {
item = new ItemBuilder(user.getPlayerHead());
} else {
item = new ItemBuilder(plugin.getGui().getChestVoteTodayPlayerItem());
}
item.setName(PlaceholderUtils.replacePlaceHolder(plugin.getGui().getChestVoteTodayIconTitle(), "player",
user.getPlayerName()));
item.setLore(msg);
String title = PlaceholderUtils.replacePlaceHolder(plugin.getGui().getChestVoteTodayIconTitle(),
placeholders);
String lore = PlaceholderUtils.replacePlaceHolder(plugin.getGui().getChestVoteTodayLine(),
placeholders);
item.setName(title);
item.setLore(lore);
final UUID uuid = user.getUuid();
inv.addButton(inv.getNextSlot(), new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
@@ -121,16 +173,13 @@ public class VoteToday extends GUIHandler {
for (final String str : plugin.getGui().getChestGUIExtraItems(guiPath)) {
inv.addButton(
new BInventoryButton(new ItemBuilder(plugin.getGui().getChestGUIExtraItemsItem(guiPath, str))) {
@Override
public void onClick(ClickEvent clickEvent) {
new RewardBuilder(plugin.getGui().getData(),
"CHEST." + guiPath + ".ExtraItems." + str + "."
+ clickEvent.getButton().getLastRewardsPath(player))
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
}
@@ -155,7 +204,7 @@ public class VoteToday extends GUIHandler {
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesite", voteSite.getKey());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("time", timeString);
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
placeholders));
@@ -185,7 +234,7 @@ public class VoteToday extends GUIHandler {
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("player", user.getPlayerName());
placeholders.put("votesite", mostRecentSite.getKey());
placeholders.put("sitename", mostRecentSite.getDisplayName());
placeholders.put("sitename", mostRecentSite.getDisplayName());
placeholders.put("time", timeString);
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
placeholders));
@@ -41,6 +41,74 @@ public class VoteTopVoter extends GUIHandler {
this.top = top;
this.page = page;
}
@Override
public void onDialog(Player player) {
if (top == null) {
top = TopVoter.getDefault();
}
String topVoter = top.getName();
@SuppressWarnings("unchecked")
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin.getTopVoter(top)
.clone();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("topvoter", topVoter)
.title(plugin.getGui().getChestVoteTopName())
.body("&7Viewing &e%topvoter% &7top voters")
.columns(2);
int pos = 1;
for (Entry<TopVoterPlayer, Integer> entry : topVotes.entrySet()) {
final TopVoterPlayer topPlayer = entry.getKey();
final int votes = entry.getValue();
final int position = pos;
dialog.placeholder("position", "" + position)
.placeholder("player", topPlayer.getPlayerName())
.placeholder("votes", "" + votes)
.button(plugin.getGui().getChestVoteTopItemName(),
plugin.getGui().getChestVoteTopItemLore(),
payload -> {
if (plugin.getGui().isChestVoteTopOpenMainGUIOnClick()) {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, topPlayer.getUser()).open(
GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
}
});
pos++;
}
dialog.button("&eNext", "&7View next top voter board", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteTopVoter(plugin, clicked, user, top.next(), 0).open(GUIMethod.DIALOG);
}
});
dialog.button("&ePrevious", "&7View previous top voter board", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteTopVoter(plugin, clicked, user, top.prev(), 0).open(GUIMethod.DIALOG);
}
});
if (plugin.getGui().isChestVoteTopBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender sender) {
@@ -28,6 +28,50 @@ public class VoteTopVoterLastMonth extends GUIHandler {
this.plugin = plugin;
this.user = user;
}
@Override
public void onDialog(Player player) {
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getLastMonthTopVoter().entrySet();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("topvoter", "Last Month")
.title(plugin.getGui().getChestVoteTopName())
.body("&7Viewing &eLast Month &7top voters")
.columns(2);
int pos = 1;
for (Entry<TopVoterPlayer, Integer> entry : users) {
final TopVoterPlayer topPlayer = entry.getKey();
final int votes = entry.getValue();
final int position = pos;
dialog.placeholder("position", "" + position)
.placeholder("player", topPlayer.getPlayerName())
.placeholder("votes", "" + votes)
.button(plugin.getGui().getChestVoteTopItemName(),
plugin.getGui().getChestVoteTopItemLore(),
payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, topPlayer.getUser())
.open(GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
});
pos++;
}
if (plugin.getGui().isChestVoteTopBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
@@ -37,6 +37,84 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
this.user = user;
this.index = index;
}
@Override
public void onDialog(Player player) {
Set<YearMonth> months = plugin.getPreviousMonthsTopVoters().keySet();
List<YearMonth> yearMonthList = months.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
if (index < 0 || yearMonthList.isEmpty()) {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data");
return;
}
if (yearMonthList.size() <= index) {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data for requested index");
return;
}
YearMonth yearMonth = yearMonthList.get(index);
if (!plugin.getPreviousMonthsTopVoters().containsKey(yearMonth)) {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data");
return;
}
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("topvoter", yearMonth.toString())
.title(plugin.getGui().getChestVoteTopName())
.body("&7Viewing &e%topvoter% &7top voters")
.columns(2);
int pos = 1;
for (Entry<TopVoterPlayer, Integer> entry : users) {
final TopVoterPlayer topPlayer = entry.getKey();
final int votes = entry.getValue();
final int position = pos;
dialog.placeholder("position", "" + position)
.placeholder("player", topPlayer.getPlayerName())
.placeholder("votes", "" + votes)
.button(plugin.getGui().getChestVoteTopItemName(),
plugin.getGui().getChestVoteTopItemLore(),
payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, topPlayer.getUser())
.open(GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
});
pos++;
}
dialog.button("&eNext Month", "&7View older month", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteTopVoterPreviousMonths(plugin, clicked, user, index + 1).open(GUIMethod.DIALOG);
}
});
dialog.button("&ePrevious Month", "&7View newer month", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteTopVoterPreviousMonths(plugin, clicked, user, index - 1).open(GUIMethod.DIALOG);
}
});
if (plugin.getGui().isChestVoteTopBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
@@ -30,6 +30,42 @@ public class VoteTotal extends GUIHandler {
this.user = user;
}
@Override
public void onDialog(Player player) {
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
.placeholder("DailyTotal", "" + user.getTotal(TopVoter.Daily))
.placeholder("WeeklyTotal", "" + user.getTotal(TopVoter.Weekly))
.placeholder("MonthlyTotal", "" + user.getTotal(TopVoter.Monthly))
.placeholder("AllTimeTotal", "" + user.getTotal(TopVoter.AllTime))
.title(plugin.getGui().getChestVoteTotalName()).body("&7Vote totals for %player%").columns(2);
for (final TopVoter top : TopVoter.values()) {
dialog.placeholder("topvoter", top.getName()).placeholder("Total", "" + user.getTotal(top))
.button("%topvoter%", "&7Total: &e%Total%", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
clicked.sendMessage("&e" + top.getName() + ": &a" + user.getTotal(top));
}
});
}
if (plugin.getGui().isChestVoteTotalBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteGUI(plugin, clicked, user).open();
}
});
}
dialog.open();
}
@Override
public ArrayList<String> getChat(CommandSender arg0) {
ArrayList<String> msg = new ArrayList<>();
@@ -23,9 +23,9 @@ import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.topvoter.TopVoter;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import xyz.upperlevel.spigot.book.BookUtil;
@@ -43,11 +43,6 @@ public class VoteURL extends GUIHandler {
if (user == null && player instanceof Player) {
this.user = plugin.getVotingPluginUserManager().getVotingPluginUser((Player) player);
}
if (player != null && user != null && player.getName().equals(user.getPlayerName())) {
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders() && user.hasPrimaryAccount()) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(user.getPrimaryAccount());
}
}
}
@Override
@@ -64,7 +59,7 @@ public class VoteURL extends GUIHandler {
}
if (plugin.getConfigFile().isFormatCommandsVoteAutoInputSites()) {
int counter = 0;
for (VoteSite voteSite : plugin.getVoteSitesEnabled()) {
for (VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!voteSite.isHidden()) {
if (voteSite.getPermissionToView().isEmpty()
|| sender.hasPermission(voteSite.getPermissionToView())) {
@@ -101,6 +96,93 @@ public class VoteURL extends GUIHandler {
return ArrayUtils.colorize(sites);
}
@Override
public void onDialog(Player player) {
VotingPluginUser currentUser = this.user;
if (currentUser == null) {
currentUser = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
}
String body = "&7Select a vote site";
if (plugin.getConfigFile().getFormatCommandsVoteText() != null
&& !plugin.getConfigFile().getFormatCommandsVoteText().isEmpty()) {
body = String.join("\n", plugin.getConfigFile().getFormatCommandsVoteText());
}
final VotingPluginUser finalUser = currentUser;
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", finalUser.getPlayerName())
.placeholder("DailyTotal", "" + finalUser.getTotal(TopVoter.Daily))
.placeholder("WeekTotal", "" + finalUser.getTotal(TopVoter.Weekly))
.placeholder("MonthTotal", "" + finalUser.getTotal(TopVoter.Monthly))
.placeholder("Total", "" + finalUser.getTotal(TopVoter.AllTime))
.title(plugin.getGui().getChestVoteURLName()).body(body).columns(2);
if (plugin.getGui().isChestVoteURLViewAllUrlsButtonEnabled()) {
boolean canViewAll;
if (plugin.getGui().isChestVoteURLAllUrlsButtonrequireAllSitesVoted()) {
canViewAll = finalUser.canVoteAny();
} else {
canViewAll = finalUser.canVoteAll();
}
String allColor = canViewAll ? "&a" : "&c";
dialog.button(allColor + "All Voting Sites", "&7Show all vote URLs", payload -> {
VotingPluginUser payloadUser = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
json = true;
payloadUser.sendMessage(getChat(player, false));
});
}
for (final VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (voteSite.isHidden()) {
continue;
}
if (!voteSite.getPermissionToView().isEmpty() && !player.hasPermission(voteSite.getPermissionToView())) {
continue;
}
boolean canVote = finalUser.canVoteSite(voteSite);
String color = canVote ? "&a" : "&c";
dialog.placeholder("sitename", voteSite.getDisplayName())
.placeholder("SiteName", voteSite.getDisplayName())
.placeholder("servicesite", voteSite.getServiceSite())
.placeholder("ServiceSite", voteSite.getServiceSite())
.placeholder("VoteDelay", "" + voteSite.getVoteDelay())
.placeholder("VoteHour", "" + voteSite.getVoteDelayDailyHour())
.placeholder("Next", finalUser.voteCommandNextInfo(voteSite))
.button(color + voteSite.getDisplayName(),
canVote ? "&aClick to view vote link" : "&c" + finalUser.voteCommandNextInfo(voteSite),
payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
VotingPluginUser clickedUser = plugin.getVotingPluginUserManager()
.getVotingPluginUser(clicked);
HashMap<String, String> placeholders = new HashMap<String, String>();
placeholders.put("voteurl", voteSite.getVoteURL());
placeholders.put("sitename", voteSite.getDisplayName());
placeholders.put("player", clicked.getName());
placeholders.put("servicesite", voteSite.getServiceSite());
placeholders.put("VoteDelay", "" + voteSite.getVoteDelay());
placeholders.put("VoteHour", "" + voteSite.getVoteDelayDailyHour());
clickedUser.sendMessage(plugin.getGui().getChestVoteURLURLText(), placeholders);
}
});
}
if (plugin.getGui().isChestVoteURLBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> player.performCommand("vote gui"));
}
dialog.open();
}
private ItemBuilder getItemAll() {
ItemBuilder builderAll = new ItemBuilder(plugin.getGui().getChestVoteURLAlreadyVotedAllUrlsButtonItemSection());
if (plugin.getGui().isChestVoteURLAllUrlsButtonrequireAllSitesVoted()) {
@@ -154,7 +236,7 @@ public class VoteURL extends GUIHandler {
book.addLayout(layout);
}
int i = 1;
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!site.isHidden()) {
if (site.getPermissionToView().isEmpty() || player.hasPermission(site.getPermissionToView())) {
Layout layout = new Layout(plugin.getGui().getBookVoteURLBookGUILayout())
@@ -186,8 +268,26 @@ public class VoteURL extends GUIHandler {
@Override
public void onChest(Player player) {
// normal GUI
BInventory inv = new BInventory(plugin.getGui().getChestVoteURLName());
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
inv.dontClose();
}
for (final String str : plugin.getGui().getChestVoteURLExtraItems()) {
inv.addButton(new BInventoryButton(new ItemBuilder(plugin.getGui().getChestVoteURLExtraItemsItem(str))) {
@Override
public void onClick(ClickEvent clickEvent) {
new RewardBuilder(plugin.getGui().getData(),
"CHEST.VoteURL.ExtraItems." + str + "." + clickEvent.getButton().getLastRewardsPath(player))
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
}
if (plugin.getGui().isChestVoteURLViewAllUrlsButtonEnabled()) {
ItemBuilder builderAll = getItemAll();
@@ -195,6 +295,7 @@ public class VoteURL extends GUIHandler {
@Override
public void onClick(ClickEvent event) {
event.closeInventory();
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(event.getPlayer());
json = true;
if (event.getClick().equals(ClickType.SHIFT_LEFT)
@@ -213,11 +314,20 @@ public class VoteURL extends GUIHandler {
}
int startSlot = plugin.getGui().getChestVoteURLAllUrlsButtonStartSlot();
for (final VoteSite voteSite : plugin.getVoteSitesEnabled()) {
for (final VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (!voteSite.isHidden()) {
if (voteSite.getPermissionToView().isEmpty() || player.hasPermission(voteSite.getPermissionToView())) {
ItemBuilder builder = getItemVoteSite(voteSite);
if (startSlot >= 0) {
if (inv.isSlotTaken(startSlot)) {
boolean found = false;
while (!found) {
startSlot++;
if (!inv.isSlotTaken(startSlot)) {
found = true;
}
}
}
builder.setSlot(startSlot);
startSlot++;
}
@@ -226,6 +336,7 @@ public class VoteURL extends GUIHandler {
@Override
public void onClick(ClickEvent event) {
event.closeInventory();
Player player = event.getPlayer();
if (player != null) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
@@ -252,21 +363,6 @@ public class VoteURL extends GUIHandler {
}
}
for (
final String str : plugin.getGui().getChestVoteURLExtraItems()) {
inv.addButton(new BInventoryButton(new ItemBuilder(plugin.getGui().getChestVoteURLExtraItemsItem(str))) {
@Override
public void onClick(ClickEvent clickEvent) {
new RewardBuilder(plugin.getGui().getData(),
"CHEST.VoteURL.ExtraItems." + str + "." + clickEvent.getButton().getLastRewardsPath(player))
.setGiveOffline(false).send(clickEvent.getPlayer());
}
});
}
if (plugin.getGui().isChestVoteURLBackButton()) {
inv.addButton(plugin.getCommandLoader().getBackButton(user));
}
@@ -14,8 +14,8 @@ import com.bencodez.advancedcore.api.inventory.BInventoryButton;
import com.bencodez.advancedcore.api.inventory.UpdatingBInventoryButton;
import com.bencodez.advancedcore.api.item.ItemBuilder;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
public class VoteURLVoteSite extends GUIHandler {
@@ -47,11 +47,11 @@ public class VoteURLVoteSite extends GUIHandler {
@Override
public void onChest(Player player) {
if (!plugin.isVoteSite(voteSite)) {
if (!plugin.getVoteSiteManager().isVoteSite(voteSite)) {
player.sendMessage("Not a valid votesite");
return;
}
VoteSite site = plugin.getVoteSite(voteSite, true);
VoteSite site = plugin.getVoteSiteManager().getVoteSite(voteSite, true);
BInventory inv = new BInventory(plugin.getGui().getChestVoteURLSiteName());
inv.addPlaceholder("site", site.getDisplayName());
inv.setMeta(player, "VoteSite", site);
@@ -106,4 +106,56 @@ public class VoteURLVoteSite extends GUIHandler {
open(GUIMethod.CHEST);
}
@Override
public void onDialog(Player player) {
if (!plugin.getVoteSiteManager().isVoteSite(voteSite)) {
player.sendMessage("Not a valid votesite");
return;
}
VoteSite site = plugin.getVoteSiteManager().getVoteSite(voteSite, true);
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName()).placeholder("site", site.getDisplayName())
.placeholder("sitename", site.getDisplayName()).placeholder("SiteName", site.getDisplayName())
.placeholder("servicesite", site.getServiceSite()).placeholder("ServiceSite", site.getServiceSite())
.placeholder("VoteDelay", "" + site.getVoteDelay())
.placeholder("VoteHour", "" + site.getVoteDelayDailyHour())
.placeholder("Next", user.voteCommandNextInfo(site)).placeholder("Last", user.voteCommandLastLine(site))
.title(plugin.getGui().getChestVoteURLSiteName()).body("&7Site: &e%site%").columns(2);
dialog.button("&4URL", "&7Click to see URL", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
clicked.sendMessage(site.getVoteURL());
}
});
dialog.button("&4Next Vote", "%Next%", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteURL(plugin, clicked, user, true).open();
}
});
dialog.button("&4Last Vote", "%Last%", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteURL(plugin, clicked, user, true).open();
}
});
if (plugin.getGui().isChestVoteURLBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
new VoteURL(plugin, clicked, user, true).open();
}
});
}
dialog.open();
}
}
@@ -0,0 +1,141 @@
package com.bencodez.votingplugin.commands.tabcompleter;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandSendEvent;
import com.bencodez.votingplugin.VotingPluginMain;
/**
* Filters VotingPlugin command aliases from tab completion when aliases are
* disabled.
* <p>
* This listener ONLY hides aliases that are explicitly listed in VotingPlugin's
* plugin.yml under the "aliases:" section for the "vote" and "adminvote"
* commands.
* <p>
* It will NOT hide unrelated commands such as "/votechallenge" unless that
* exact command name is an alias defined in VotingPlugin's plugin.yml.
*/
public class AliasCommandFilterListener implements Listener {
private final VotingPluginMain plugin;
/**
* Cached lowercase alias names (without '/') that should be hidden when alias
* loading is disabled.
*/
private final Set<String> aliasesToHide;
/**
* Creates a new listener and caches aliases from VotingPlugin's plugin.yml.
*
* @param plugin VotingPlugin main instance
*/
public AliasCommandFilterListener(VotingPluginMain plugin) {
this.plugin = plugin;
this.aliasesToHide = buildAliasesToHide(plugin);
}
/**
* Removes VotingPlugin aliases from the player's available command list when
* alias loading is disabled.
*
* @param event Bukkit command send event
*/
@EventHandler
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
// Only hide when aliases feature is disabled
if (plugin.getConfigFile().isLoadCommandAliases()) {
return;
}
// Remove ONLY exact alias command names (not "vote*" prefixes)
event.getCommands().removeIf(this::shouldHideCommand);
}
/**
* Determines whether a specific command should be hidden.
*
* @param cmd Command name (without '/'), possibly namespaced (e.g.
* "otherplugin:vote")
* @return true if the command should be hidden
*/
private boolean shouldHideCommand(String cmd) {
String name = cmd.toLowerCase(Locale.ROOT);
// Never touch namespaced commands (otherplugin:vote)
if (name.contains(":")) {
return false;
}
// Always keep the primary commands visible
if (name.equals("vote") || name.equals("adminvote")) {
return false;
}
// Hide only exact aliases defined in VotingPlugin plugin.yml
return aliasesToHide.contains(name);
}
/**
* Builds the set of aliases to hide from VotingPlugin's plugin.yml.
* <p>
* Bukkit exposes the plugin.yml "commands" section via
* {@code plugin.getDescription().getCommands()}. Each command entry is a map
* that may contain an "aliases" key.
*
* @param plugin VotingPlugin main instance
* @return a lowercase set of alias command names
*/
private Set<String> buildAliasesToHide(VotingPluginMain plugin) {
Set<String> aliases = new HashSet<>();
Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
if (commands == null || commands.isEmpty()) {
return Collections.emptySet();
}
// Only consider aliases for these main commands
addAliasesFor(commands, "vote", aliases);
addAliasesFor(commands, "adminvote", aliases);
return Collections.unmodifiableSet(aliases);
}
/**
* Adds aliases for a given command from the plugin.yml commands map into the
* provided set.
*
* @param commandsMap full commands map from PluginDescriptionFile
* @param commandName the primary command to read aliases for (e.g. "vote")
* @param out output set to add lowercase alias names into
*/
@SuppressWarnings("unchecked")
private static void addAliasesFor(Map<String, Map<String, Object>> commandsMap, String commandName,
Set<String> out) {
Map<String, Object> cmdInfo = commandsMap.get(commandName);
if (cmdInfo == null) {
return;
}
Object aliasesObj = cmdInfo.get("aliases");
if (aliasesObj instanceof String) {
// plugin.yml also allows a single alias as a string
out.add(((String) aliasesObj).toLowerCase(Locale.ROOT));
} else if (aliasesObj instanceof Collection) {
for (Object o : (Collection<Object>) aliasesObj) {
if (o != null) {
out.add(o.toString().toLowerCase(Locale.ROOT));
}
}
}
}
}
@@ -98,6 +98,13 @@ public class AliasesTabCompleter implements TabCompleter {
return tab;
}
/**
* Set the command handler for this tab completer.
*
* @param cmd the command handler
* @param adminCommand whether this is an admin command
* @return this tab completer instance
*/
public AliasesTabCompleter setCMDHandle(CommandHandler cmd, boolean adminCommand) {
cmdHandle = cmd;
this.adminCommand = adminCommand;
@@ -13,16 +13,11 @@ import com.bencodez.votingplugin.VotingPluginMain;
import lombok.Getter;
/**
* Configuration file for Bungee/proxy settings.
*/
public class BungeeSettings extends YMLFile {
@ConfigDataBoolean(path = "BungeeBroadcast")
@Getter
private boolean bungeeBroadcast = false;
@ConfigDataBoolean(path = "BungeeBroadcastAlways")
@Getter
private boolean bungeeBroadcastAlways = false;
@ConfigDataBoolean(path = "BungeeDebug")
@Getter
private boolean bungeeDebug = false;
@@ -33,32 +28,36 @@ public class BungeeSettings extends YMLFile {
@ConfigDataString(path = "Redis.Host")
@Getter
private String RedisHost = "";
private String redisHost = "";
@ConfigDataString(path = "Redis.Username")
@Getter
private String RedisUsername = "";
private String redisUsername = "";
@ConfigDataInt(path = "Redis.Db-Index")
@Getter
private int redisdbindex = 0;
@ConfigDataString(path = "PluginMessageChannel")
@Getter
private String pluginMessagingChannel = "vp:vp";
@ConfigDataBoolean(path = "PluginMessageEncryption")
@Getter
private boolean pluginMessageEncryption = false;
@ConfigDataString(path = "Redis.Prefix")
@Getter
private String RedisPrefix = "";
private String redisPrefix = "";
@ConfigDataString(path = "Redis.Password")
@Getter
private String RedisPassword = "";
private String redisPassword = "";
@ConfigDataInt(path = "Redis.Port")
@Getter
private int RedisPort = 6379;
private int redisPort = 6379;
@ConfigDataString(path = "MQTT.ClientID")
@Getter
private String mqttClientID = "";
@@ -91,10 +90,6 @@ public class BungeeSettings extends YMLFile {
@Getter
private boolean perServerPoints = false;
@ConfigDataBoolean(path = "PerServerMilestones")
@Getter
private boolean perServerMilestones = false;
@ConfigDataBoolean(path = "GiveExtraAllSitesRewards")
@Getter
private boolean giveExtraAllSitesRewards = false;
@@ -131,10 +126,6 @@ public class BungeeSettings extends YMLFile {
@Getter
private boolean votifierBypass = false;
@ConfigDataBoolean(path = "DisableBroadcast")
@Getter
private boolean disableBroadcast = false;
@ConfigDataBoolean(path = "GlobalData.UseMainMySQL")
@Getter
private boolean globlalDataUseMainMySQL = true;
@@ -147,10 +138,21 @@ public class BungeeSettings extends YMLFile {
@Getter
private ArrayList<String> bungeeVotePartyGlobalCommands = new ArrayList<>();
/**
* Constructs a new BungeeSettings.
*
* @param plugin the main plugin instance
*/
public BungeeSettings(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "BungeeSettings.yml"));
setIgnoreCase(plugin.getConfigFile().isCaseInsensitiveYMLFiles());
}
/**
* Gets the server name formatted for storage.
*
* @return the formatted server name
*/
public String getServerNameStorage() {
return getServer().replace("-", "_");
}
@@ -14,6 +14,7 @@ import com.bencodez.simpleapi.file.annotation.ConfigDataBoolean;
import com.bencodez.simpleapi.file.annotation.ConfigDataInt;
import com.bencodez.simpleapi.file.annotation.ConfigDataKeys;
import com.bencodez.simpleapi.file.annotation.ConfigDataListString;
import com.bencodez.simpleapi.file.annotation.ConfigDataLong;
import com.bencodez.simpleapi.file.annotation.ConfigDataString;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.placeholders.PlaceholderCacheLevel;
@@ -51,6 +52,11 @@ public class Config extends YMLFile {
@Getter
private int limitVotePoints = -1;
/** Whether YAML files should be case insensitive. */
@ConfigDataBoolean(path = "CaseInsensitiveYMLFiles")
@Getter
public boolean caseInsensitiveYMLFiles = false;
@ConfigDataBoolean(path = "QueueVotesDuringTimeChange")
@Getter
private boolean queueVotesDuringTimeChange = false;
@@ -67,6 +73,220 @@ public class Config extends YMLFile {
@Getter
private boolean preloadSkulls = false;
@ConfigDataBoolean(path = "DiscordSRV.Enabled")
@Getter
private boolean discordSRVEnabled = false;
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.AllTime.Enabled")
@Getter
private boolean discordSRVTopVoterAllTimeEnabled = false;
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.AllTime.NewMessageOnUpdate")
@Getter
private boolean discordSRVTopVoterAllTimeNewMessageOnUpdate = false;
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Monthly.NewMessageOnUpdate")
@Getter
private boolean discordSRVTopVoterMonthlyNewMessageOnUpdate = false;
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Weekly.NewMessageOnUpdate")
@Getter
private boolean discordSRVTopVoterWeeklyNewMessageOnUpdate = false;
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Daily.NewMessageOnUpdate")
@Getter
private boolean discordSRVTopVoterDailyNewMessageOnUpdate = false;
@ConfigDataLong(path = "DiscordSRV.TopVoter.AllTime.Channel")
@Getter
private long discordSRVTopVoterAllTimeChannel = 0;
@ConfigDataString(path = "DiscordSRV.TopVoter.AllTime.Title")
@Getter
private String discordSRVTopVoterAllTimeTitle = "All Time Top Voters";
@ConfigDataString(path = "DiscordSRV.TopVoter.AllTime.RankDisplay")
@Getter
private String discordSRVTopVoterAllTimeRankDisplay = "%rank%: %player% - %votes% Votes";
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Monthly.Enabled")
@Getter
private boolean discordSRVTopVoterMonthlyEnabled = false;
@ConfigDataLong(path = "DiscordSRV.TopVoter.Monthly.Channel")
@Getter
private long discordSRVTopVoterMonthlyChannel = 0;
@ConfigDataString(path = "DiscordSRV.TopVoter.Monthly.Title")
@Getter
private String discordSRVTopVoterMonthlyTitle = "Top Voters of the Month";
@ConfigDataString(path = "DiscordSRV.TopVoter.Monthly.RankDisplay")
@Getter
private String discordSRVTopVoterMonthlyRankDisplay = "%rank%: %player% - %votes% Votes";
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Weekly.Enabled")
@Getter
private boolean discordSRVTopVoterWeeklyEnabled = false;
@ConfigDataLong(path = "DiscordSRV.TopVoter.Weekly.Channel")
@Getter
private long discordSRVTopVoterWeeklyChannel = 0;
@ConfigDataString(path = "DiscordSRV.TopVoter.Weekly.Title")
@Getter
private String discordSRVTopVoterWeeklyTitle = "Top Voters of the Week";
@ConfigDataString(path = "DiscordSRV.TopVoter.Weekly.RankDisplay")
@Getter
private String discordSRVTopVoterWeeklyRankDisplay = "%rank%: %player% - %votes% Votes";
@ConfigDataBoolean(path = "DiscordSRV.TopVoter.Daily.Enabled")
@Getter
private boolean discordSRVTopVoterDailyEnabled = false;
@ConfigDataLong(path = "DiscordSRV.TopVoter.Daily.Channel")
@Getter
private long discordSRVTopVoterDailyChannel = 0;
@ConfigDataString(path = "DiscordSRV.TopVoter.Daily.Title")
@Getter
private String discordSRVTopVoterDailyTitle = "Top Voters of the Day";
@ConfigDataString(path = "DiscordSRV.TopVoter.Daily.RankDisplay")
@Getter
private String discordSRVTopVoterDailyRankDisplay = "%rank%: %player% - %votes% Votes";
// VoteLogging configuration section - minimal options mirror Config.yml
@ConfigDataBoolean(path = "VoteLogging.Enabled")
@Getter
private boolean voteLoggingEnabled = false;
@ConfigDataInt(path = "VoteLogging.PurgeDays")
@Getter
private int voteLoggingPurgeDays = 30;
@ConfigDataBoolean(path = "VoteLogging.UseMainMySQL")
@Getter
private boolean voteLoggingUseMainMySQL = true;
/**
* Gets the vote logging configuration section.
*
* @return the vote logging configuration section
*/
public ConfigurationSection getVoteLoggingSection() {
if (!getData().isConfigurationSection("VoteLogging")) {
getData().createSection("VoteLogging");
}
return getData().getConfigurationSection("VoteLogging");
}
/**
* Checks if DiscordSRV top voter is enabled.
*
* @param topVoter the top voter type
* @return true if enabled
*/
public boolean isDiscordSRVTopVoterEnabled(TopVoter topVoter) {
switch (topVoter) {
case AllTime:
return isDiscordSRVTopVoterAllTimeEnabled();
case Monthly:
return isDiscordSRVTopVoterMonthlyEnabled();
case Weekly:
return isDiscordSRVTopVoterWeeklyEnabled();
case Daily:
return isDiscordSRVTopVoterDailyEnabled();
default:
return false;
}
}
/**
* Checks if DiscordSRV top voter should send a new message on update.
*
* @param topVoter the top voter type
* @return true if new message should be sent
*/
public boolean isDiscordSRVTopVoterNewMessageOnUpdate(TopVoter topVoter) {
switch (topVoter) {
case AllTime:
return isDiscordSRVTopVoterAllTimeNewMessageOnUpdate();
case Monthly:
return isDiscordSRVTopVoterMonthlyNewMessageOnUpdate();
case Weekly:
return isDiscordSRVTopVoterWeeklyNewMessageOnUpdate();
case Daily:
return isDiscordSRVTopVoterDailyNewMessageOnUpdate();
default:
return false;
}
}
/**
* Gets the DiscordSRV top voter channel ID.
*
* @param topVoter the top voter type
* @return the channel ID
*/
public long getDiscordSRVTopVoterChannel(TopVoter topVoter) {
switch (topVoter) {
case AllTime:
return getDiscordSRVTopVoterAllTimeChannel();
case Monthly:
return getDiscordSRVTopVoterMonthlyChannel();
case Weekly:
return getDiscordSRVTopVoterWeeklyChannel();
case Daily:
return getDiscordSRVTopVoterDailyChannel();
default:
return 0;
}
}
/**
* Gets the DiscordSRV top voter title.
*
* @param topVoter the top voter type
* @return the title
*/
public String getDiscordSRVTopVoterTitle(TopVoter topVoter) {
switch (topVoter) {
case AllTime:
return getDiscordSRVTopVoterAllTimeTitle();
case Monthly:
return getDiscordSRVTopVoterMonthlyTitle();
case Weekly:
return getDiscordSRVTopVoterWeeklyTitle();
case Daily:
return getDiscordSRVTopVoterDailyTitle();
default:
return "";
}
}
/**
* Gets the DiscordSRV top voter rank display format.
*
* @param topVoter the top voter type
* @return the rank display format
*/
public String getDiscordSRVTopVoterRankDisplay(TopVoter topVoter) {
switch (topVoter) {
case AllTime:
return getDiscordSRVTopVoterAllTimeRankDisplay();
case Monthly:
return getDiscordSRVTopVoterMonthlyRankDisplay();
case Weekly:
return getDiscordSRVTopVoterWeeklyRankDisplay();
case Daily:
return getDiscordSRVTopVoterDailyRankDisplay();
default:
return "";
}
}
@ConfigDataBoolean(path = "AllowUnJoinedCheckServer")
@Getter
private boolean allowUnJoinedCheckServer = true;
@@ -87,10 +307,6 @@ public class Config extends YMLFile {
@Getter
private boolean extraVoteShopCheck = true;
@ConfigDataBoolean(path = "TrackShopPurchases")
@Getter
private boolean trackShopPurchases = false;
@ConfigDataBoolean(path = "AlwaysUpdate")
@Getter
private boolean alwaysUpdate = false;
@@ -99,17 +315,13 @@ public class Config extends YMLFile {
@Getter
private boolean autoCreateVoteSites = true;
@ConfigDataBoolean(path = "Format.BroadcastVote")
@Getter
private boolean broadcastVotesEnabled = true;
@ConfigDataBoolean(path = "CountFakeVotes")
@Getter
private boolean countFakeVotes = true;
@ConfigDataInt(path = "DelayBetweenUpdates")
@ConfigDataString(path = "DelayBetweenUpdates")
@Getter
private int delayBetweenUpdates = 3;
private String delayBetweenUpdates = "3m";
@ConfigDataBoolean(path = "DisableAdvancedTab")
@Getter
@@ -139,6 +351,14 @@ public class Config extends YMLFile {
@Getter
private boolean disableNoServiceSiteMessage = false;
@ConfigDataString(path = "Format.Commands.AdminVote.Points.PlayerRemoved")
@Getter
private String formatCommandsAdminVotePointsPlayerRemoved = "&c%amount% voting points have been removed from you";
@ConfigDataString(path = "Format.Commands.AdminVote.Points.PlayerGiven")
@Getter
private String formatCommandsAdminVotePointsPlayerGiven = "&cYou have been given %amount% voting points";
@ConfigDataBoolean(path = "DisableUpdateChecking")
@Getter
private boolean disableUpdateChecking = false;
@@ -155,26 +375,6 @@ public class Config extends YMLFile {
@Getter
private boolean extraBackgroundUpdate = false;
@ConfigDataString(path = "Format.AlternateBroadcast.Broadcast")
@Getter
private String formatAlternateBroadcastBroadcast = "&6[&4Broadcast&6] &2%numberofplayers% voted in the last half hour! /vote";
@ConfigDataInt(path = "Format.AlternateBroadcast.Delay")
@Getter
private int formatAlternateBroadcastDelay = 30;
@ConfigDataBoolean(path = "Format.AlternateBroadcast.Enabled")
@Getter
private boolean formatAlternateBroadcastEnabled = false;
@ConfigDataBoolean(path = "Format.OnlyOneOfflineBroadcast")
@Getter
private boolean formatOnlyOneOfflineBroadcast = false;
@ConfigDataString(path = "Format.OfflineBroadcast")
@Getter
private String formatOfflineBroadcast = "&6[&4Broadcast&6] &2Thanks &c%player% &2for voting on %numberofvotes% times!";
@ConfigDataBoolean(path = "Format.Commands.Vote.ForceLinks")
@Getter
private boolean formatCommandsVoteForceLinks = true;
@@ -287,10 +487,6 @@ public class Config extends YMLFile {
@Getter
private boolean loadCommandAliases = true;
@ConfigDataBoolean(path = "LogVotesToFile")
@Getter
private boolean logVotesToFile = false;
@ConfigDataInt(path = "MaxiumNumberOfTopVotersToLoad")
@Getter
private int MaxiumNumberOfTopVotersToLoad = 1000;
@@ -323,10 +519,6 @@ public class Config extends YMLFile {
@Getter
private boolean useJavascriptPlaceholders = false;
@ConfigDataBoolean(path = "UsePrimaryAccountForPlaceholders")
@Getter
private boolean usePrimaryAccountForPlaceholders = false;
@ConfigDataBoolean(path = "UseVoteGUIMainCommand")
@Getter
private boolean useVoteGUIMainCommand = false;
@@ -347,14 +539,6 @@ public class Config extends YMLFile {
@Getter
private Set<String> customPlaceholderReturns = new HashSet<>();
@ConfigDataString(path = "Format.BroadcastMsg")
@Getter
private String formatBroadCastMsg = "&6[&4Broadcast&6] &2Thanks &c%player% &2for voting on %SiteName%";
@ConfigDataBoolean(path = "Format.BroadcastWhenOnline")
@Getter
private boolean formatBroadcastWhenOnline = false;
@ConfigDataBoolean(path = "Format.Commands.Vote.AutoInputSites")
@Getter
private boolean formatCommandsVoteAutoInputSites = true;
@@ -581,28 +765,22 @@ public class Config extends YMLFile {
@Getter
private boolean topVoterIgnorePermission = false;
@ConfigDataBoolean(path = "VoteReminding.Enabled")
@Getter
private boolean voteRemindingEnabled = true;
@ConfigDataInt(path = "VoteReminding.RemindDelay")
@Getter
private int voteRemindingRemindDelay = 30;
@ConfigDataBoolean(path = "VoteReminding.RemindOnLogin")
@Getter
private boolean voteRemindingRemindOnLogin = false;
@ConfigDataBoolean(path = "VoteReminding.RemindOnlyOnce")
@Getter
private boolean voteRemindingRemindOnlyOnce = false;
@ConfigDataString(path = "VoteTopDefault")
@Getter
private String voteTopDefault = "Monthly";
@ConfigDataBoolean(path = "AlwaysProcessAsyncPlaceholders")
@Getter
private boolean alwaysProcessAsyncPlaceholders = false;
/**
* Constructs a new Config.
*
* @param plugin the main plugin instance
*/
public Config(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "Config.yml"));
setIgnoreCase(true);
}
/**
@@ -615,10 +793,22 @@ public class Config extends YMLFile {
return (ArrayList<String>) getData().getList("BlackList", new ArrayList<>());
}
/**
* Gets the custom commands configuration section.
*
* @param ident the command identifier
* @return the configuration section
*/
public ConfigurationSection getCustomCommands(String ident) {
return getData().getConfigurationSection("CustomCommands." + ident);
}
/**
* Gets the custom placeholder return keys.
*
* @param placeholder the placeholder name
* @return set of return keys
*/
public Set<String> getCustomPlaceholderReturns(String placeholder) {
Set<String> str = getData().getConfigurationSection("CustomPlaceholderReturns." + placeholder).getKeys(false);
if (str == null) {
@@ -627,6 +817,13 @@ public class Config extends YMLFile {
return str;
}
/**
* Gets a custom placeholder return value.
*
* @param placeholder the placeholder name
* @param returnString the return key
* @return the return value
*/
public String getCustomPlaceholderReturns(String placeholder, String returnString) {
return getData().getString("CustomPlaceholderReturns." + placeholder + "." + returnString, "");
}
@@ -644,6 +841,11 @@ public class Config extends YMLFile {
}
/**
* Gets the vote streak lines format.
*
* @return list of format lines
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteStreakLines() {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Streak.Lines", new ArrayList<>());
@@ -661,6 +863,11 @@ public class Config extends YMLFile {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Text", str);
}
/**
* Gets the vote total format lines.
*
* @return list of format lines
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotal() {
ArrayList<String> list = (ArrayList<String>) getData().getList("Format.Commands.Vote.Total", new ArrayList<>());
@@ -674,6 +881,11 @@ public class Config extends YMLFile {
return list;
}
/**
* Gets the vote total all format lines.
*
* @return list of format lines
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getFormatCommandsVoteTotalAll() {
@@ -699,6 +911,12 @@ public class Config extends YMLFile {
return (ArrayList<String>) getData().getList("Format.Commands.Vote.Help.Lines", new ArrayList<>());
}
/**
* Checks if a top voter type should be loaded.
*
* @param top the top voter type
* @return true if should be loaded
*/
public boolean getLoadTopVoter(TopVoter top) {
switch (top) {
case AllTime:
@@ -714,19 +932,15 @@ public class Config extends YMLFile {
}
}
/**
* Gets the placeholder cache level.
*
* @return the cache level
*/
public PlaceholderCacheLevel getPlaceholderCacheLevel() {
return PlaceholderCacheLevel.getCache(getPlaceholderCacheLevelString());
}
/**
* Gets the rewards.
*
* @return the rewards
*/
public String getVoteRemindingRewardsPath() {
return "VoteReminding.Rewards";
}
@Override
public void loadValues() {
new AnnotationHandler().load(getData(), this);
@@ -5,6 +5,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -17,8 +18,9 @@ import com.bencodez.advancedcore.api.rewards.DirectlyDefinedReward;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.simpleapi.file.YMLFile;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.simpleapi.time.ParsedDuration;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.votesites.VoteSite;
// TODO: Auto-generated Javadoc
/**
@@ -28,8 +30,14 @@ public class ConfigVoteSites extends YMLFile {
private VotingPluginMain plugin;
/**
* Constructs a new ConfigVoteSites.
*
* @param plugin the plugin instance
*/
public ConfigVoteSites(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "VoteSites.yml"));
setIgnoreCase(plugin.getConfigFile().isCaseInsensitiveYMLFiles());
this.plugin = plugin;
}
@@ -41,13 +49,14 @@ public class ConfigVoteSites extends YMLFile {
public void generateVoteSite(String siteName) {
if (plugin.getConfigFile().isAutoCreateVoteSites()) {
String org = siteName;
siteName = siteName.replace(".", "_").replace(" ", "_");
siteName = siteName.replaceAll("[\\.\\s]+", "_");
plugin.getLogger().warning("VoteSite " + siteName + " does not exist with the servicesite '" + org
+ "', creating one, set AutoCreateVoteSites to false to prevent this");
setEnabled(siteName, true);
setServiceSite(siteName, org);
setVoteURL(siteName, "VoteURL");
setVoteDelay(siteName, 24);
setVoteDelay(siteName, "24h");
set(siteName, "DisplayItem.Material", "STONE");
set(siteName, "DisplayItem.Amount", 1);
set(siteName, "Rewards.Messages.Player", "&aThanks for voting on %ServiceSite%!");
@@ -123,14 +132,31 @@ public class ConfigVoteSites extends YMLFile {
return getData().getConfigurationSection("VoteSites." + siteName);
}
/**
* Gets the display name for a site.
*
* @param site the site name
* @return the display name
*/
public String getDisplayName(String site) {
return getData(site).getString("Name");
}
/**
* Gets the path to the every site reward.
*
* @return the every site reward path
*/
public String getEverySiteRewardPath() {
return "EverySiteReward";
}
/**
* Gets the item configuration for a site.
*
* @param site the site name
* @return the item configuration
*/
public ConfigurationSection getItem(String site) {
if (getData(site).isConfigurationSection("DisplayItem")) {
return getData(site).getConfigurationSection("DisplayItem");
@@ -138,6 +164,12 @@ public class ConfigVoteSites extends YMLFile {
return getData(site).getConfigurationSection("Item");
}
/**
* Gets the permission required to view a site.
*
* @param siteName the site name
* @return the permission to view
*/
public String getPermissionToView(String siteName) {
return getData(siteName).getString("PermissionToView", "");
}
@@ -173,23 +205,38 @@ public class ConfigVoteSites extends YMLFile {
}
/**
* Gets the vote delay.
* Gets the vote delay for a site.
*
* @param siteName the site name
* @param site the site name
* @return the vote delay
*/
public double getVoteDelay(String siteName) {
return getData(siteName).getDouble("VoteDelay", 24);
public ParsedDuration getVoteDelay(String site) {
ConfigurationSection sec = getData(site);
// NEW FORMAT (string)
if (sec.isString("VoteDelay")) {
return ParsedDuration.parse(sec.getString("VoteDelay"), TimeUnit.HOURS);
}
// LEGACY FORMAT (numbers)
double hours = sec.getDouble("VoteDelay", 0);
double minutes = sec.getDouble("VoteDelayMin", 0);
long millis = (long) (hours * 60 * 60 * 1000) + (long) (minutes * 60 * 1000);
return ParsedDuration.ofMillis(millis);
}
/**
* Gets the vote delay daily hour for a site.
*
* @param siteName the site name
* @return the vote delay daily hour
*/
public int getVoteDelayDailyHour(String siteName) {
return getData(siteName).getInt("VoteDelayDailyHour", 0);
}
public double getVoteDelayMin(String siteName) {
return getData(siteName).getDouble("VoteDelayMin", 0);
}
/**
* Gets the vote site enabled.
*
@@ -221,18 +268,42 @@ public class ConfigVoteSites extends YMLFile {
}
/**
* Gets whether to give rewards offline for a site.
*
* @param site the site name
* @return true if rewards should be given offline
*/
public boolean getVoteSiteGiveOffline(String site) {
return getData(site).getBoolean("ForceOffline", getData(site).getBoolean("GiveOffline"));
}
/**
* Gets whether a site is hidden.
*
* @param siteName the site name
* @return true if the site is hidden
*/
public boolean getVoteSiteHidden(String siteName) {
return getData(siteName).getBoolean("Hidden");
}
/**
* Gets whether to ignore can vote check for a site.
*
* @param siteName the site name
* @return true if can vote check should be ignored
*/
public boolean getVoteSiteIgnoreCanVote(String siteName) {
return getData(siteName).getBoolean("IgnoreCanVote");
}
/**
* Gets whether vote delay resets daily for a site.
*
* @param siteName the site name
* @return true if vote delay resets daily
*/
public boolean getVoteSiteResetVoteDelayDaily(String siteName) {
return getData(siteName).getBoolean("VoteDelayDaily");
}
@@ -279,24 +350,35 @@ public class ConfigVoteSites extends YMLFile {
return voteSites;
}
/**
* Gets the names of vote sites.
*
* @param checkEnabled whether to check if sites are enabled
* @return the list of vote site names
*/
public ArrayList<String> getVoteSitesNames(boolean checkEnabled) {
ArrayList<String> siteNames = new ArrayList<>();
if (getData().isConfigurationSection("VoteSites")) {
siteNames = ArrayUtils.convert(getData().getConfigurationSection("VoteSites").getKeys(false));
if (!getData().isConfigurationSection("VoteSites")) {
return siteNames;
}
siteNames = ArrayUtils.convert(getData().getConfigurationSection("VoteSites").getKeys(false));
for (int i = siteNames.size() - 1; i >= 0; i--) {
// plugin.getLogger().info(siteNames.get(i));
if (!getData().isConfigurationSection("VoteSites." + siteNames.get(i))) {
plugin.getLogger()
.warning("VoteSites." + siteNames.get(i) + " is not a configuration section, please remove");
siteNames.remove(i);
} else if (siteNames.get(i).equalsIgnoreCase("null")
|| (!getVoteSiteEnabled(siteNames.get(i)) && checkEnabled) || !siteCheck(siteNames.get(i))) {
// plugin.getLogger().info("Removed: " + siteNames.get(i));
String site = siteNames.get(i);
String path = "VoteSites." + site;
if (!getData().isConfigurationSection(path)) {
plugin.getLogger().warning(path + " is not a configuration section, please remove");
siteNames.remove(i);
continue;
}
if (site.equalsIgnoreCase("null") || (!getVoteSiteEnabled(site) && checkEnabled) || !siteCheck(site)) {
siteNames.remove(i);
continue;
}
}
return siteNames;
@@ -312,6 +394,12 @@ public class ConfigVoteSites extends YMLFile {
return getData(siteName).getString("VoteURL", "");
}
/**
* Gets whether to wait until vote delay for a site.
*
* @param siteName the site name
* @return true if should wait until vote delay
*/
public boolean getWaitUntilVoteDelay(String siteName) {
return getData(siteName).getBoolean("WaitUntilVoteDelay", false);
}
@@ -388,10 +476,22 @@ public class ConfigVoteSites extends YMLFile {
set(siteName, "Cumulative.Rewards", value);
}
/**
* Sets the cumulative votes for a site.
*
* @param siteName the site name
* @param value the value
*/
public void setCumulativeVotes(String siteName, int value) {
set(siteName, "Cumulative.Votes", value);
}
/**
* Sets the display name for a site.
*
* @param siteName the site name
* @param value the value
*/
public void setDisplayName(String siteName, String value) {
set(siteName, "Name", value);
}
@@ -406,6 +506,12 @@ public class ConfigVoteSites extends YMLFile {
set(siteName, "Enabled", disabled);
}
/**
* Sets whether to force offline for a site.
*
* @param siteName the site name
* @param value the value
*/
public void setForceOffline(String siteName, boolean value) {
set(siteName, "ForceOffline", value);
@@ -447,14 +553,10 @@ public class ConfigVoteSites extends YMLFile {
* @param siteName the site name
* @param voteDelay the vote delay
*/
public void setVoteDelay(String siteName, double voteDelay) {
public void setVoteDelay(String siteName, String voteDelay) {
set(siteName, "VoteDelay", voteDelay);
}
public void setVoteDelayDaily(String siteName, boolean value) {
set(siteName, "VoteDelayDaily", value);
}
/**
* Sets the vote URL.
*
@@ -483,4 +585,24 @@ public class ConfigVoteSites extends YMLFile {
return pass;
}
/**
* Sets the vote delay daily hour for a site.
*
* @param siteName the site name
* @param intValue the value
*/
public void setVoteDelayDailyHour(String siteName, int intValue) {
set(siteName, "VoteDelayDailyHour", intValue);
}
/**
* Sets whether vote delay is daily for a site.
*
* @param siteName the site name
* @param value the value
*/
public void setVoteDelayDaily(String siteName, boolean value) {
set(siteName, "VoteDelayDaily", value);
}
}
@@ -21,6 +21,9 @@ import com.bencodez.votingplugin.topvoter.TopVoter;
import lombok.Getter;
/**
* GUI configuration.
*/
public class GUI extends YMLFile {
@ConfigDataString(path = "BOOK.VoteURLBookGUI.AlreadyVotedColor")
@@ -88,42 +91,42 @@ public class GUI extends YMLFile {
@Getter
private boolean chestVoteURLAllUrlsButtonrequireAllSitesVoted = true;
@ConfigDataString(path = "GUIMethod.Best")
@Getter
private String guiMethodBest = "CHEST";
@ConfigDataString(path = "GUIMethod.GUI")
@Getter
private String guiMethodGUI = "CHEST";
@ConfigDataString(path = "GUIMethod.Last")
@Getter
private String guiMethodLast = "CHEST";
@ConfigDataString(path = "GUIMethod.Next")
@Getter
private String guiMethodNext = "CHEST";
@ConfigDataString(path = "GUIMethod.Streak")
@Getter
private String guiMethodStreak = "CHEST";
@ConfigDataString(path = "GUIMethod.Today")
@ConfigDataString(path = "GUIMethod.Today", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodToday = "CHEST";
@ConfigDataString(path = "GUIMethod.TopVoter")
@ConfigDataString(path = "GUIMethod.TopVoter", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodTopVoter = "CHEST";
@ConfigDataString(path = "GUIMethod.Total")
@ConfigDataString(path = "GUIMethod.Last", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodLast = "CHEST";
@ConfigDataString(path = "GUIMethod.Next", options = { "CHEST", "CHAT", "BOOK", "DIALOG" })
@Getter
private String guiMethodNext = "CHEST";
@ConfigDataString(path = "GUIMethod.Total", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodTotal = "CHEST";
@ConfigDataString(path = "GUIMethod.URL")
@ConfigDataString(path = "GUIMethod.URL", options = { "CHEST", "CHAT", "BOOK", "DIALOG" })
@Getter
private String guiMethodURL = "CHEST";
@ConfigDataString(path = "GUIMethod.Best", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodBest = "CHEST";
@ConfigDataString(path = "GUIMethod.Streak", options = { "CHEST", "CHAT", "DIALOG" })
@Getter
private String guiMethodStreak = "CHEST";
@ConfigDataString(path = "GUIMethod.GUI", options = { "CHEST", "DIALOG" })
@Getter
private String guiMethodGUI = "CHEST";
@ConfigDataBoolean(path = "LastMonthGUI")
@Getter
private boolean lastMonthGUI = false;
@@ -358,11 +361,23 @@ public class GUI extends YMLFile {
@Getter
private boolean chestVoteURLViewAllUrlsButtonEnabled = false;
/**
* Constructs a new GUI configuration.
*
* @param plugin the plugin instance
*/
public GUI(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "GUI.yml"));
setIgnoreCase(plugin.getConfigFile().isCaseInsensitiveYMLFiles());
this.plugin = plugin;
}
/**
* Gets the extra items for a chest GUI.
*
* @param gui the GUI name
* @return the extra items
*/
public Set<String> getChestGUIExtraItems(String gui) {
if (getData().isConfigurationSection("CHEST." + gui + ".ExtraItems")) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems").getKeys(false);
@@ -370,6 +385,13 @@ public class GUI extends YMLFile {
return new HashSet<>();
}
/**
* Gets an extra item configuration for a chest GUI.
*
* @param gui the GUI name
* @param item the item name
* @return the item configuration
*/
public ConfigurationSection getChestGUIExtraItemsItem(String gui, String item) {
return getData().getConfigurationSection("CHEST." + gui + ".ExtraItems." + item);
}
@@ -396,10 +418,23 @@ public class GUI extends YMLFile {
return (ArrayList<String>) getData().getList("CHEST.VoteGUI." + slot + ".Item.Lore", new ArrayList<>());
}
/**
* Gets the rewards path for a chest vote GUI slot.
*
* @param slot the slot
* @param lastPath the last path segment
* @return the rewards path
*/
public String getChestVoteGUISlotRewardsPath(String slot, String lastPath) {
return "CHEST.VoteGUI." + slot + "." + lastPath;
}
/**
* Gets the configuration section for a chest vote GUI slot.
*
* @param slot the slot
* @return the configuration section
*/
public ConfigurationSection getChestVoteGUISlotSection(String slot) {
return getData().getConfigurationSection("CHEST.VoteGUI." + slot + ".Item");
}
@@ -414,10 +449,22 @@ public class GUI extends YMLFile {
return getData().getInt("CHEST.VoteGUI." + slot + ".Slot", -1);
}
/**
* Gets the custom site name display for a vote next GUI.
*
* @param site the site name
* @return the custom display name
*/
public String getChestVoteNextCustomSiteNamesDisplays(String site) {
return getData().getString("CHEST.VoteNext.CustomSiteNamesDisplays." + site, "");
}
/**
* Gets the total item configuration for a top voter.
*
* @param top the top voter
* @return the item configuration
*/
public ConfigurationSection getChestVoteTotalItem(TopVoter top) {
switch (top) {
case AllTime:
@@ -434,6 +481,12 @@ public class GUI extends YMLFile {
}
}
/**
* Gets an extra item configuration for a vote URL GUI.
*
* @param item the item name
* @return the item configuration
*/
public ConfigurationSection getChestVoteURLExtraItemsItem(String item) {
return getData().getConfigurationSection("CHEST.VoteURL.ExtraItems." + item);
}
@@ -15,66 +15,71 @@ import com.bencodez.simpleapi.file.annotation.ConfigDataString;
import com.bencodez.votingplugin.VotingPluginMain;
import lombok.Getter;
import lombok.Setter;
/**
* The ShopFile class manages the vote shop configuration.
*/
@Getter
@Setter
public class ShopFile extends YMLFile {
@Getter
@ConfigDataConfigurationSection(path = "ShopConfirmPurchase.NoItem")
private ConfigurationSection shopConfirmPurchaseNoItem;
@Getter
@ConfigDataBoolean(path = "ShopConfirmPurchase.UseDialog")
private boolean shopConfirmPurchaseUseDialog = false;
@ConfigDataString(path = "ShopConfirmPurchase.Title")
private String shopConfirmPurchaseTitle = "Confirm Purchase?";
@Getter
@ConfigDataConfigurationSection(path = "ShopConfirmPurchase.YesItem")
private ConfigurationSection shopConfirmPurchaseYesItem;
@Getter
@ConfigDataString(path = "VoteShop.Disabled")
private String voteShopDisabled = "&cVote shop disabled";
@ConfigDataBoolean(path = "VoteShop.HideLimitedReached")
@Getter
private boolean voteShopHideLimitedReached = true;
@ConfigDataString(path = "VoteShop.LimitReached")
@Getter
private String voteShopLimitReached = "&aYou reached your limit";
@ConfigDataBoolean(path = "VoteShop.RequireConfirmation")
@Getter
private boolean voteShopRequireConfirmation = false;
private VotingPluginMain plugin;
@ConfigDataBoolean(path = "VoteShop.BackButton")
@Getter
private boolean voteShopBackButton = true;
@ConfigDataBoolean(path = "VoteShop.ReopenGUIOnPurchase")
@Getter
private boolean voteShopReopenGUIOnPurchase = true;
private boolean voteShopReopenGuiOnPurchase = true;
@ConfigDataBoolean(path = "VoteShop.Enabled")
@Getter
private boolean voteShopEnabled = true;
@ConfigDataString(path = "VoteShop.Name")
@Getter
private String voteShopName = "VoteShop";
@ConfigDataKeys(path = "ExtraItems")
@Getter
private Set<String> voteShopExtraItems = new HashSet<>();
private Set<String> voteShopExtraItems = new HashSet<String>();
/**
* Constructs a new ShopFile.
*
* @param plugin the main plugin instance
*/
public ShopFile(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "Shop.yml"));
setIgnoreCase(plugin.getConfigFile().isCaseInsensitiveYMLFiles());
this.plugin = plugin;
}
/**
* Converts vote shop data from the GUI file to this shop file.
*/
public void convertFromGUIFile() {
// booleans
setValue("VoteShop.Enabled", plugin.getGui().getData().getBoolean("CHEST.VoteShopEnabled"));
setValue("VoteShop.BackButton", plugin.getGui().getData().getBoolean("CHEST.VoteShopBackButton"));
setValue("VoteShop.HideLimitReached", plugin.getGui().getData().getBoolean("CHEST.VoteShopHideLimitedReached"));
@@ -82,20 +87,20 @@ public class ShopFile extends YMLFile {
plugin.getGui().getData().getBoolean("CHEST.VoteShopRequireConfirmation"));
setValue("VoteShop.ReopenGUIOnPurchase",
plugin.getGui().getData().getBoolean("CHEST.VoteShopReopenGUIOnPurchase"));
// strings
setValue("VoteShop.Name", plugin.getGui().getData().getString("CHEST.VoteShopName"));
setValue("VoteShop.LimitReached", plugin.getGui().getData().getString("CHEST.VoteShopLimitReached"));
setValue("VoteShop.Disabled", plugin.getGui().getData().getString("CHEST.VoteShopDisabled"));
// sections
setValue("Shop", plugin.getGui().getData().getConfigurationSection("CHEST.Shop"));
setValue("ExtraItems", plugin.getGui().getData().getConfigurationSection("CHEST.VoteShopExtraItems"));
setValue("ShopConfirmPurchase", plugin.getGui().getData().getConfigurationSection("CHEST.ShopConfirmPurchase"));
saveData();
}
/**
* Creates a new legacy shop item.
*
* @param value the identifier
*/
public void createShop(String value) {
ConfigurationSection shopData = getData().createSection("Shop." + value);
shopData.set("Identifier_Name", value);
@@ -106,77 +111,264 @@ public class ShopFile extends YMLFile {
shopData.set("Permission", "");
shopData.set("CloseGUI", true);
shopData.set("RequireConfirmation", false);
shopData.set("Rewards.Items.Item1.Material", "STONE");
shopData.set("Rewards.Items.Item1.Amount", 1);
saveData();
}
/**
* Gets the categories section.
*
* @return the categories section
*/
public ConfigurationSection getCategoriesSection() {
return getData().getConfigurationSection("Categories");
}
/**
* Gets a category section.
*
* @param categoryId the category id
* @return the category section
*/
public ConfigurationSection getCategorySection(String categoryId) {
return getData().getConfigurationSection("Categories." + categoryId);
}
/**
* Gets a category shop section.
*
* @param categoryId the category id
* @return the category shop section
*/
public ConfigurationSection getCategoryShopSection(String categoryId) {
return getData().getConfigurationSection("Categories." + categoryId + ".Shop");
}
/**
* Checks if a category back button is enabled.
*
* @param category the category id
* @return true if enabled
*/
public boolean isCategoryBackButtonEnabled(String category) {
return getData().getBoolean("Categories." + category + ".BackButton", false);
}
/**
* Gets the category back button item section.
*
* @param category the category id
* @return configuration section or null
*/
public ConfigurationSection getCategoryBackButtonItem(String category) {
String path = "Categories." + category + ".BackButtonItem";
if (getData().isConfigurationSection(path)) {
return getData().getConfigurationSection(path);
}
return null;
}
/**
* Gets the default VoteShop back button item.
*
* @return configuration section or null
*/
public ConfigurationSection getDefaultBackButtonItem() {
if (getData().isConfigurationSection("VoteShop.BackButtonItem")) {
return getData().getConfigurationSection("VoteShop.BackButtonItem");
}
return null;
}
/**
* Gets the display section for an entry, preferring DisplayItem when present.
*
* @param section the entry section
* @return the display section
*/
public ConfigurationSection getDisplaySection(ConfigurationSection section) {
if (section == null) {
return null;
}
ConfigurationSection displaySection = section.getConfigurationSection("DisplayItem");
if (displaySection != null) {
return displaySection;
}
return section;
}
/**
* Gets the configuration for a vote shop extra item.
*
* @param item the item identifier
* @return the configuration section
*/
public ConfigurationSection getGUIVoteShopExtraItems(String item) {
return getData().getConfigurationSection("ExtraItems." + item);
}
/**
* Gets the cost of a shop item.
*
* @param identifier the shop identifier
* @return the cost
*/
public int getShopIdentifierCost(String identifier) {
return getData().getInt("Shop." + identifier + ".Cost");
}
/**
* Gets the identifier name for a shop item.
*
* @param identifier the shop identifier
* @return the identifier name
*/
public String getShopIdentifierIdentifierName(String identifier) {
return getData().getString("Shop." + identifier + ".Identifier_Name", identifier);
}
/**
* Gets the purchase limit for a shop item.
*
* @param identifier the shop identifier
* @return the purchase limit
*/
public int getShopIdentifierLimit(String identifier) {
return getData().getInt("Shop." + identifier + ".Limit", -1);
}
/**
* Gets the rewards path for a shop item.
*
* @param identifier the shop identifier
* @return the rewards path
*/
public String getShopIdentifierRewardsPath(String identifier) {
return "Shop." + identifier + ".Rewards";
}
/**
* Gets all shop identifiers.
*
* @return the set of shop identifiers
*/
public Set<String> getShopIdentifiers() {
ConfigurationSection shop = getData().getConfigurationSection("Shop");
if (shop != null) {
return shop.getKeys(false);
}
return new HashSet<>();
return new HashSet<String>();
}
/**
* Gets the shop root section.
*
* @return the shop section
*/
public ConfigurationSection getShopSection() {
return getData().getConfigurationSection("Shop");
}
/**
* Gets the configuration section for a shop item.
*
* @param identifier the shop identifier
* @return the configuration section
*/
public ConfigurationSection getShopIdentifierSection(String identifier) {
return getData().getConfigurationSection("Shop." + identifier);
}
/**
* Checks if the GUI should close on purchase.
*
* @param shop the shop identifier
* @return true if GUI should close
*/
public boolean getVoteShopCloseGUI(String shop) {
return getData().getBoolean("Shop." + shop + ".CloseGUI", true);
}
/**
* Checks if the shop item should be hidden when player has no permission.
*
* @param shop the shop identifier
* @return true if should hide
*/
public boolean getVoteShopHideOnNoPermission(String shop) {
return getData().getBoolean("Shop." + shop + ".HideOnNoPermission", true);
}
/**
* Checks if the shop item is not buyable.
*
* @param shop the shop identifier
* @return true if not buyable
*/
public boolean getVoteShopNotBuyable(String shop) {
return getData().getBoolean("Shop." + shop + ".NotBuyable", false);
}
/**
* Gets the permission required for a shop item.
*
* @param ident the shop identifier
* @return the permission
*/
public String getVoteShopPermission(String ident) {
return getData().getString("Shop." + ident + ".Permission", "");
}
/**
* Gets the purchase message for a shop item.
*
* @param identifier the shop identifier
* @return the purchase message
*/
public String getVoteShopPurchase(String identifier) {
return getData().getString("Shop." + identifier + ".PurchaseMessage",
plugin.getConfigFile().getFormatShopPurchaseMsg());
}
/**
* Checks if the shop item resets daily.
*
* @param shop the shop identifier
* @return true if resets daily
*/
public boolean getVoteShopResetDaily(String shop) {
return getData().getBoolean("Shop." + shop + ".Reset.Daily", false);
}
/**
* Checks if the shop item resets monthly.
*
* @param shop the shop identifier
* @return true if resets monthly
*/
public boolean getVoteShopResetMonthly(String shop) {
return getData().getBoolean("Shop." + shop + ".Reset.Monthly", false);
}
/**
* Checks if the shop item resets weekly.
*
* @param shop the shop identifier
* @return true if resets weekly
*/
public boolean getVoteShopResetWeekly(String shop) {
return getData().getBoolean("Shop." + shop + ".Reset.Weekly", false);
}
/**
* Checks if the shop item requires purchase confirmation.
*
* @param identifier the shop identifier
* @return true if requires confirmation
*/
public boolean isVoteShopRequireConfirmation(String identifier) {
return getData().getBoolean("Shop." + identifier + ".RequireConfirmation", isVoteShopRequireConfirmation());
}
@@ -191,8 +383,13 @@ public class ShopFile extends YMLFile {
plugin.saveResource("Shop.yml", true);
}
/**
* Removes a shop item.
*
* @param value the shop identifier
*/
public void removeShop(String value) {
getData().set("Shop." + value, null);
saveData();
}
}
}
@@ -3,7 +3,6 @@ package com.bencodez.votingplugin.config;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.bencodez.simpleapi.file.YMLFile;
@@ -16,18 +15,14 @@ import com.bencodez.simpleapi.file.annotation.ConfigDataListInt;
import com.bencodez.simpleapi.file.annotation.ConfigDataListString;
import com.bencodez.simpleapi.file.annotation.ConfigDataString;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.topvoter.TopVoter;
import lombok.Getter;
/**
* The SpecialRewardsConfig class manages special rewards configuration.
*/
public class SpecialRewardsConfig extends YMLFile {
@Getter
private String allSitesRewardPath = "AllSites";
@Getter
private String almostAllSitesRewardPath = "AlmostAllSites";
@Getter
private String anySiteRewardsPath = "AnySiteRewards";
@@ -43,16 +38,6 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private boolean enableWeeklyAwards = false;
@ConfigDataBoolean(path = "OnlyOneCumulative")
@Getter
private boolean onlyOneCumulative = false;
@Getter
private String firstVoteRewardsPath = "FirstVote";
@Getter
private String firstVoteTodayRewardsPath = "FirstVoteToday";
/** The plugin. */
private VotingPluginMain plugin;
@@ -72,14 +57,18 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private boolean votePartyResetExtraVotesWeekly = false;
@ConfigDataString(path = "VoteParty.VoteReminderBroadcast")
@ConfigDataString(path = "VoteParty.VoteReminder.Broadcast", secondPath = "VoteParty.VoteReminderBroadcast")
@Getter
private String votePartyVoteReminderBroadcast = "%votesrequired% left to go, go vote!";
@ConfigDataListInt(path = "VoteParty.VoteReminderAtVotes")
@ConfigDataListInt(path = "VoteParty.VoteReminder.AtVotes", secondPath = "VoteParty.VoteReminderAtVotes")
@Getter
private ArrayList<Integer> votePartyVoteReminderAtVotes = new ArrayList<>();
@ConfigDataListString(path = "VoteParty.VoteReminder.Commands", secondPath = "VoteParty.VoteReminderCommands")
@Getter
private ArrayList<String> votePartyVoteReminderCommands = new ArrayList<>();
@ConfigDataListString(path = "VoteParty.GlobalRandomCommand")
@Getter
private ArrayList<String> votePartyGlobalRandomCommand = new ArrayList<>();
@@ -103,22 +92,10 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private double voteStreakRequirementWeek = 50;
@ConfigDataKeys(path = "Cumulative")
@Getter
private Set<String> cumulativeVotes = new HashSet<>();
@ConfigDataKeys(path = "DailyAwards")
@Getter
private Set<String> dailyPossibleRewardPlaces = new HashSet<>();
@ConfigDataKeys(path = "MileStones")
@Getter
private Set<String> milestoneVotes = new HashSet<>();
@ConfigDataBoolean(path = "ResetMilestonesMonthly")
@Getter
private boolean resetMilestonesMonthly = false;
@ConfigDataString(path = "VoteParty.Broadcast")
@Getter
private String votePartyBroadcast = "";
@@ -183,82 +160,48 @@ public class SpecialRewardsConfig extends YMLFile {
@Getter
private Set<String> weeklyPossibleRewardPlaces = new HashSet<>();
@ConfigDataBoolean(path = "NameMCLikeReward.Enabled")
@Getter
private boolean nameMCLikeRewardEnabled = false;
@ConfigDataString(path = "NameMCLikeReward.Url")
@Getter
private String nameMCLikeRewardUrl = "";
@ConfigDataInt(path = "NameMCLikeReward.CheckIntervalMinutes")
@Getter
private int nameMCLikeRewardCheckIntervalMinutes = 10;
@Getter
private final String nameMCLikeRewardPath = "NameMCLikeReward.Rewards";
/**
* Constructs a new SpecialRewardsConfig.
*
* @param plugin the main plugin instance
*/
public SpecialRewardsConfig(VotingPluginMain plugin) {
super(plugin, new File(plugin.getDataFolder(), "SpecialRewards.yml"));
setIgnoreCase(plugin.getConfigFile().isCaseInsensitiveYMLFiles());
this.plugin = plugin;
}
public List<Integer> getCumulativeBlackList(int cumulative) {
return getData().getIntegerList("Cumulative." + cumulative + ".BlackList");
}
public boolean getCumulativeRecurring(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Recurring", true);
}
public boolean getCumulativeRewardEnabled(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".Enabled");
}
public String getCumulativeRewardsPath(int cumulative) {
return "Cumulative." + cumulative + ".Rewards";
}
@Deprecated
public boolean getCumulativeVotesInSameDay(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameDay");
}
@Deprecated
public boolean getCumulativeVotesInSameMonth(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameMonth");
}
@Deprecated
public boolean getCumulativeVotesInSameWeek(int cumulative) {
return getData().getBoolean("Cumulative." + cumulative + ".VotesInSameWeek");
}
public String getCumulativeVotesTotal(int cumulative) {
String str = getData().getString("Cumulative." + cumulative + ".TotalToUse", "");
if (str.isEmpty()) {
if (getCumulativeVotesInSameMonth(cumulative)) {
return TopVoter.Monthly.toString();
}
if (getCumulativeVotesInSameWeek(cumulative)) {
return TopVoter.Weekly.toString();
}
if (getCumulativeVotesInSameDay(cumulative)) {
return TopVoter.Daily.toString();
}
}
return str;
}
/**
* Gets the rewards path for a daily award.
*
* @param path the award path
* @return the daily award rewards path
*/
public String getDailyAwardRewardsPath(String path) {
return "DailyAwards." + path + ".Rewards";
}
/**
* Gets the milestone reward enabled.
* Gets the rewards path for a monthly award.
*
* @param milestones the milestones
* @return the milestone reward enabled
* @param path the award path
* @return the monthly award rewards path
*/
public boolean getMilestoneRewardEnabled(int milestones) {
return getData().getBoolean("MileStones." + milestones + ".Enabled");
}
/**
* Gets the milestone rewards.
*
* @param milestones the milestones
* @return the milestone rewards
*/
public String getMilestoneRewardsPath(int milestones) {
return "MileStones." + milestones + ".Rewards";
}
public String getMonthlyAwardRewardsPath(String path) {
return "MonthlyAwards." + path + ".Rewards";
}
@@ -276,6 +219,12 @@ public class SpecialRewardsConfig extends YMLFile {
}
}
/**
* Gets the increase votes required with the old typo field.
*
* @return the increase votes required
* @deprecated Use getVotePartyIncreaseVotesRequired instead
*/
public int getVotePartyIncreaseVotesRequiredWithTypo() {
int increase = getVotePartyIncreaseVotesRequired();
if (increase > 0) {
@@ -284,14 +233,34 @@ public class SpecialRewardsConfig extends YMLFile {
return getVotePartyIncreaseVotesRquired();
}
/**
* Checks if a vote streak reward is enabled.
*
* @param type the streak type
* @param s the streak value
* @return true if enabled
*/
public boolean getVoteStreakRewardEnabled(String type, String s) {
return getData().getBoolean("VoteStreak." + type + "." + s + ".Enabled");
}
/**
* Gets the rewards path for a vote streak.
*
* @param type the streak type
* @param string the streak value
* @return the vote streak rewards path
*/
public String getVoteStreakRewardsPath(String type, String string) {
return "VoteStreak." + type + "." + string + ".Rewards";
}
/**
* Gets all vote streak values for a type.
*
* @param type the streak type
* @return the set of vote streak values
*/
public Set<String> getVoteStreakVotes(String type) {
try {
Set<String> set = getData().getConfigurationSection("VoteStreak." + type).getKeys(false);
@@ -304,6 +273,12 @@ public class SpecialRewardsConfig extends YMLFile {
}
}
/**
* Gets the rewards path for a weekly award.
*
* @param path the award path
* @return the weekly award rewards path
*/
public String getWeeklyAwardRewardsPath(String path) {
return "WeeklyAwards." + path + ".Rewards";
}
@@ -318,27 +293,25 @@ public class SpecialRewardsConfig extends YMLFile {
plugin.saveResource("SpecialRewards.yml", true);
}
public void removeCumulative(String votes) {
getData().set("Cumulative." + votes, null);
/**
* Removes a vote milestone.
*
* @param votes the milestone votes value
*/
public void removeVoteMilestone(String votes) {
getData().set("VoteMilestones." + votes, null);
saveData();
}
public void removeMilestone(String votes) {
getData().set("MileStones." + votes, null);
saveData();
}
public void setCumulative(int intValue) {
getData().set("Cumulative." + intValue + ".Enabled", true);
getData().set("Cumulative." + intValue + ".TotalToUse", "AllTime");
getData().set("Cumulative." + intValue + ".Rewards.Messages.Player",
"&aYou got %cumulative% cumulative votes!");
saveData();
}
public void setMilestone(int intValue) {
getData().set("MileStones." + intValue + ".Enabled", true);
getData().set("MileStones." + intValue + ".Rewards.Messages.Player", "&aYou got %milestone% milestone votes!");
/**
* Sets a vote milestone with default values.
*
* @param intValue the milestone votes value
*/
public void setVoteMilestone(int intValue) {
getData().set("VoteMilestones." + intValue + ".Enabled", true);
getData().set("VoteMilestones." + intValue + ".Rewards.Messages.Player",
"&aYou got %milestone% milestone votes!");
saveData();
}
}
@@ -2,11 +2,13 @@ package com.bencodez.votingplugin.cooldown;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.bukkit.event.EventHandler;
@@ -15,216 +17,359 @@ import org.bukkit.event.Listener;
import com.bencodez.advancedcore.api.rewards.RewardOptions;
import com.bencodez.advancedcore.api.user.AdvancedCoreUser;
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
import com.bencodez.advancedcore.api.user.UserStartup;
import com.bencodez.simpleapi.sql.Column;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.events.PlayerVoteCoolDownEndEvent;
import com.bencodez.votingplugin.events.PlayerVoteSiteCoolDownEndEvent;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.NextSite;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
/**
* Manages cooldown checks for vote rewards.
*/
public class CoolDownCheck implements Listener {
private VotingPluginMain plugin;
private final VotingPluginMain plugin;
private HashMap<UUID, ScheduledFuture<?>> perSiteTasks = new HashMap<>();
private HashMap<UUID, ScheduledFuture<?>> allSiteTasks = new HashMap<>();
private final Map<UUID, ScheduledFuture<?>> perSiteTasks = new ConcurrentHashMap<>();
private final Map<UUID, ScheduledFuture<?>> allSiteTasks = new ConcurrentHashMap<>();
@Getter
private ScheduledExecutorService timer;
private final ScheduledExecutorService timer;
private boolean cooldownCheckEnabled = false;
private volatile boolean cooldownCheckEnabled = false;
/**
* Constructs a new cooldown check manager.
*
* @param plugin the plugin instance
*/
public CoolDownCheck(VotingPluginMain plugin) {
this.plugin = plugin;
this.timer = Executors.newScheduledThreadPool(1);
// Better behavior when you cancel+reschedule a lot (removes cancelled tasks from queue)
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.setRemoveOnCancelPolicy(true);
this.timer = exec;
}
/**
* Checks the cooldown for a player by UUID.
*
* @param uuid the player UUID
*/
public void check(UUID uuid) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (!user.isOnline()) {
user.dontCache();
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
}
check(user);
}
/**
* Shuts down the cooldown check timer.
*/
public void shutdown() {
timer.shutdownNow();
for (ScheduledFuture<?> f : perSiteTasks.values()) {
if (f != null) {
f.cancel(false);
}
}
for (ScheduledFuture<?> f : allSiteTasks.values()) {
if (f != null) {
f.cancel(false);
}
}
perSiteTasks.clear();
allSiteTasks.clear();
}
/**
* Checks the cooldown for a user.
*
* @param user the voting plugin user
*/
public synchronized void check(VotingPluginUser user) {
boolean coolDownCheck = user.getCoolDownCheck();
if (coolDownCheck) {
if (user.canVoteAll()) {
user.setCoolDownCheck(false);
PlayerVoteCoolDownEndEvent event = new PlayerVoteCoolDownEndEvent(user);
plugin.getServer().getPluginManager().callEvent(event);
allSiteTasks.remove(user.getJavaUUID());
} else {
schedulePerSite(user, false);
}
if (!user.getCoolDownCheck()) {
return;
}
if (user.canVoteAll()) {
user.setCoolDownCheck(false);
PlayerVoteCoolDownEndEvent event = new PlayerVoteCoolDownEndEvent(user);
plugin.getServer().getPluginManager().callEvent(event);
ScheduledFuture<?> f = allSiteTasks.remove(user.getJavaUUID());
if (f != null) {
f.cancel(false);
}
return;
}
// Keep per-site scheduling going while waiting for "all sites available"
schedulePerSite(user, false);
}
/**
* Check ONLY a specific votesite for all users (uses streaming keys/cols).
*
* @param site the vote site to check
*/
public void checkAllVoteSite(VoteSite site) {
if (site == null) {
return;
}
plugin.getLogger().info("Checking vote cooldown rewards for all players: " + site.getKey());
HashMap<UUID, ArrayList<Column>> cols = plugin.getUserManager().getAllKeys();
for (Entry<UUID, ArrayList<Column>> playerData : cols.entrySet()) {
String uuid = playerData.getKey().toString();
if (plugin != null && plugin.isEnabled()) {
if (uuid != null && !uuid.isEmpty()) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(UUID.fromString(uuid), false);
user.dontCache();
user.updateTempCacheWithColumns(playerData.getValue());
cols.put(playerData.getKey(), null);
checkPerSite(user);
user.clearTempCache();
user = null;
}
plugin.getUserManager().forEachUserKeys((uuid, cols) -> {
if (!plugin.isEnabled() || uuid == null) {
return;
}
}
cols.clear();
cols = null;
plugin.getLogger().info("Finished checking vote cooldown rewards for all players: " + site.getKey());
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, false);
if (user == null) {
return;
}
user.userDataFetechMode(UserDataFetchMode.TEMP_ONLY);
try {
if (cols != null) {
user.updateTempCacheWithColumns(cols);
cols.clear(); // help GC (only useful if reused)
}
checkPerSite(site, user);
} finally {
user.clearTempCache();
}
}, (count) -> plugin.getLogger().info("Finished checking vote cooldown rewards for all players: " + site.getKey()
+ " (processed: " + count + ")"));
}
/**
* Checks if cooldown check is enabled.
*/
public void checkEnabled() {
if (!plugin.getConfigFile().isDisableCoolDownCheck() && plugin.getRewardHandler()
.hasRewards(plugin.getSpecialRewardsConfig().getData(), "VoteCoolDownEndedReward")) {
cooldownCheckEnabled = true;
} else {
cooldownCheckEnabled = false;
}
cooldownCheckEnabled = !plugin.getConfigFile().isDisableCoolDownCheck()
&& plugin.getRewardHandler().hasRewards(plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward");
}
/**
* Checks per-site cooldown for a player by UUID.
*
* @param uuid the player UUID
*/
public void checkPerSite(UUID uuid) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (!user.isOnline()) {
user.dontCache();
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
}
checkPerSite(user);
}
/**
* Checks per-site cooldown for a user.
*
* @param user the voting plugin user
*/
public synchronized void checkPerSite(VotingPluginUser user) {
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
boolean changed = false;
for (VoteSite site : plugin.getVoteSitesEnabled()) {
if (!coolDownChecks.containsKey(site.getKey()) || !coolDownChecks.get(site.getKey()).booleanValue()) {
if (user.canVoteSite(site)) {
coolDownChecks.put(site.getKey(), Boolean.TRUE);
changed = true;
plugin.extraDebug("Triggering votesitecooldownend event for " + user.getUUID());
PlayerVoteSiteCoolDownEndEvent event = new PlayerVoteSiteCoolDownEndEvent(user, site);
plugin.getServer().getPluginManager().callEvent(event);
}
}
}
if (changed) {
user.setCoolDownCheckSite(coolDownChecks);
}
schedulePerSite(user, false);
if (!plugin.getConfigFile().isPerSiteCoolDownEvents()) {
return;
}
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
boolean changed = false;
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
if (site == null) {
continue;
}
if (!Boolean.TRUE.equals(coolDownChecks.get(site.getKey()))) {
if (user.canVoteSite(site)) {
coolDownChecks.put(site.getKey(), Boolean.TRUE);
changed = true;
plugin.extraDebug("Triggering votesitecooldownend event for " + user.getUUID());
PlayerVoteSiteCoolDownEndEvent event = new PlayerVoteSiteCoolDownEndEvent(user, site);
plugin.getServer().getPluginManager().callEvent(event);
}
}
}
if (changed) {
user.setCoolDownCheckSite(coolDownChecks);
}
schedulePerSite(user, false);
}
/**
* Site-specific version used by batch checks / checkAllVoteSite.
*/
private void checkPerSite(VoteSite site, VotingPluginUser user) {
if (!plugin.getConfigFile().isPerSiteCoolDownEvents() || site == null) {
return;
}
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
if (Boolean.TRUE.equals(coolDownChecks.get(site.getKey()))) {
return;
}
if (user.canVoteSite(site)) {
coolDownChecks.put(site.getKey(), Boolean.TRUE);
user.setCoolDownCheckSite(coolDownChecks);
plugin.extraDebug(
"Triggering votesitecooldownend event on site " + site.getKey() + " for " + user.getUUID());
PlayerVoteSiteCoolDownEndEvent event = new PlayerVoteSiteCoolDownEndEvent(user, site);
plugin.getServer().getPluginManager().callEvent(event);
}
}
/**
* Loads the cooldown check system.
*/
public void load() {
plugin.addUserStartup(new UserStartup() {
@Override
public void onFinish() {
checkAllVoteSites();
}
@Override
public void onStart() {
}
@Override
public void onStartUp(AdvancedCoreUser advancedcoreUser) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(advancedcoreUser);
user.dontCache();
if (cooldownCheckEnabled) {
check(user);
}
if (plugin.getConfigFile().isPerSiteCoolDownEvents()) {
checkPerSite(user);
}
}
});
}
/**
* Handles the cooldown end event.
*
* @param event the cooldown end event
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward", new RewardOptions());
}
/**
* Handles the per-site cooldown end event.
*
* @param event the per-site cooldown end event
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
plugin.getRewardHandler().giveReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName()).addPlaceholder("url",
event.getSite().getVoteURL(false)));
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName())
.addPlaceholder("url", event.getSite().getVoteURL(false)));
}
/**
* Schedules a cooldown check for a user.
*
* @param user the voting plugin user
* @param force whether to force the schedule
*/
public void schedule(VotingPluginUser user, boolean force) {
if (user.getSitesVotedOn() > 0 || force) {
final UUID uuid = UUID.fromString(user.getUUID());
long time = user.getNextTimeAllSitesAvailable();
if (allSiteTasks.containsKey(uuid)) {
allSiteTasks.get(uuid).cancel(false);
allSiteTasks.remove(uuid);
}
if (time > 0) {
user.setCoolDownCheck(true);
ScheduledFuture<?> scheduledFuture = timer.schedule(new Runnable() {
@Override
public void run() {
if (plugin != null && plugin.isEnabled()) {
check(uuid);
}
}
}, time + 2, TimeUnit.SECONDS);
allSiteTasks.put(uuid, scheduledFuture);
} else {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling cooldown check");
}
if (user.getSitesVotedOn() <= 0 && !force) {
return;
}
final UUID uuid = user.getJavaUUID();
final long time = user.getNextTimeAllSitesAvailable();
allSiteTasks.compute(uuid, (k, existing) -> {
if (existing != null) {
existing.cancel(false);
}
if (time <= 0) {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling cooldown check");
return null; // remove entry
}
user.setCoolDownCheck(true);
return timer.schedule(() -> {
if (plugin.isEnabled()) {
check(uuid);
}
}, time + 2, TimeUnit.SECONDS);
});
}
/**
* Schedules per-site cooldown checks for a user.
*
* @param user the voting plugin user
* @param force whether to force the schedule
*/
public void schedulePerSite(VotingPluginUser user, boolean force) {
if (user.getSitesVotedOn() > 0 || force) {
final UUID uuid = UUID.fromString(user.getUUID());
long time = user.getNextTimeFirstSiteAvailable();
if (perSiteTasks.containsKey(uuid)) {
perSiteTasks.get(uuid).cancel(false);
perSiteTasks.remove(uuid);
}
if (time > 0) {
plugin.devDebug("PerSiteCoolDownEvent schedule time: " + time + " seconds");
ScheduledFuture<?> scheduledFuture = timer.schedule(new Runnable() {
@Override
public void run() {
if (plugin != null && plugin.isEnabled()) {
checkPerSite(uuid);
}
}
}, time + 2, TimeUnit.SECONDS);
perSiteTasks.put(uuid, scheduledFuture);
} else {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling cooldown check");
}
if (!plugin.getConfigFile().isPerSiteCoolDownEvents()) {
return;
}
if (user.getSitesVotedOn() <= 0 && !force) {
return;
}
final UUID uuid = user.getJavaUUID();
final NextSite next = user.getNextSiteAvailable();
perSiteTasks.compute(uuid, (k, existing) -> {
if (existing != null) {
existing.cancel(false);
}
if (next == null || next.getSite() == null || next.getSecondsUntilAvailable() <= 0) {
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling per-site cooldown check");
return null; // remove entry
}
plugin.devDebug("PerSiteCoolDownEvent schedule: site=" + next.getSite().getKey() + " time="
+ next.getSecondsUntilAvailable() + " seconds");
return timer.schedule(() -> {
if (!plugin.isEnabled()) {
return;
}
// Only check the next site; this will set the cooldown-end flag + fire event if ready
checkPerSite(next.getSite(), user);
// Schedule the following site (if any)
schedulePerSite(user, false);
}, next.getSecondsUntilAvailable() + 2, TimeUnit.SECONDS);
});
}
/**
* Handles a vote event for cooldown scheduling.
*
* @param user the voting plugin user
* @param site the vote site
*/
public void vote(VotingPluginUser user, VoteSite site) {
if (cooldownCheckEnabled) {
schedule(user, true);
@@ -236,4 +381,55 @@ public class CoolDownCheck implements Listener {
}
}
/**
* Performance-optimized: scan users ONCE, process all daily-delay sites.
*/
public void checkAllVoteSites() {
final List<VoteSite> sites = plugin.getVoteSiteManager().getVoteSites();
if (sites == null || sites.isEmpty()) {
return;
}
final ArrayList<VoteSite> dailySites = new ArrayList<>();
for (int i = 0; i < sites.size(); i++) {
VoteSite site = sites.get(i);
if (site != null && site.isVoteDelayDaily()) {
dailySites.add(site);
}
}
if (dailySites.isEmpty()) {
return;
}
plugin.debug("Checking vote cooldown rewards for all players across " + dailySites.size() + " sites...");
plugin.getUserManager().forEachUserKeys((uuid, cols) -> {
if (!plugin.isEnabled() || uuid == null) {
return;
}
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, false);
if (user == null) {
return;
}
user.userDataFetechMode(UserDataFetchMode.TEMP_ONLY);
try {
if (cols != null) {
user.updateTempCacheWithColumns(cols);
cols.clear();
}
for (int i = 0; i < dailySites.size(); i++) {
checkPerSite(dailySites.get(i), user);
}
check(user);
} finally {
user.clearTempCache();
}
}, (count) -> plugin.debug("Finished checking vote cooldown rewards (processed: " + count + " users)"));
}
}
@@ -16,6 +16,7 @@ import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.signs.SignHandler;
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
import com.bencodez.votingplugin.topvoter.TopVoter;
// TODO: Auto-generated Javadoc
/**
@@ -25,10 +26,20 @@ public class ServerData {
private VotingPluginMain plugin = VotingPluginMain.plugin;
/**
* Constructs a new ServerData.
*
* @param plugin the main plugin instance
*/
public ServerData(VotingPluginMain plugin) {
this.plugin = plugin;
}
/**
* Adds an auto-cached placeholder.
*
* @param placeholder the placeholder to add
*/
public void addAutoCachedPlaceholder(String placeholder) {
List<String> p = getAutoCachedPlaceholder();
@@ -38,6 +49,11 @@ public class ServerData {
}
}
/**
* Adds a service site to the list.
*
* @param site the service site to add
*/
public synchronized void addServiceSite(String site) {
ArrayList<String> l = getServiceSites();
if (!getServiceSites().contains(site)) {
@@ -68,6 +84,12 @@ public class ServerData {
getSignSkullLocation("" + count), getSignData("" + count), getSignPosition("" + count)));
}
/**
* Adds a timed vote to the cache.
*
* @param num the vote number
* @param vote the vote time queue entry
*/
public void addTimeVoted(int num, VoteTimeQueue vote) {
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
@@ -75,23 +97,46 @@ public class ServerData {
saveData();
}
/**
* Adds a vote shop purchase for the specified identifier.
*
* @param ident the vote shop identifier
*/
public void addVoteShopPurchase(String ident) {
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
}
/**
* Clears the timed vote cache.
*/
public void clearTimedVoteCache() {
getData().set("TimedVoteCache", null);
saveData();
}
/**
* Gets the auto cached placeholders.
*
* @return the auto cached placeholder list
*/
public List<String> getAutoCachedPlaceholder() {
return getData().getStringList("AutoCachePlaceholders");
}
/**
* Gets the current bungee vote party count.
*
* @return the bungee vote party current count
*/
public int getBungeeVotePartyCurrent() {
return getData().getInt("BungeeVotePartyCurrent");
}
/**
* Gets the required votes for bungee vote party.
*
* @return the bungee vote party required votes
*/
public int getBungeeVotePartyRequired() {
return getData().getInt("BungeeVotePartyRequired");
}
@@ -110,10 +155,20 @@ public class ServerData {
return data;
}
/**
* Gets the list of disabled reminders.
*
* @return the disabled reminders
*/
public List<String> getDisabledReminders() {
return getData().getStringList("DisabledReminders");
}
/**
* Gets the service sites list.
*
* @return the service sites
*/
@SuppressWarnings("unchecked")
public ArrayList<String> getServiceSites() {
return (ArrayList<String>) getData().getList("ServiceSites", new ArrayList<>());
@@ -179,6 +234,11 @@ public class ServerData {
getData().getDouble("Signs." + sign + ".Skull.Z"));
}
/**
* Gets the timed vote cache keys.
*
* @return the timed vote cache keys
*/
public Set<String> getTimedVoteCacheKeys() {
if (getData().isConfigurationSection("TimedVoteCache")) {
return getData().getConfigurationSection("TimedVoteCache").getKeys(false);
@@ -186,18 +246,40 @@ public class ServerData {
return new HashSet<>();
}
/**
* Gets the timed vote cache section for the given number.
*
* @param num the cache entry number
* @return the timed vote cache section
*/
public ConfigurationSection getTimedVoteCacheSection(String num) {
return getData().getConfigurationSection("TimedVoteCache." + num);
}
/**
* Gets the extra required votes for vote party.
*
* @return the vote party extra required votes
*/
public int getVotePartyExtraRequired() {
return getData().getInt("VotePartyExtraRequired", 0);
}
/**
* Gets the number of purchases for a vote shop item.
*
* @param ident the vote shop identifier
* @return the vote shop purchases
*/
public int getVoteShopPurchases(String ident) {
return getData().getInt("VoteShopPurchases." + ident);
}
/**
* Checks if the last vote party was on the same day.
*
* @return true if same day
*/
public boolean isLastVotePartySameDay() {
int num = getData().getInt("LastVoteParty", 0);
if (num == plugin.getTimeChecker().getTime().getDayOfYear()) {
@@ -206,6 +288,11 @@ public class ServerData {
return false;
}
/**
* Checks if the last vote party was in the same week.
*
* @return true if same week
*/
public boolean isLastVotePartySameWeek() {
int num = getData().getInt("LastVotePartyWeek", -1);
if (num == plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear())
@@ -215,6 +302,11 @@ public class ServerData {
return false;
}
/**
* Checks if the vote shop has been converted.
*
* @return true if converted
*/
public boolean isVoteShopConverted() {
return getData().getBoolean("VoteShopConverted");
}
@@ -244,6 +336,27 @@ public class ServerData {
plugin.getServerDataFile().reloadData();
}
/**
* Gets the Discord message ID for the top voter.
*
* @param top the top voter type
* @return the top voter message ID
*/
public long getTopVoterMessageId(TopVoter top) {
return getData().getLong("DiscordSRV.TopVoterMessageId." + top.toString(), 0);
}
/**
* Sets the Discord message ID for the top voter.
*
* @param top the top voter type
* @param messageId the message ID
*/
public void setTopVoterMessageId(TopVoter top, long messageId) {
getData().set("DiscordSRV.TopVoterMessageId." + top.toString(), messageId);
saveData();
}
/**
* Removes the sign.
*
@@ -271,6 +384,11 @@ public class ServerData {
plugin.getServerDataFile().saveData();
}
/**
* Saves the disabled reminders list.
*
* @param disabledReminders the list of UUIDs with disabled reminders
*/
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
ArrayList<String> uuids = new ArrayList<>();
for (UUID uuid : disabledReminders) {
@@ -280,31 +398,65 @@ public class ServerData {
saveData();
}
/**
* Sets the auto cached placeholders.
*
* @param placeholders the list of placeholders
*/
public void setAutoCachedPlaceholder(List<String> placeholders) {
getData().set("AutoCachePlaceholders", placeholders);
saveData();
}
/**
* Sets the current bungee vote party count.
*
* @param current the current vote count
*/
public void setBungeeVotePartyCurrent(int current) {
getData().set("BungeeVotePartyCurrent", current);
saveData();
}
/**
* Sets the required votes for bungee vote party.
*
* @param required the required vote count
*/
public void setBungeeVotePartyRequired(int required) {
getData().set("BungeeVotePartyRequired", required);
saveData();
}
/**
* Sets the service sites list.
*
* @param list the service sites list
*/
public void setServiceSites(ArrayList<String> list) {
getData().set("ServiceSites", list);
saveData();
}
/**
* Sets the vote shop converted status.
*
* @param value the converted status
*/
public void setShopConverted(boolean value) {
getData().set("VoteShopConverted", value);
saveData();
}
/**
* Sets sign data.
*
* @param count the sign count
* @param location the sign location
* @param skullLocation the skull location
* @param data the sign data
* @param position the sign position
*/
public void setSign(String count, Location location, Location skullLocation, String data, int position) {
getData().set("Signs." + count + ".World", location.getWorld().getName());
@@ -322,6 +474,12 @@ public class ServerData {
saveData();
}
/**
* Sets the skull location for a sign.
*
* @param count the sign count
* @param skullLocation the skull location
*/
public void setSkullLocation(String count, Location skullLocation) {
if (skullLocation != null) {
getData().set("Signs." + count + ".Skull.World", skullLocation.getWorld().getName());
@@ -339,27 +497,47 @@ public class ServerData {
saveData();
}
/**
* Sets the extra required votes for vote party.
*
* @param value the extra required votes
*/
public void setVotePartyExtraRequired(int value) {
getData().set("VotePartyExtraRequired", value);
saveData();
}
/**
* Sets the number of purchases for a vote shop item.
*
* @param ident the vote shop identifier
* @param amount the purchase amount
*/
public void setVoteShopPurchases(String ident, int amount) {
getData().set("VoteShopPurchases." + ident, amount);
saveData();
}
/**
* Updates the last vote party timestamp to today.
*/
public void updateLastVoteParty() {
getData().set("LastVoteParty", plugin.getTimeChecker().getTime().getDayOfYear());
saveData();
}
/**
* Updates the last vote party week timestamp to this week.
*/
public void updateLastVotePartyWeek() {
getData().set("LastVotePartyWeek",
plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear()));
saveData();
}
/**
* Updates placeholders to lowercase format.
*/
public void updatePlaceholders() {
boolean data = getData().getBoolean("AutoCacheUpdated", false);
if (!data) {
@@ -0,0 +1,222 @@
package com.bencodez.votingplugin.discord;
import java.awt.Color;
import java.time.Instant;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bukkit.configuration.ConfigurationSection;
import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
import com.bencodez.advancedcore.api.rewards.Reward;
import com.bencodez.advancedcore.api.rewards.injected.RewardInjectConfigurationSection;
import com.bencodez.advancedcore.api.user.AdvancedCoreUser;
import com.bencodez.advancedcore.api.user.UserStartup;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.topvoter.TopVoter;
import com.bencodez.votingplugin.topvoter.TopVoterPlayer;
import github.scarsz.discordsrv.DiscordSRV;
import github.scarsz.discordsrv.api.Subscribe;
import github.scarsz.discordsrv.api.events.DiscordReadyEvent;
import github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;
import github.scarsz.discordsrv.dependencies.jda.api.JDA;
import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel;
import github.scarsz.discordsrv.util.DiscordUtil;
import lombok.Getter;
/**
* Handler for Discord integration.
*/
public class DiscordHandler {
private final VotingPluginMain plugin;
@Getter
private final HashMap<TopVoter, Long> topVoterMessageIds = new HashMap<TopVoter, Long>();
private final AtomicBoolean discordReady = new AtomicBoolean(false);
/**
* Constructs a new Discord handler.
*
* @param plugin the plugin instance
*/
public DiscordHandler(VotingPluginMain plugin) {
this.plugin = plugin;
for (TopVoter top : TopVoter.values()) {
long savedId = plugin.getServerData().getTopVoterMessageId(top);
topVoterMessageIds.put(top, savedId);
}
}
/** Call this early, e.g. from onEnable() in main plugin class */
public void load() {
DiscordSRV.api.subscribe(this);
plugin.getLogger().info("DiscordHandler loaded; awaiting Discord readiness.");
// if DiscordSRV is already up and running, mark it ready now
if (DiscordUtil.getJda().getStatus() == JDA.Status.CONNECTED) {
discordReady.set(true);
plugin.getLogger().info("DiscordSRV was already ready; manual update now available.");
}
plugin.getRewardHandler().addInjectedReward(new RewardInjectConfigurationSection("DiscordSRV") {
@Override
public String onRewardRequested(Reward arg0, com.bencodez.advancedcore.api.user.AdvancedCoreUser user,
ConfigurationSection section, HashMap<String, String> placeholders) {
if (section.getBoolean("Enabled")) {
String msg = PlaceholderUtils
.replacePlaceHolder(section.getString("Message", "Please set a message"), placeholders);
msg = PlaceholderUtils.replacePlaceHolders(user.getOfflinePlayer(), msg);
sendRewardMessage(msg, section.getString("ChannelID", "0"));
}
return null;
}
});
plugin.addUserStartup(new UserStartup() {
@Override
public void onStartUp(AdvancedCoreUser user) {
}
@Override
public void onStart() {
}
@Override
public void onPostFinish() {
plugin.getTimer().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
updateDiscordLeaderboard();
}
}, 130, 60 * 60, TimeUnit.SECONDS); // 10-minute interval
}
@Override
public void onFinish() {
}
});
}
/**
* Fired once JDA is fully initialized.
*
* @param event the Discord ready event
*/
@Subscribe
public void onDiscordReady(DiscordReadyEvent event) {
discordReady.set(true);
plugin.getLogger().info("DiscordSRV is ready; manual update now available.");
}
/**
* Public method to update the Top Voter message on demand. Checks Discord
* readiness internally.
*/
public void updateDiscordLeaderboard() {
if (!discordReady.get()) {
plugin.getLogger().warning("DiscordSRV not ready yet; cannot update Top Voters.");
return;
}
for (TopVoter top : TopVoter.values()) {
if (plugin.getConfigFile().isDiscordSRVTopVoterEnabled(top)) {
plugin.debug("Updating Discord Top Voter: " + top.toString());
updateTopVoterMessageId(top);
}
}
}
/**
* Updates the top voter message ID for the specified top voter.
*
* @param top the top voter
*/
public void updateTopVoterMessageId(TopVoter top) {
plugin.extraDebug("Updating Discord Top Voter message for: " + top);
long channelId = plugin.getConfigFile().getDiscordSRVTopVoterChannel(top);
LinkedHashMap<TopVoterPlayer, Integer> topVoters = plugin.getTopVoter(top);
String title = plugin.getConfigFile().getDiscordSRVTopVoterTitle(top);
boolean newMessage = plugin.getConfigFile().isDiscordSRVTopVoterNewMessageOnUpdate(top);
EmbedBuilder eb = new EmbedBuilder().setTitle(title).setColor(Color.CYAN).setTimestamp(Instant.now());
if (topVoters == null || topVoters.isEmpty()) {
eb.setDescription("No votes recorded yet.");
} else {
StringBuilder sb = new StringBuilder();
sb.append("```");
int rank = 1;
for (Entry<TopVoterPlayer, Integer> entry : topVoters.entrySet()) {
if (rank > 10)
break;
String prefix = rank <= 3 ? new String[] { "🥇", "🥈", "🥉" }[rank - 1] : rank + ".";
String player = entry.getKey().getPlayerName();
int votes = entry.getValue();
// simple alignment: trim long names, pad to 16 chars
if (player.length() > 16)
player = player.substring(0, 16);
sb.append(String.format("%-3s %-16s %4d votes%n", prefix, player, votes));
rank++;
}
sb.append("```");
eb.setDescription(sb.toString()).setFooter("Top 10 • Updated");
}
TextChannel channel = DiscordUtil.getJda().getTextChannelById(channelId);
if (channel == null) {
plugin.getLogger().warning("Discord channel ID " + channelId + " not found: " + top);
return;
}
long existingId = topVoterMessageIds.getOrDefault(top, 0L);
if (existingId <= 0 || newMessage) {
channel.sendMessageEmbeds(eb.build()).queue(msg -> {
long newId = msg.getIdLong();
topVoterMessageIds.put(top, newId);
if (!newMessage)
plugin.getServerData().setTopVoterMessageId(top, newId);
plugin.debug("Posted new Top Voters " + top + " (ID: " + newId + ")");
}, err -> plugin.getLogger().warning("Error sending Top Voters " + top + ": " + err.getMessage()));
} else {
channel.editMessageEmbedsById(existingId, eb.build()).queue(
m -> plugin.debug("Edited Top Voters " + top + " (ID: " + existingId + ")"),
err -> plugin.getLogger().warning("Error editing Top Voters " + top + ": " + err.getMessage()));
}
}
/**
* Sends a reward message to a Discord channel.
*
* @param message the message to send
* @param channelId the Discord channel ID
*/
public void sendRewardMessage(String message, String channelId) {
TextChannel channel = DiscordUtil.getJda().getTextChannelById(channelId);
if (channel != null) {
channel.sendMessage(message).queue();
} else {
plugin.getLogger().warning("Discord channel ID " + channelId + " not found for reward message.");
}
}
}
@@ -1,11 +1,13 @@
package com.bencodez.votingplugin.events;
import java.util.UUID;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.proxy.BungeeMessageData;
import com.bencodez.votingplugin.proxy.VoteTotalsSnapshot;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
import lombok.Setter;
@@ -34,7 +36,7 @@ public class PlayerPostVoteEvent extends Event {
@Getter
@Setter
private BungeeMessageData bungeeTextTotals;
private VoteTotalsSnapshot bungeeTextTotals;
@Getter
@Setter
@@ -62,16 +64,50 @@ public class PlayerPostVoteEvent extends Event {
@Getter
@Setter
private VotingPluginUser votingPluginUser;
private boolean cached;
@Getter
@Setter
private String service;
@Getter
@Setter
private UUID uuid;
@Getter
@Setter
private String playerName;
@Getter
@Setter
private UUID voteUUID;
/**
* Constructs a new PlayerPostVoteEvent.
*
* @param voteSite the vote site
* @param user the voting plugin user
* @param realVote whether this is a real vote
* @param forceBungee whether to force Bungee processing
* @param voteTime the vote timestamp
* @param cached whether the vote was cached
* @param service the service name
* @param uuid the player UUID
* @param playerName the player name
* @param voteUUID the vote UUID
*/
public PlayerPostVoteEvent(VoteSite voteSite, VotingPluginUser user, boolean realVote, boolean forceBungee,
long voteTime) {
long voteTime, boolean cached, String service, UUID uuid, String playerName, UUID voteUUID) {
super(true);
this.user = user;
this.voteSite = voteSite;
this.realVote = realVote;
this.forceBungee = forceBungee;
this.voteTime = voteTime;
this.cached = cached;
this.service = service;
this.uuid = uuid;
this.playerName = playerName;
this.voteUUID = voteUUID;
}
/*
@@ -42,6 +42,12 @@ public class PlayerReceivePointsEvent extends Event {
@Setter
private String serviceSite = "";
/**
* Constructs a new PlayerReceivePointsEvent.
*
* @param user the voting plugin user
* @param points the points received
*/
public PlayerReceivePointsEvent(VotingPluginUser user, int points) {
super(true);
this.player = user;
@@ -1,5 +1,7 @@
package com.bencodez.votingplugin.events;
import java.util.UUID;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -38,10 +40,22 @@ public class PlayerSpecialRewardEvent extends Event {
@Setter
private VotingPluginUser user;
public PlayerSpecialRewardEvent(VotingPluginUser user, SpecialRewardType type) {
@Getter
@Setter
private UUID voteUUID;
/**
* Constructs a new PlayerSpecialRewardEvent.
*
* @param user the voting plugin user
* @param type the special reward type
* @param voteUUID the vote UUID
*/
public PlayerSpecialRewardEvent(VotingPluginUser user, SpecialRewardType type, UUID voteUUID) {
super(true);
this.type = type;
this.user = user;
this.voteUUID = voteUUID;
}
/*
@@ -34,6 +34,11 @@ public class PlayerVoteCoolDownEndEvent extends Event {
@Setter
private VotingPluginUser player;
/**
* Constructs a new PlayerVoteCoolDownEndEvent.
*
* @param user the voting plugin user
*/
public PlayerVoteCoolDownEndEvent(VotingPluginUser user) {
super(true);
player = user;
@@ -3,9 +3,9 @@ package com.bencodez.votingplugin.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.proxy.BungeeMessageData;
import com.bencodez.votingplugin.proxy.VoteTotalsSnapshot;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
import lombok.Setter;
@@ -38,7 +38,7 @@ public class PlayerVoteEvent extends Event {
@Getter
@Setter
private BungeeMessageData bungeeTextTotals;
private VoteTotalsSnapshot bungeeTextTotals;
@Getter
@Setter
@@ -84,6 +84,14 @@ public class PlayerVoteEvent extends Event {
@Setter
private int voteNumber = 1;
/**
* Constructs a new PlayerVoteEvent.
*
* @param voteSite the vote site
* @param voteUsername the username of the voter
* @param serviceSite the service site name
* @param realVote whether this is a real vote
*/
public PlayerVoteEvent(VoteSite voteSite, String voteUsername, String serviceSite, boolean realVote) {
super(true);
this.player = voteUsername;
@@ -3,8 +3,8 @@ package com.bencodez.votingplugin.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
import lombok.Setter;
@@ -39,6 +39,12 @@ public class PlayerVoteSiteCoolDownEndEvent extends Event {
@Setter
private VoteSite site;
/**
* Constructs a new PlayerVoteSiteCoolDownEndEvent.
*
* @param user the voting plugin user
* @param site the vote site
*/
public PlayerVoteSiteCoolDownEndEvent(VotingPluginUser user, VoteSite site) {
super(true);
player = user;
@@ -2,8 +2,34 @@ package com.bencodez.votingplugin.events;
import lombok.Getter;
/**
* Enumeration for different special reward types.
*/
public enum SpecialRewardType {
ALLSITE, CUMMULATIVE, FIRSTVOTE, FIRSTVOTETODAY, MILESTONE, VOTESTREAK, ALMOSTALLSITES;
/** @deprecated All site reward. */
@Deprecated
ALLSITE,
/** @deprecated Cumulative reward. */
@Deprecated
CUMMULATIVE,
/** @deprecated First vote reward. */
@Deprecated
FIRSTVOTE,
/** @deprecated First vote today reward. */
@Deprecated
FIRSTVOTETODAY,
/** @deprecated Milestone reward. */
@Deprecated
MILESTONE,
/** Vote streak reward. */
VOTESTREAK,
/** @deprecated Almost all sites reward. */
@Deprecated
ALMOSTALLSITES,
/** Top voter reward. */
TOPVOTER,
/** Vote streaks reward. */
VOTESTREAKS;
@Getter
private int amount = -1;
@@ -11,14 +37,48 @@ public enum SpecialRewardType {
@Getter
private String type = "";
/**
* Sets the amount for this special reward.
*
* @param num the amount
* @return this special reward type
*/
public SpecialRewardType setAmount(int num) {
amount = num;
return this;
}
/**
* Sets the type for this special reward.
*
* @param type the type
* @return this special reward type
*/
public SpecialRewardType setType(String type) {
this.type = type;
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(name());
if (amount >= 0) {
sb.append("(amount=").append(amount);
}
if (type != null && !type.isEmpty()) {
if (amount >= 0) {
sb.append(", ");
} else {
sb.append("(");
}
sb.append("type=").append(type).append(")");
} else if (amount >= 0) {
sb.append(")");
}
return sb.toString();
}
}
@@ -0,0 +1,159 @@
package com.bencodez.votingplugin.events;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.bencodez.votingplugin.specialrewards.votemilestones.VoteMilestone;
import com.bencodez.votingplugin.user.VotingPluginUser;
import lombok.Getter;
/**
* Fired after a VoteMilestone reward has been executed successfully.
*/
public class VoteMilestoneRewardEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
private final VotingPluginUser user;
private final UUID uuid;
private final String playerName;
private final VoteMilestone milestone;
private final long value;
private final String groupId;
private final String rewardPath;
@Getter
private final UUID voteUUID;
private final Map<String, String> placeholders;
/**
* Constructs a new VoteMilestoneRewardEvent.
*
* @param user VotingPluginUser who received the reward
* @param milestone milestone that triggered
* @param value resolved total value used for matching
* @param groupId resolved group id used for selection
* @param rewardPath path used to execute rewards
* @param placeholders placeholders passed to the reward handler
* @param voteUUID UUID of the vote that triggered this reward (may be null)
*/
public VoteMilestoneRewardEvent(VotingPluginUser user, VoteMilestone milestone, long value, String groupId,
String rewardPath, Map<String, String> placeholders, UUID voteUUID) {
super(true);
this.user = user;
this.uuid = user == null ? null : user.getJavaUUID();
this.playerName = user == null ? null : user.getPlayerName();
this.milestone = milestone;
this.value = value;
this.groupId = groupId;
this.rewardPath = rewardPath;
this.voteUUID = voteUUID;
if (placeholders == null || placeholders.isEmpty()) {
this.placeholders = Collections.emptyMap();
} else {
this.placeholders = Collections.unmodifiableMap(new HashMap<>(placeholders));
}
}
/**
* Gets the voting plugin user associated with this event.
*
* @return the voting plugin user
*/
public VotingPluginUser getUser() {
return user;
}
/**
* Gets the player UUID.
*
* @return the player UUID
*/
public UUID getUuid() {
return uuid;
}
/**
* Gets the player name.
*
* @return the player name
*/
public String getPlayerName() {
return playerName;
}
/**
* Gets the milestone that triggered this event.
*
* @return milestone instance
*/
public VoteMilestone getMilestone() {
return milestone;
}
/**
* Gets the milestone ID.
*
* @return milestone id string
*/
public String getMilestoneId() {
return milestone == null ? null : milestone.getId();
}
/**
* Gets the value that triggered the milestone.
*
* @return the milestone value
*/
public long getValue() {
return value;
}
/**
* Gets the group ID used for selection.
*
* @return group id string
*/
public String getGroupId() {
return groupId;
}
/**
* Gets the configuration path for the rewards.
*
* @return the reward path
*/
public String getRewardPath() {
return rewardPath;
}
/**
* Gets the placeholders map for this milestone reward.
*
* @return map of placeholder names to values
*/
public Map<String, String> getPlaceholders() {
return placeholders;
}
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
/**
* Gets the handler list for this event.
*
* @return handler list
*/
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
@@ -28,6 +28,9 @@ public class VotePartyEvent extends Event {
@Setter
private boolean cancelled;
/**
* Constructs a new VotePartyEvent.
*/
public VotePartyEvent() {
super(true);
}
@@ -0,0 +1,51 @@
package com.bencodez.votingplugin.events;
import java.util.UUID;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.bencodez.votingplugin.user.VotingPluginUser;
import lombok.Getter;
/**
* Fired when a player attempts to purchase an item from VotingPlugin's
* VoteShop.
*/
public class VoteShopPurchaseEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
@Getter
private UUID playerUuid;
@Getter
private String playerName;
@Getter
private VotingPluginUser user;
@Getter
private String identifier;
@Getter
private int cost;
public VoteShopPurchaseEvent(UUID playerUUID, String playerName, VotingPluginUser user, String identifier,
int cost) {
super(true);
this.playerName = playerName;
this.user = user;
this.playerUuid = playerUUID;
this.identifier = identifier;
this.cost = cost;
}
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
@@ -6,18 +6,20 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import com.bencodez.advancedcore.api.player.UuidLookup;
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
import com.bencodez.advancedcore.listeners.AdvancedCoreLoginEvent;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.proxy.VotingPluginWire;
import com.bencodez.votingplugin.user.VotingPluginUser;
// TODO: Auto-generated Javadoc
/**
* The Class PlayerJoinEvent.
*/
public class PlayerJoinEvent implements Listener {
/** The plugin. */
private VotingPluginMain plugin;
private final VotingPluginMain plugin;
/**
* Instantiates a new player join event.
@@ -28,21 +30,48 @@ public class PlayerJoinEvent implements Listener {
this.plugin = plugin;
}
private void login(Player player) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
if (player.isOp() && plugin.isYmlError()) {
private static boolean isBlank(String s) {
return s == null || s.trim().isEmpty() || "null".equalsIgnoreCase(s.trim());
}
/**
* On AdvancedCore login event (post-auth / delayed login).
*
* @param event the event
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerLogin(AdvancedCoreLoginEvent event) {
if (event == null || !plugin.isMySQLOkay() || event.isCancelled() || event.getUser() == null) {
return;
}
// UUID is authoritative here (String)
String uuid = event.getUuid();
if (isBlank(uuid)) {
return;
}
// "Has data" should come from AdvancedCore event (storage presence)
boolean hasData = event.isUserInStorage();
// Resolve VotingPluginUser by the storage UUID string (offline-mode
// name-derived UUID)
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (user == null) {
return;
}
Player player = event.getPlayer();
if (player != null && player.isOp() && plugin.isYmlError()) {
user.sendMessage("&cVotingPlugin: Detected yml error, please check console for details");
}
boolean data = user.getData().hasData();
// run remind
user.loginMessage();
if (data) {
if (hasData) {
// give offline vote (if they voted offline)
user.offVote();
} else {
plugin.debug("No data detected for " + player.getUniqueId().toString() + "/" + player.getName());
plugin.debug("No data detected for " + user.getUUID() + "/" + user.getPlayerName());
}
user.loginRewards();
@@ -50,42 +79,49 @@ public class PlayerJoinEvent implements Listener {
plugin.getPlaceholders().onUpdate(user, true);
if (plugin.getBungeeSettings().isUseBungeecoord()) {
plugin.getBungeeHandler().getGlobalMessageHandler().sendMessage("Login", user.getPlayerName(),
user.getUUID(), plugin.getBungeeSettings().getServer());
plugin.getBungeeHandler().getGlobalMessageHandler().sendMessage(VotingPluginWire.login(user.getPlayerName(),
user.getUUID(), plugin.getBungeeSettings().getServer()));
}
}
/**
* On player login.
* Handles player quit events.
*
* @param event the event
* @param event the player quit event
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerLogin(AdvancedCoreLoginEvent event) {
if (event.getPlayer() == null || !plugin.isMySQLOkay()) {
public void onPlayerQuit(PlayerQuitEvent event) {
if (plugin == null || !plugin.isEnabled() || event == null) {
return;
}
login(event.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent event) {
if (plugin != null && plugin.isEnabled()) {
final Player player = event.getPlayer();
plugin.getLoginTimer().execute(new Runnable() {
@Override
public void run() {
VotingPluginMain.plugin.getAdvancedTab().remove(player.getUniqueId());
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
user.dontCache();
user.logoutRewards();
plugin.getPlaceholders().onLogout(user);
}
});
final Player player = event.getPlayer();
if (player == null) {
return;
}
plugin.getLoginTimer().execute(new Runnable() {
@Override
public void run() {
VotingPluginMain.plugin.getAdvancedTab().remove(player.getUniqueId());
// Use AdvancedCore UUIDLookup to derive the correct UUID (online/offline aware)
String uuid = UuidLookup.getInstance().getUUID(player.getName());
if (isBlank(uuid)) {
// Fallback to online UUID if lookup fails
uuid = player.getUniqueId().toString();
}
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
if (user == null) {
return;
}
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
user.logoutRewards();
plugin.getPlaceholders().onLogout(user);
}
});
}
}
}
@@ -3,6 +3,8 @@ package com.bencodez.votingplugin.listeners;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -10,15 +12,15 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.bencodez.advancedcore.api.misc.PlayerManager;
import com.bencodez.advancedcore.api.bedrock.BedrockNameResolver;
import com.bencodez.advancedcore.api.user.validation.UserValidationResult;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.events.PlayerPostVoteEvent;
import com.bencodez.votingplugin.events.PlayerVoteEvent;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.proxy.BungeeMethod;
import com.bencodez.votingplugin.topvoter.TopVoter;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
// TODO: Auto-generated Javadoc
/**
@@ -51,33 +53,36 @@ public class PlayerVoteListener implements Listener {
String playerName = event.getPlayer();
plugin.debug("Processing PlayerVoteEvent: " + playerName + "/" + event.getServiceSite());
boolean notValid = false;
if (!PlayerManager.getInstance().isValidUser(playerName, plugin.getConfigFile().isAllowUnJoinedCheckServer())) {
if (!playerName.startsWith(plugin.getOptions().getBedrockPlayerPrefix())
&& !plugin.getOptions().getBedrockPlayerPrefix().isEmpty()) {
if (!event.isBungee() && PlayerManager.getInstance().isValidUser(
plugin.getOptions().getBedrockPlayerPrefix() + playerName,
plugin.getConfigFile().isAllowUnJoinedCheckServer())) {
plugin.debug("Detected a bedrock user without bedrock prefix, adjusting");
playerName = plugin.getOptions().getBedrockPlayerPrefix() + playerName;
} else {
notValid = true;
}
} else {
notValid = true;
// check for name casing
final String properName = plugin.getUserManager().getProperName(playerName);
// Validate BEFORE full bedrock/db-backed resolution
boolean allowUnJoinedCheckServer = plugin.getConfigFile().isAllowUnJoinedCheckServer();
UserValidationResult validationResult = plugin.getUserManager().getValidationService().validate(properName,
allowUnJoinedCheckServer);
plugin.extraDebug("Vote validation result for " + properName + ": valid=" + validationResult.isValid()
+ ", source=" + validationResult.getSource() + ", reason=" + validationResult.getReason()
+ ", normalizedName=" + validationResult.getNormalizedName() + ", bedrock="
+ validationResult.isBedrock());
if (!validationResult.isValid() && !plugin.getConfigFile().isAllowUnjoined()) {
plugin.getLogger().warning("Player " + properName + " has not joined before, disregarding vote. "
+ "Reason: " + validationResult.getReason() + ". Set AllowUnjoined to true to accept.");
if (event.isBungee() && plugin.getBungeeSettings().isRemoveInvalidUsers()) {
plugin.getVotingPluginUserManager().getVotingPluginUser(properName).remove();
}
return;
}
if (notValid) {
if (!plugin.getConfigFile().isAllowUnjoined()) {
plugin.getLogger().warning("Player " + playerName
+ " has not joined before, disregarding vote, set AllowUnjoined to true to prevent this");
if (event.isBungee() && plugin.getBungeeSettings().isRemoveInvalidUsers()) {
plugin.getVotingPluginUserManager().getVotingPluginUser(playerName).remove();
}
return;
}
}
// Resolve Bedrock/Java + add prefix only when appropriate AFTER validation
BedrockNameResolver.Result rn = plugin.getBedrockHandle().resolve(properName);
String creditedName = rn.finalName;
plugin.debug("Vote name resolved: " + properName + " -> " + creditedName + " (" + rn.rationale + ")");
// If we get here, use the resolved/possibly-prefixed name going forward
playerName = creditedName;
if (playerName.isEmpty()) {
plugin.getLogger().warning("Empty player name from vote, ignoring");
@@ -89,14 +94,22 @@ public class PlayerVoteListener implements Listener {
+ event.getBungeeTextTotals());
if (plugin.getBungeeSettings().isTriggerVotifierEvent()) {
new BungeeVotifierEvent().send(plugin, event);
try {
new ProxyVotifierEvent().send(plugin, event);
} catch (NoClassDefFoundError ex) {
plugin.getLogger().severe(
"Failed to trigger Votifier event for proxy vote. Either install votiifer or disable tirgger votiifer event");
plugin.getLogger().severe("Error: " + ex.getMessage());
plugin.debug(ex);
}
}
}
VoteSite voteSite = event.getVoteSite();
if (voteSite == null) {
voteSite = plugin.getVoteSite(plugin.getVoteSiteName(true, event.getServiceSite()), true);
voteSite = plugin.getVoteSiteManager()
.getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, event.getServiceSite()), true);
}
// check valid service sites
@@ -105,7 +118,7 @@ public class PlayerVoteListener implements Listener {
plugin.getLogger().warning("No voting site with the service site: '" + event.getServiceSite() + "'");
ArrayList<String> services = new ArrayList<>();
for (VoteSite site : plugin.getVoteSites()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSites()) {
services.add(site.getServiceSite());
}
plugin.getLogger().warning("Currently set service sites: " + ArrayUtils.makeStringList(services));
@@ -127,6 +140,7 @@ public class PlayerVoteListener implements Listener {
// player online
user = plugin.getVotingPluginUserManager().getVotingPluginUser(p);
} else {
// attempt to get exact name from cache matching casing
user = plugin.getVotingPluginUserManager().getVotingPluginUser(playerName);
}
}
@@ -144,6 +158,14 @@ public class PlayerVoteListener implements Listener {
}
}
UUID voteUUID = UUID.randomUUID();
if (event.isBungee() && event.getBungeeTextTotals() != null) {
voteUUID = event.getBungeeTextTotals().getVoteUUID();
if (voteUUID == null) {
voteUUID = UUID.randomUUID();
}
}
final String uuid = user.getUUID();
// reupdate cache
@@ -154,20 +176,21 @@ public class PlayerVoteListener implements Listener {
// vote party
plugin.getVoteParty().vote(user, event.isRealVote(), event.isForceBungee());
if (event.isBroadcast() && !plugin.getBungeeSettings().isDisableBroadcast()) {
// broadcast vote if enabled in config
if (plugin.getConfigFile().isBroadcastVotesEnabled()
&& (plugin.getBungeeSettings().isBungeeBroadcast() || !event.isBungee())) {
if (!plugin.getConfigFile().isFormatBroadcastWhenOnline() || user.isOnline()) {
voteSite.broadcastVote(user);
if (event.isBroadcast()) {
if (plugin.getBroadcastHandler() != null) {
boolean online = user.isOnline();
if (event.isBungee()) {
online = event.isWasOnline();
}
if (!user.isVanished()) {
plugin.getBroadcastHandler().broadcastVote(user.getJavaUUID(), playerName,
voteSite.getDisplayName(), online);
} else {
plugin.debug("Not broadcasting vote for vanished user: " + user.getPlayerName());
}
}
}
if (plugin.getBroadcastHandler() != null) {
plugin.getBroadcastHandler().onVote(playerName);
}
long voteTime = 0;
// update last vote time
if (event.getTime() != 0) {
@@ -178,24 +201,7 @@ public class PlayerVoteListener implements Listener {
voteTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
// try logging to file
if (plugin.getConfigFile().isLogVotesToFile()) {
try {
plugin.logVote(LocalDateTime.now().atZone(ZoneId.systemDefault()).toLocalDateTime(), playerName,
voteSite.getKey());
} catch (Exception e) {
e.printStackTrace();
}
}
// check first vote rewards
plugin.getSpecialRewards().checkFirstVote(user, event.isForceBungee());
plugin.getSpecialRewards().checkFirstVoteToday(user, event.isForceBungee());
if (user.isReminded() && plugin.getConfigFile().isVoteRemindingRemindOnlyOnce()) {
user.setReminded(false);
}
boolean cached = false;
// check if player has voted on all sites in one day
if (((user.isOnline() || voteSite.isGiveOffline()) && plugin.getOptions().isProcessRewards())
|| event.isBungee()) {
@@ -203,7 +209,7 @@ public class PlayerVoteListener implements Listener {
if (event.isBungee()) {
online = event.isWasOnline();
}
user.playerVote(voteSite, online, false, event.isForceBungee());
user.playerVote(voteSite, online, event.isForceBungee());
if (event.getVoteNumber() == 1) {
user.sendVoteEffects(online);
}
@@ -214,6 +220,7 @@ public class PlayerVoteListener implements Listener {
if (!plugin.getConfigFile().isOfflineVotesLimitEnabled()
|| user.getNumberOfOfflineVotes(voteSite) <= plugin.getConfigFile().getOfflineVotesLimitAmount()) {
user.addOfflineVote(voteSite.getKey());
cached = true;
plugin.debug(
"Offline vote set for " + playerName + " (" + user.getUUID() + ") on " + voteSite.getKey());
} else {
@@ -244,40 +251,26 @@ public class PlayerVoteListener implements Listener {
LocalDateTime cTime = plugin.getTimeChecker().getTime();
int days = cTime.getDayOfMonth();
plugin.extraDebug("Current day of month: " + days + " Current total: " + value);
if (value >= days * plugin.getVoteSitesEnabled().size()) {
if (value >= days * plugin.getVoteSiteManager().getVoteSitesEnabled().size()) {
plugin.debug("Detected higher month total, changing. Current Total: " + value + " Days: " + days
+ " New Total: " + days * plugin.getVoteSitesEnabled().size());
user.setTotal(TopVoter.Monthly, days * plugin.getVoteSitesEnabled().size());
+ " New Total: " + days * plugin.getVoteSiteManager().getVoteSitesEnabled().size());
user.setTotal(TopVoter.Monthly, days * plugin.getVoteSiteManager().getVoteSitesEnabled().size());
}
}
// other rewards
plugin.getSpecialRewards().checkAllSites(user, event.isForceBungee());
plugin.getSpecialRewards().checkAlmostAllSites(user, event.isForceBungee());
plugin.getSpecialRewards().checkCumualativeVotes(user, event.getBungeeTextTotals(), event.isForceBungee());
plugin.getSpecialRewards().checkMilestone(user, event.getBungeeTextTotals(), event.isForceBungee());
plugin.getVoteMilestonesManager().handleVote(user, event.getBungeeTextTotals(), event.isForceBungee(), voteUUID,
new HashMap<String, String>());
plugin.getCoolDownCheck().vote(user, voteSite);
if (plugin.getBungeeSettings().isUseBungeecoord()) {
if (plugin.getBungeeHandler().getMethod().equals(BungeeMethod.MYSQL)) {
plugin.getBukkitScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
@Override
public void run() {
if (Bukkit.getOnlinePlayers().size() > 0) {
plugin.getBungeeHandler().getGlobalMessageHandler().sendMessage("VoteUpdate", uuid);
}
}
}, 2);
}
}
plugin.getVoteStreakHandler().processVote(user, voteTime, voteUUID);
PlayerPostVoteEvent postVoteEvent = new PlayerPostVoteEvent(voteSite, user, event.isRealVote(),
event.isForceBungee(), voteTime);
event.isForceBungee(), voteTime, cached, voteSite.getServiceSite(), user.getJavaUUID(), playerName,
voteUUID);
plugin.getServer().getPluginManager().callEvent(postVoteEvent);
if (user.isOnline()) {
if (user.isOnline() || plugin.getConfigFile().getPlaceholderCacheLevel().isCacheAlways()) {
plugin.getPlaceholders().onUpdate(user, true);
}
@@ -289,4 +282,4 @@ public class PlayerVoteListener implements Listener {
plugin.extraDebug("Finished vote processing: " + playerName + "/" + uuid);
}
}
}
@@ -5,9 +5,18 @@ import com.bencodez.votingplugin.events.PlayerVoteEvent;
import com.vexsoftware.votifier.model.Vote;
import com.vexsoftware.votifier.model.VotifierEvent;
public class BungeeVotifierEvent {
/**
* Handler for triggering Bungee Votifier events.
*/
public class ProxyVotifierEvent {
/**
* Sends a Votifier event for a player vote.
*
* @param plugin the main plugin instance
* @param event the player vote event
*/
public void send(VotingPluginMain plugin, PlayerVoteEvent event) {
plugin.debug("Triggering vote event");
plugin.debug("Triggering proxy vote event");
plugin.getBukkitScheduler().runTask(plugin, new Runnable() {
@Override
@@ -1,7 +1,5 @@
package com.bencodez.votingplugin.listeners;
import java.util.ArrayList;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -13,13 +11,11 @@ import com.bencodez.votingplugin.proxy.BungeeMethod;
import com.vexsoftware.votifier.model.Vote;
import com.vexsoftware.votifier.model.VotifierEvent;
// TODO: Auto-generated Javadoc
/**
* The Class VotiferEvent.
*/
public class VotiferEvent implements Listener {
/** The plugin. */
private VotingPluginMain plugin;
/**
@@ -48,7 +44,6 @@ public class VotiferEvent implements Listener {
final String IP = vote.getAddress();
final String voteUsername = vote.getUsername().trim();
if (IP.equals("VotingPlugin")) {
// ignore own plugin calls of event
return;
}
@@ -79,6 +74,7 @@ public class VotiferEvent implements Listener {
"Ignoring vote from votifier since pluginmessaging, socket, redis, or mqtt bungee method is enabled, this means you aren't setup correctly for those methods, please check: https://github.com/BenCodez/VotingPlugin/wiki/Bungeecord-Setups");
return;
}
String matchSite = "";
if (plugin.getConfigFile().isAdvancedServiceSiteHandling()) {
if (plugin.getServiceSiteHandler() != null) {
@@ -86,17 +82,8 @@ public class VotiferEvent implements Listener {
}
}
String voteSiteNameStr = plugin.getVoteSiteName(false, voteSite, matchSite);
ArrayList<String> sites = plugin.getConfigVoteSites().getVoteSitesNames(false);
boolean createSite = false;
if (sites != null) {
if (!ArrayUtils.containsIgnoreCase(sites, voteSiteNameStr)) {
createSite = true;
}
} else {
createSite = true;
}
String voteSiteNameStr = plugin.getVoteSiteManager().getVoteSiteName(false, voteSite, matchSite);
boolean createSite = !plugin.getVoteSiteManager().hasVoteSite(voteSiteNameStr);
String serviceSite = voteSite;
@@ -111,17 +98,15 @@ public class VotiferEvent implements Listener {
if (plugin.getTimeChecker().isActiveProcessing()
&& plugin.getConfigFile().isQueueVotesDuringTimeChange()) {
// time change in progress
plugin.debug("Adding vote to time queue " + voteUsername + "/" + voteSite);
plugin.getTimeQueueHandler().addVote(voteUsername, voteSite);
return;
}
String voteSiteName = plugin.getVoteSiteName(true, serviceSite, matchSite);
String voteSiteName = plugin.getVoteSiteManager().getVoteSiteName(true, serviceSite, matchSite);
PlayerVoteEvent voteEvent = new PlayerVoteEvent(plugin.getVoteSite(voteSiteName, true),
voteUsername, voteSite, true);
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
plugin.getVoteSiteManager().getVoteSite(voteSiteName, true), voteUsername, voteSite, true);
plugin.getServer().getPluginManager().callEvent(voteEvent);
if (voteEvent.isCancelled()) {
@@ -132,9 +117,7 @@ public class VotiferEvent implements Listener {
plugin.getLogger().severe("Error occured during vote processing");
e.printStackTrace();
}
}
});
}
}
}
@@ -29,6 +29,9 @@ public class MVdWPlaceholders {
this.plugin = plugin;
}
/**
* Loads MVdW placeholders if the MVdWPlaceholderAPI plugin is enabled.
*/
public void loadMVdWPlaceholders() {
if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) {
// The plugin is enabled
@@ -42,11 +45,7 @@ public class MVdWPlaceholders {
public String onPlaceholderReplace(PlaceholderReplaceEvent event) {
VotingPluginUser user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(event.getOfflinePlayer());
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders()
&& user.hasPrimaryAccount()) {
user = plugin.getVotingPluginUserManager()
.getVotingPluginUser(user.getPrimaryAccount());
}
return place.placeholderRequest(user,
event.getPlaceholder().substring("VotingPlugin_".length()));
}
@@ -25,12 +25,14 @@ import com.bencodez.advancedcore.api.placeholder.NonPlayerPlaceHolder;
import com.bencodez.advancedcore.api.placeholder.PlaceHolder;
import com.bencodez.advancedcore.api.user.AdvancedCoreUser;
import com.bencodez.advancedcore.api.user.UserDataChanged;
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.objects.VoteSite;
import com.bencodez.votingplugin.specialrewards.votemilestones.VoteMilestone;
import com.bencodez.votingplugin.topvoter.TopVoter;
import com.bencodez.votingplugin.topvoter.TopVoterPlayer;
import com.bencodez.votingplugin.user.VotingPluginUser;
import com.bencodez.votingplugin.votesites.VoteSite;
import lombok.Getter;
@@ -55,11 +57,18 @@ public class PlaceHolders {
@Getter
private PlaceholderCacheLevel cacheLevel;
/**
* Constructor for PlaceHolders.
* @param plugin the voting plugin instance
*/
public PlaceHolders(VotingPluginMain plugin) {
this.plugin = plugin;
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
}
/**
* Check for placeholders that need caching.
*/
public void checkNonCachedPlaceholders() {
while (!placeholdersToSetCacheOn.isEmpty()) {
String toCache = placeholdersToSetCacheOn.poll().toLowerCase();
@@ -87,16 +96,30 @@ public class PlaceHolders {
}
}
/**
* Get placeholder value for offline player.
* @param p the offline player
* @param identifier the placeholder identifier
* @return the placeholder value
*/
public String getPlaceHolder(OfflinePlayer p, String identifier) {
return getPlaceHolder(p, identifier, true);
}
/**
* Get placeholder value for offline player with javascript support.
* @param p the offline player
* @param identifier1 the placeholder identifier
* @param javascript enable javascript processing
* @return the placeholder value
*/
public String getPlaceHolder(OfflinePlayer p, String identifier1, boolean javascript) {
boolean forceProcess = false;
boolean useCache = true;
String identifier = identifier1.toLowerCase();
boolean custom = false;
if (identifier.endsWith("_process")) {
if (identifier.endsWith("_process")
|| (!Bukkit.isPrimaryThread() && plugin.getConfigFile().isAlwaysProcessAsyncPlaceholders())) {
forceProcess = true;
identifier = identifier.replaceAll("_process", "");
}
@@ -125,6 +148,12 @@ public class PlaceHolders {
}
/**
* Get placeholder value for online player.
* @param p the player
* @param identifier the placeholder identifier
* @return the placeholder value
*/
public String getPlaceHolder(Player p, String identifier) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders()) {
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
@@ -132,6 +161,15 @@ public class PlaceHolders {
return getPlaceHolder(p, identifier, false);
}
/**
* Get placeholder value with options.
* @param p the offline player
* @param identifier the placeholder identifier
* @param javascript enable javascript processing
* @param forceProcess force processing of placeholder
* @param useCache use cached value if available
* @return the placeholder value
*/
public String getPlaceholderValue(OfflinePlayer p, String identifier, boolean javascript, boolean forceProcess,
boolean useCache) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders() && javascript && p != null) {
@@ -174,11 +212,6 @@ public class PlaceHolders {
}
}
}
if (plugin.getConfigFile().isUsePrimaryAccountForPlaceholders()) {
if (user.hasPrimaryAccount()) {
user = plugin.getVotingPluginUserManager().getVotingPluginUser(user.getPrimaryAccount());
}
}
UUID uuid = user.getJavaUUID();
@@ -266,6 +299,9 @@ public class PlaceHolders {
return "Not a valid placeholder";
}
/**
* Load all placeholders.
*/
public void load() {
placeholders.clear();
nonPlayerPlaceholders.clear();
@@ -305,80 +341,19 @@ public class PlaceHolders {
}
}.withDescription("Returns true/false if user has broadcast disabled").updateDataKey("DisableBroadcast"));
placeholders.add(new PlaceHolder<VotingPluginUser>("DisableReminders") {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
if (plugin.getVoteReminding().getRemindersEnabled().containsKey(user.getJavaUUID())) {
if (!plugin.getVoteReminding().getRemindersEnabled().get(user.getJavaUUID()).booleanValue()) {
return "True";
}
}
return "False";
}
}.withDescription("Returns true/false if user has reminders disabled"));
placeholders.add(new PlaceHolder<VotingPluginUser>("MilestoneCount") {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
return "" + user.getMilestoneCount();
}
}.withDescription("User milestonecount").updateDataKey("MilestoneCount"));
Set<String> mVotes = plugin.getSpecialRewardsConfig().getMilestoneVotes();
for (String vote : mVotes) {
if (MessageAPI.isInt(vote)) {
final int num = Integer.parseInt(vote);
if (plugin.getSpecialRewardsConfig().getMilestoneRewardEnabled(num)) {
placeholders.add(new PlaceHolder<VotingPluginUser>("milestone_numberofvotesuntil_" + num) {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
int toGo = num - user.getMilestoneCount();
if (toGo >= 0) {
return "" + toGo;
}
return "0";
}
}.withDescription("Get number of votes until milestone").updateDataKey("MilestoneCount"));
}
}
}
placeholders.add(new PlaceHolder<VotingPluginUser>("nextmilestone_votes_required") {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
return "" + user.getNextAvailableMileStone();
}
}.withDescription("Get number of votes required for next available milestone").updateDataKey("MilestoneCount"));
placeholders.add(new PlaceHolder<VotingPluginUser>("nextmilestone_votes_until") {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
int toGo = user.getNextAvailableMileStone() - user.getMilestoneCount();
if (toGo >= 0) {
return "" + toGo;
}
return "0";
}
}.withDescription("Get number of votes until next available milestone").updateDataKey("MilestoneCount"));
placeholders.add(new PlaceHolder<VotingPluginUser>("lastmilestone_votes_since") {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
int toGo = user.getMilestoneCount() - user.getLastGottenMilestone();
if (toGo >= 0) {
return "" + toGo;
}
return "0";
}
}.withDescription("Get number of votes since last milestone").updateDataKey("MilestoneCount"));
/*
* placeholders.add(new PlaceHolder<VotingPluginUser>("DisableReminders") {
*
* @Override public String placeholderRequest(VotingPluginUser user, String
* identifier) { if
* (plugin.getVoteReminding().getRemindersEnabled().containsKey(user.getJavaUUID
* ())) { if
* (!plugin.getVoteReminding().getRemindersEnabled().get(user.getJavaUUID()).
* booleanValue()) {
*
* return "True"; } } return "False"; }
* }.withDescription("Returns true/false if user has reminders disabled"));
*/
for (final String identifier : plugin.getShopFile().getShopIdentifiers()) {
if (plugin.getShopFile().getShopIdentifierLimit(identifier) > 0) {
@@ -516,7 +491,7 @@ public class PlaceHolders {
}
long smallest = -1;
HashMap<Long, VoteSite> times = new HashMap<>();
for (VoteSite site : plugin.getVoteSitesEnabled()) {
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
long t = user.voteNextDurationTime(site);
if (smallest == -1) {
smallest = t;
@@ -552,7 +527,7 @@ public class PlaceHolders {
}
}.withDescription("Get total number of sites available to be voted on"));
for (final VoteSite voteSite : plugin.getVoteSitesEnabled()) {
for (final VoteSite voteSite : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
placeholders.add(new CalculatingPlaceholder<VotingPluginUser>("Next_" + voteSite.getKey()) {
@Override
@@ -620,6 +595,71 @@ public class PlaceHolders {
}
}.withDescription("Return true/false if player has said points").updateDataKey("Points").useStartsWith());
// VoteMilestones placeholders (explicit per group, like
// VoteShopLimit_<identifier>)
// Base/default (no group suffix)
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneNext") {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
Long next = plugin.getVoteMilestonesManager().getNextMilestoneValue("default", user);
return next == null ? "none" : Long.toString(next);
}
}.withDescription("Next VoteMilestone value for default group").updateDataKey("LastVotes"));
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneLast") {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
Long last = plugin.getVoteMilestonesManager().getLastMilestoneValue("default", user);
return last == null ? "none" : Long.toString(last);
}
}.withDescription("Last achieved VoteMilestone value for default group").updateDataKey("LastVotes"));
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneVotesUntilNext") {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
return Long.toString(plugin.getVoteMilestonesManager().getVotesUntilNextMilestone("default", user));
}
}.withDescription("Votes until next VoteMilestone for default group").updateDataKey("LastVotes"));
Set<String> groups = new HashSet<>();
groups.add("default");
for (VoteMilestone m : plugin.getVoteMilestonesManager().getConfig().getMilestones().values()) {
String g = m.getGroupKey();
if (g == null)
continue;
g = g.trim().toLowerCase(Locale.ROOT);
if (!g.isEmpty())
groups.add(g);
}
for (final String groupIdRaw : groups) {
final String groupId = (groupIdRaw == null || groupIdRaw.trim().isEmpty()) ? "default" : groupIdRaw.trim();
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneNext_" + groupId) {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
Long next = plugin.getVoteMilestonesManager().getNextMilestoneValue(groupId, user);
return next == null ? "none" : Long.toString(next);
}
}.withDescription("Next VoteMilestone value for group " + groupId).updateDataKey("LastVotes"));
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneLast_" + groupId) {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
Long last = plugin.getVoteMilestonesManager().getLastMilestoneValue(groupId, user);
return last == null ? "none" : Long.toString(last);
}
}.withDescription("Last achieved VoteMilestone value for group " + groupId).updateDataKey("LastVotes"));
placeholders.add(new PlaceHolder<VotingPluginUser>("VoteMilestoneVotesUntilNext_" + groupId) {
@Override
public String placeholderRequest(VotingPluginUser user, String ident) {
return Long.toString(plugin.getVoteMilestonesManager().getVotesUntilNextMilestone(groupId, user));
}
}.withDescription("Votes until next VoteMilestone for group " + groupId).updateDataKey("LastVotes"));
}
nonPlayerPlaceholders.add(new NonPlayerPlaceHolder<VotingPluginUser>("Top_AllVotes_") {
@Override
@@ -1018,7 +1058,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(String identifier) {
LocalDateTime now = plugin.getTimeChecker().getTime();
LocalDateTime now = plugin.getTimeChecker().getTime().plusDays(plugin.getOptions().getTimeWeekOffSet());
LocalDateTime newWeek = plugin.getTimeChecker().getTime().withHour(0).withMinute(0);
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
@@ -1121,7 +1161,7 @@ public class PlaceHolders {
public void onChange(AdvancedCoreUser user, String... keys) {
VotingPluginUser vpUser = plugin.getVotingPluginUserManager().getVotingPluginUser(user);
if (!vpUser.isCached()) {
vpUser.dontCache();
vpUser.userDataFetechMode(UserDataFetchMode.NO_CACHE);
}
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
if (placeholder.isUsesCache()) {
@@ -1165,17 +1205,11 @@ public class PlaceHolders {
}
});
}
public void onBungeeVotePartyUpdate() {
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
* nonPlayerPlaceholders) { if (placeholder.isUsesCache()) { if
* (placeholder.getIdentifier().startsWith("BungeeVoteParty")) { for (String
* ident : placeholder.getCache().keySet()) { placeholder.getCache().put(ident,
* placeholder.placeholderRequest(ident)); } } } }
*/
}
/**
* Handle player logout.
* @param user the voting plugin user
*/
public void onLogout(VotingPluginUser user) {
if (plugin.getPlaceholders().getCacheLevel().onlineOnly()) {
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
@@ -1186,6 +1220,9 @@ public class PlaceHolders {
}
}
/**
* Update all placeholders.
*/
public void onUpdate() {
checkNonCachedPlaceholders();
for (Player p : Bukkit.getOnlinePlayers()) {
@@ -1202,6 +1239,11 @@ public class PlaceHolders {
}
/**
* Update placeholders for specific user.
* @param user the voting plugin user
* @param login whether this is a login update
*/
public void onUpdate(VotingPluginUser user, boolean login) {
for (PlaceHolder<VotingPluginUser> placeholder : placeholders) {
if (placeholder.isUsesCache()) {
@@ -1231,6 +1273,9 @@ public class PlaceHolders {
}
}
/**
* Handle vote party update.
*/
public void onVotePartyUpdate() {
/*
* for (NonPlayerPlaceHolder<VotingPluginUser> placeholder :
@@ -1241,6 +1286,9 @@ public class PlaceHolders {
*/
}
/**
* Reload placeholders.
*/
public void reload() {
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
onUpdate();
@@ -1251,6 +1299,10 @@ public class PlaceHolders {
}
}
/**
* Schedule placeholder check for user.
* @param user the voting plugin user
*/
public void schedulePlaceholderCheck(VotingPluginUser user) {
plugin.getTimer().execute(new Runnable() {
@@ -1,8 +1,25 @@
package com.bencodez.votingplugin.placeholders;
/**
* Enum for placeholder cache levels.
*/
public enum PlaceholderCacheLevel {
NONE, SPECIFIC, AUTO, AUTOALL, SPECIFICALL;
/** No caching. */
NONE,
/** Specific placeholders cached. */
SPECIFIC,
/** Auto-cache for online players. */
AUTO,
/** Auto-cache for all players. */
AUTOALL,
/** Specific cache for all players. */
SPECIFICALL;
/**
* Get cache level from string.
* @param str the string to parse
* @return the cache level
*/
public static PlaceholderCacheLevel getCache(String str) {
for (PlaceholderCacheLevel v : PlaceholderCacheLevel.values()) {
if (v.toString().equalsIgnoreCase(str)) {
@@ -12,6 +29,10 @@ public enum PlaceholderCacheLevel {
return AUTO;
}
/**
* Check if cache is for online players only.
* @return true if online only
*/
public boolean onlineOnly() {
if ((this == AUTOALL) || (this == SPECIFICALL)) {
return false;
@@ -19,6 +40,10 @@ public enum PlaceholderCacheLevel {
return true;
}
/**
* Check if caching should be enabled.
* @return true if should cache
*/
public boolean shouldCache() {
switch (this) {
case AUTO:
@@ -36,4 +61,15 @@ public enum PlaceholderCacheLevel {
}
}
/**
* Check if cache should always be used.
* @return true if cache always
*/
public boolean isCacheAlways() {
if ((this == AUTOALL) || (this == SPECIFICALL)) {
return true;
}
return false;
}
}
@@ -0,0 +1,26 @@
package com.bencodez.votingplugin.presets;
import lombok.Getter;
import lombok.Setter;
/**
* Represents display information for a preset. Display information
* includes a name and a description used to describe the preset to
* users. This class is used when parsing meta JSON files.
*/
@Getter
@Setter
public class DisplayInfo {
/**
* The human‑readable name of the preset. This name will appear in
* preset selection UIs.
*/
private String name;
/**
* A brief description of the preset. This description helps users
* understand what the preset is intended for.
*/
private String description;
}
@@ -0,0 +1,30 @@
package com.bencodez.votingplugin.presets;
import lombok.Getter;
import lombok.Setter;
/**
* Represents a fragment defined in a preset meta JSON file. A
* fragment contains the path to a YAML file and a path indicating
* where the fragment should be merged into when applying the preset.
* In the context of using only values from JSON (without YAML
* fragments), this class is unused but included for completeness.
*/
@Getter
@Setter
public class Fragment {
/**
* The relative path to the fragment file. This file typically
* contains a YAML snippet defining a portion of the configuration.
*/
private String path;
/**
* The dot‑separated path within the configuration to merge the
* fragment into. For example, {@code VoteSites} indicates the
* fragment should be merged into the {@code VoteSites} section of
* {@code VoteSites.yml}.
*/
private String mergeInto;
}
@@ -0,0 +1,199 @@
package com.bencodez.votingplugin.presets;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Utility class for loading vote site presets from GitHub.
*/
public class GitHubVoteSitePresetLoader {
private final String owner;
private final String repository;
private final String branch;
private final String token;
private final Gson gson;
/**
* Shared HTTP client.
*/
private final HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build();
public GitHubVoteSitePresetLoader(String owner, String repository, String branch) {
this(owner, repository, branch, null);
}
public GitHubVoteSitePresetLoader(String owner, String repository, String branch, String token) {
this.owner = Objects.requireNonNull(owner);
this.repository = Objects.requireNonNull(repository);
this.branch = Objects.requireNonNull(branch);
this.token = token;
this.gson = new Gson();
}
public List<String> listPresetPaths() throws IOException, InterruptedException {
String apiUrl = String.format(
"https://api.github.com/repos/%s/%s/contents/presets/votesites?ref=%s",
owner, repository, branch);
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.GET()
.timeout(Duration.ofSeconds(7))
.header("User-Agent", "VotingPlugin-PresetLoader");
if (token != null && !token.isEmpty()) {
builder.header("Authorization", "token " + token);
}
HttpResponse<String> response = httpClient.send(builder.build(),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() != 200) {
return Collections.emptyList();
}
JsonElement root = JsonParser.parseString(response.body());
if (!root.isJsonArray()) {
return Collections.emptyList();
}
JsonArray array = root.getAsJsonArray();
List<String> paths = new ArrayList<>();
for (JsonElement element : array) {
if (!element.isJsonObject()) continue;
JsonObject obj = element.getAsJsonObject();
String type = obj.has("type") ? obj.get("type").getAsString() : null;
String path = obj.has("path") ? obj.get("path").getAsString() : null;
if ("file".equals(type) && path != null && path.endsWith(".meta.json")) {
paths.add(path);
}
}
return paths;
}
public VoteSitePreset loadPreset(String path) throws IOException, InterruptedException {
Objects.requireNonNull(path, "path must not be null");
String rawUrl = String.format(
"https://raw.githubusercontent.com/%s/%s/%s/%s",
owner, repository, branch, path);
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(rawUrl))
.GET()
.timeout(Duration.ofSeconds(7))
.header("User-Agent", "VotingPlugin-PresetLoader");
if (token != null && !token.isEmpty()) {
builder.header("Authorization", "token " + token);
}
HttpResponse<String> response = httpClient.send(builder.build(),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() != 200) {
return null;
}
try (Reader reader = new InputStreamReader(
new java.io.ByteArrayInputStream(response.body().getBytes(StandardCharsets.UTF_8)),
StandardCharsets.UTF_8)) {
return gson.fromJson(reader, VoteSitePreset.class);
}
}
public List<VoteSitePreset> listAllVoteSitePresets() throws IOException, InterruptedException {
List<String> paths = listPresetPaths();
if (paths.isEmpty()) {
return Collections.emptyList();
}
List<VoteSitePreset> result = new ArrayList<>();
for (String path : paths) {
try {
VoteSitePreset preset = loadPreset(path);
if (preset != null) {
result.add(preset);
}
} catch (Exception ignored) {
}
}
return result;
}
public VoteSitePreset findVoteSitePresetForURL(String voteURL) throws IOException, InterruptedException {
if (voteURL == null || voteURL.trim().isEmpty()) {
return null;
}
String host;
try {
java.net.URI uri = new java.net.URI(voteURL.trim());
host = uri.getHost();
} catch (Exception e) {
return null;
}
if (host == null || host.isEmpty()) {
return null;
}
host = host.toLowerCase();
if (host.startsWith("www.")) {
host = host.substring(4);
}
List<VoteSitePreset> presets = listAllVoteSitePresets();
for (VoteSitePreset preset : presets) {
if (preset == null || preset.getMatch() == null || preset.getMatch().getDomains() == null) {
continue;
}
for (String domain : preset.getMatch().getDomains()) {
if (domain == null || domain.isEmpty()) {
continue;
}
String normalizedDomain = domain.toLowerCase();
if (normalizedDomain.startsWith("www.")) {
normalizedDomain = normalizedDomain.substring(4);
}
if (host.equals(normalizedDomain) || host.endsWith("." + normalizedDomain)) {
return preset;
}
}
}
return null;
}
}
@@ -0,0 +1,28 @@
package com.bencodez.votingplugin.presets;
import lombok.Getter;
import lombok.Setter;
/**
* Represents matching information for a preset. Match information
* identifies which domains or keywords should match this preset. This
* class is used for deserializing preset meta JSON files but is
* otherwise optional when programmatically applying the preset.
*/
@Getter
@Setter
public class MatchInfo {
/**
* Domains associated with the preset. These are used by the preset
* generator to automatically select a preset based on a vote site
* hostname.
*/
private java.util.List<String> domains;
/**
* Keywords associated with the preset. These can be used to search
* presets in user interfaces.
*/
private java.util.List<String> keywords;
}
@@ -0,0 +1,46 @@
package com.bencodez.votingplugin.presets;
import lombok.Getter;
import lombok.Setter;
import com.google.gson.annotations.SerializedName;
/**
* Represents a placeholder definition loaded from a preset meta JSON file.
*
* The VotingPlugin presets define a set of placeholders that may be
* substituted when creating vote site entries. Each placeholder has a
* type (for example, {@code string}), a human‑readable label, and a
* default value. This class is a simple container for these fields so
* they can be deserialized via Gson and accessed via Lombok‑generated
* getters and setters.
*/
@Getter
@Setter
public class PlaceholderDef {
/**
* The data type of this placeholder (e.g. {@code string}). The type
* information is primarily for user interfaces and may be ignored when
* programmatically applying the preset.
*/
private String type;
/**
* A human‑readable label describing the placeholder. This is used by
* external tools (such as the web preset generator) to prompt for
* values.
*/
private String label;
/**
* The default value for the placeholder. If the user does not supply a
* value when applying the preset, this value will be used instead.
* <p>
* The JSON meta files use the key {@code "default"} for this value. Because
* {@code default} is a reserved keyword in Java, we cannot name this
* field {@code default}. Instead, we annotate this field with
* {@link SerializedName @SerializedName("default")} so that Gson
* will map the {@code "default"} property in the JSON to this field.
*/
@SerializedName("default")
private String defaultValue;
}
@@ -0,0 +1,234 @@
package com.bencodez.votingplugin.presets;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.config.ConfigVoteSites;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Manager responsible for loading vote site presets defined in JSON and
* applying them to the VotingPlugin configuration. Unlike the web preset
* generator, this manager ignores YAML fragments and relies solely on values
* defined in the meta JSON file.
*/
public class VoteSiteJsonPresetManager {
/**
* The main plugin instance used to access the configuration.
*/
private final VotingPluginMain plugin;
/**
* Cached reference to the vote sites configuration helper.
*/
private final ConfigVoteSites configVoteSites;
/**
* Constructs a new manager for applying vote site presets.
*
* @param plugin the main plugin instance
*/
public VoteSiteJsonPresetManager(VotingPluginMain plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin must not be null");
this.configVoteSites = plugin.getConfigVoteSites();
}
/**
* Loads a vote site preset from the specified resource path.
*
* @param resourcePath the path to the meta JSON file within the JAR
* @return the deserialized preset
* @throws IOException if the resource cannot be read or parsed
*/
public VoteSitePreset loadPreset(String resourcePath) throws IOException {
InputStream in = plugin.getResource(resourcePath);
if (in == null) {
throw new IOException("Preset resource not found: " + resourcePath);
}
try (Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
Gson gson = new GsonBuilder().create();
return gson.fromJson(reader, VoteSitePreset.class);
}
}
/**
* Applies the given vote site preset to the VotingPlugin configuration.
* Placeholder values will be populated using the defaults defined in the
* preset and overridden by any values provided in the {@code overrides} map.
*
* @param preset the preset to apply
* @param overrides a map of placeholder names to override values
*/
public void applyPreset(VoteSitePreset preset, Map<String, Object> overrides) {
if (preset == null) {
return;
}
Map<String, Object> values = new HashMap<String, Object>();
if (preset.getPlaceholders() != null) {
for (Map.Entry<String, PlaceholderDef> entry : preset.getPlaceholders().entrySet()) {
PlaceholderDef def = entry.getValue();
if ((def != null) && (def.getDefaultValue() != null)) {
values.put(entry.getKey(), def.getDefaultValue());
}
}
}
if (overrides != null) {
for (Map.Entry<String, Object> entry : overrides.entrySet()) {
if (entry.getValue() != null) {
values.put(entry.getKey(), entry.getValue());
}
}
}
String siteKey = getString(values.get("siteKey")).trim();
String displayName = getString(values.get("displayName"));
String serviceSite = getString(values.get("serviceSite"));
String voteURL = getString(values.get("voteURL"));
String voteDelay = getString(values.get("voteDelay"));
Boolean waitUntilDelay = getBoolean(values.get("WaitUnitVoteDelay"));
if (waitUntilDelay == null) {
waitUntilDelay = getBoolean(values.get("waitUntilVoteDelay"));
}
Boolean voteDelayDaily = getBoolean(values.get("VoteDelayDaily"));
if (voteDelayDaily == null) {
voteDelayDaily = getBoolean(values.get("voteDelayDaily"));
}
Integer voteDelayDailyHour = getInteger(values.get("voteDelayDailyHour"));
if (voteDelayDailyHour == null) {
voteDelayDailyHour = getInteger(values.get("VoteDelayDailyHour"));
}
if (siteKey.isEmpty()) {
plugin.getLogger().warning("Cannot apply preset: siteKey is missing");
return;
}
configVoteSites.setEnabled(siteKey, true);
if (!displayName.isEmpty()) {
configVoteSites.setDisplayName(siteKey, displayName);
}
if (!serviceSite.isEmpty()) {
configVoteSites.setServiceSite(siteKey, serviceSite);
}
if (!voteURL.isEmpty()) {
configVoteSites.setVoteURL(siteKey, voteURL);
}
if (!voteDelay.isEmpty()) {
configVoteSites.setVoteDelay(siteKey, voteDelay);
}
if (waitUntilDelay != null) {
configVoteSites.set(siteKey, "WaitUntilVoteDelay", waitUntilDelay.booleanValue());
}
if (voteDelayDaily != null) {
configVoteSites.setVoteDelayDaily(siteKey, voteDelayDaily.booleanValue());
}
if (voteDelayDailyHour != null) {
configVoteSites.setVoteDelayDailyHour(siteKey, voteDelayDailyHour.intValue());
}
if (configVoteSites.getItem(siteKey) == null) {
configVoteSites.set(siteKey, "DisplayItem.Material", "STONE");
configVoteSites.set(siteKey, "DisplayItem.Amount", 1);
}
if (configVoteSites.getData(siteKey).getConfigurationSection("Rewards") == null) {
configVoteSites.set(siteKey, "Rewards.Messages.Player", "&aThanks for voting on %ServiceSite%!");
}
configVoteSites.saveData();
plugin.loadVoteSites();
}
/**
* Converts an object to a string.
*
* @param value the value
* @return the string form, or an empty string if null
*/
private String getString(Object value) {
return value != null ? String.valueOf(value) : "";
}
/**
* Converts an object to a boolean if possible.
*
* @param value the value
* @return the parsed boolean, or null if not set
*/
private Boolean getBoolean(Object value) {
if (value == null) {
return null;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
String text = String.valueOf(value).trim().toLowerCase();
if (text.isEmpty()) {
return null;
}
if (text.equals("true") || text.equals("yes") || text.equals("1")) {
return Boolean.TRUE;
}
if (text.equals("false") || text.equals("no") || text.equals("0")) {
return Boolean.FALSE;
}
return null;
}
/**
* Converts an object to an integer if possible.
*
* @param value the value
* @return the parsed integer, or null if not set or invalid
*/
private Integer getInteger(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return Integer.valueOf(((Number) value).intValue());
}
String text = String.valueOf(value).trim();
if (text.isEmpty()) {
return null;
}
try {
return Integer.valueOf(Integer.parseInt(text));
} catch (NumberFormatException e) {
plugin.getLogger().warning("Invalid integer value: " + text);
return null;
}
}
}
@@ -0,0 +1,62 @@
package com.bencodez.votingplugin.presets;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
import java.util.List;
/**
* Represents a vote site preset as defined in a meta JSON file.
*
* The meta JSON file defines metadata about the preset such as display
* information, matching criteria, placeholder definitions and optional YAML
* fragments. This class provides a simple POJO for deserialization via
* Gson. Only the {@code placeholders} field is strictly necessary when
* applying the preset programmatically; the other fields are included
* for completeness.
*/
@Getter
@Setter
public class VoteSitePreset {
/**
* The schema version of the preset definition. This may be used to
* handle future format changes.
*/
private int schemaVersion;
/**
* The unique identifier of the preset (e.g. {@code votesite:generic}).
*/
private String id;
/**
* Human‑friendly display information for the preset.
*/
private DisplayInfo display;
/**
* Matching information that can be used to automatically select a
* preset based on domain or keywords. Optional when applying
* programmatically.
*/
private MatchInfo match;
/**
* Definitions of placeholders used by this preset. Each entry in
* the map corresponds to a placeholder name and defines its type,
* label and default value.
*/
private Map<String, PlaceholderDef> placeholders;
/**
* A list of YAML fragments referenced by this preset. When not using
* YAML, this field is unused but retained for completeness.
*/
private List<Fragment> fragments;
/**
* Whether the preset has been verified by the project maintainers.
*/
private boolean verified;
}
@@ -0,0 +1,210 @@
package com.bencodez.votingplugin.presets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.bukkit.entity.Player;
import com.bencodez.simpleapi.valuerequest.MultiValueField;
import com.bencodez.simpleapi.valuerequest.MultiValueField.FieldType;
import com.bencodez.simpleapi.valuerequest.MultiValueListener;
import com.bencodez.simpleapi.valuerequest.MultiValueResult;
import com.bencodez.simpleapi.valuerequest.StringListener;
import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.votingplugin.VotingPluginMain;
import lombok.Getter;
/**
* Handler class that guides a player through selecting a vote site preset and
* configuring its placeholder values using the SimpleAPI {@link ValueRequest}
* system.
*/
public class VoteSitePresetSetupHandler {
/**
* Main plugin instance.
*/
private final VotingPluginMain plugin;
/**
* Loader used to fetch vote site presets.
*/
@Getter
private final GitHubVoteSitePresetLoader loader;
/**
* Creates a new setup handler.
*
* @param plugin plugin instance
*/
public VoteSitePresetSetupHandler(VotingPluginMain plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin must not be null");
this.loader = new GitHubVoteSitePresetLoader("BenCodez", "VotingPlugin-Presets", "main");
}
/**
* Starts the preset setup process.
*
* @param player player running setup
*/
public void startSetup(Player player) {
List<VoteSitePreset> presets;
try {
presets = loader.listAllVoteSitePresets();
} catch (Exception e) {
player.sendMessage("§cUnable to load vote site presets.");
plugin.getLogger().warning("Failed to load vote site presets: " + e.getMessage());
return;
}
if (presets == null || presets.isEmpty()) {
player.sendMessage("§cNo vote site presets are available.");
return;
}
List<String> options = new ArrayList<String>();
for (VoteSitePreset preset : presets) {
options.add(preset.getId());
}
ValueRequest request = new ValueRequest(plugin, plugin.getDialogService());
request.requestString(player, null, options, false, "Select a vote site preset", new StringListener() {
@Override
public void onInput(Player p, String value) {
VoteSitePreset selected = null;
for (VoteSitePreset preset : presets) {
if (preset.getId() != null && preset.getId().equalsIgnoreCase(value)) {
selected = preset;
break;
}
}
if (selected == null) {
p.sendMessage("§cInvalid preset: " + value);
return;
}
promptPlaceholders(p, selected);
}
});
}
/**
* Prompts placeholder values using the multi-value request system.
*
* @param player player
* @param preset preset
*/
public void promptPlaceholders(Player player, VoteSitePreset preset) {
Map<String, PlaceholderDef> defs = preset.getPlaceholders();
if (defs == null || defs.isEmpty()) {
new VoteSiteJsonPresetManager(plugin).applyPreset(preset, new HashMap<String, Object>());
player.sendMessage("§aPreset applied successfully.");
return;
}
List<MultiValueField> fields = new ArrayList<MultiValueField>();
List<String> keys = new ArrayList<String>();
for (Map.Entry<String, PlaceholderDef> entry : defs.entrySet()) {
String key = entry.getKey();
if (key == null) {
continue;
}
// skip auto values
if (key.equalsIgnoreCase("siteKey") || key.equalsIgnoreCase("serviceSite")) {
continue;
}
PlaceholderDef def = entry.getValue();
String label = def != null && def.getLabel() != null ? def.getLabel() : key;
String defaultValue = def != null && def.getDefaultValue() != null ? def.getDefaultValue() : "";
MultiValueField field = createField(key, label, defaultValue);
fields.add(field);
keys.add(key);
}
if (fields.isEmpty()) {
new VoteSiteJsonPresetManager(plugin).applyPreset(preset, new HashMap<String, Object>());
player.sendMessage("§aPreset applied successfully.");
return;
}
ValueRequest request = new ValueRequest(plugin, plugin.getDialogService());
request.requestMultipleValues(player, fields, new MultiValueListener() {
@Override
public void onInput(Player p, MultiValueResult result) {
Map<String, Object> overrides = new HashMap<String, Object>();
for (String key : keys) {
if (isBooleanField(key)) {
Boolean value = result.getBoolean(key);
overrides.put(key, value != null ? value : Boolean.FALSE);
} else {
String value = result.getString(key);
overrides.put(key, value != null ? value : "");
}
}
new VoteSiteJsonPresetManager(plugin).applyPreset(preset, overrides);
p.sendMessage("§aVote site configured and preset applied.");
}
});
}
/**
* Creates a field based on placeholder key.
*
* @param key key
* @param label label
* @param defaultValue default value
* @return field
*/
private MultiValueField createField(String key, String label, String defaultValue) {
if (isBooleanField(key)) {
boolean boolValue = Boolean.parseBoolean(defaultValue);
return new MultiValueField(key, label + " (default: " + boolValue + ")", FieldType.BOOLEAN)
.booleanValue(Boolean.valueOf(boolValue))
.required(false);
}
return new MultiValueField(key, label + " (default: " + defaultValue + ")", FieldType.STRING)
.stringValue(defaultValue)
.required(true);
}
/**
* Determines if the placeholder should be treated as a boolean.
*
* @param key placeholder key
* @return true if boolean field
*/
private boolean isBooleanField(String key) {
return key.equalsIgnoreCase("WaitUntilVoteDelay")
|| key.equalsIgnoreCase("VoteDelayDaily");
}
}
@@ -1,79 +0,0 @@
package com.bencodez.votingplugin.proxy;
import java.util.regex.Pattern;
import lombok.Getter;
import lombok.Setter;
public class BungeeMessageData {
// Message string
// alltimetotal//monthtotal//weeklytotal//dailytotal//points//milestonecount//votepartycurrent//votepartyrequired//datemonthtotal
@Getter
@Setter
private int allTimeTotal = 0;
@Getter
@Setter
private int dailyTotal = 0;
@Getter
@Setter
private int milestoneCount = 0;
@Getter
@Setter
private int monthTotal = 0;
@Getter
@Setter
private int dateMonthTotal = 0;
@Getter
@Setter
private int points = 0;
@Getter
@Setter
private int weeklyTotal = 0;
@Getter
@Setter
private int votePartyCurrent = 0;
@Getter
@Setter
private int votePartyRequired = 0;
public BungeeMessageData(int allTimeTotal, int monthTotal, int weeklyTotal, int dailyTotal, int points,
int milestoneCount, int votePartyCurrent, int votePartyRequired, int dateMonthTotal) {
this.allTimeTotal = allTimeTotal;
this.monthTotal = monthTotal;
this.weeklyTotal = weeklyTotal;
this.dailyTotal = dailyTotal;
this.points = points;
this.milestoneCount = milestoneCount;
this.votePartyCurrent = votePartyCurrent;
this.votePartyRequired = votePartyRequired;
this.dateMonthTotal = dateMonthTotal;
}
public BungeeMessageData(String str) {
String[] data = str.split(Pattern.quote("//"));
if (data.length >= 6) {
allTimeTotal = Integer.parseInt(data[0]);
monthTotal = Integer.parseInt(data[1]);
weeklyTotal = Integer.parseInt(data[2]);
dailyTotal = Integer.parseInt(data[3]);
points = Integer.parseInt(data[4]);
milestoneCount = Integer.parseInt(data[5]);
}
if (data.length >= 8) {
votePartyCurrent = Integer.parseInt(data[6]);
votePartyRequired = Integer.parseInt(data[7]);
}
if (data.length >= 9) {
dateMonthTotal = Integer.parseInt(data[8]);
}
}
@Override
public String toString() {
return allTimeTotal + "//" + monthTotal + "//" + weeklyTotal + "//" + dailyTotal + "//" + points + "//"
+ milestoneCount + "//" + votePartyCurrent + "//" + votePartyRequired;
}
}
@@ -1,12 +1,35 @@
package com.bencodez.votingplugin.proxy;
/**
* Enumeration of available Bungee connection methods.
*/
public enum BungeeMethod {
MYSQL, PLUGINMESSAGING, SOCKETS, REDIS, MQTT;
/** MySQL database connection. */
MYSQL,
/** Plugin messaging channel. */
PLUGINMESSAGING,
/** Socket connection. */
SOCKETS,
/** Redis connection. */
REDIS,
/** MQTT message broker. */
MQTT;
/**
* Checks if this method requires a player to be online.
*
* @return true if player must be online
*/
public boolean requiresPlayerOnline() {
return this == MYSQL || this == PLUGINMESSAGING;
return this == PLUGINMESSAGING;
}
/**
* Gets a BungeeMethod by name.
*
* @param str the method name
* @return the matching BungeeMethod, or PLUGINMESSAGING if not found
*/
public static BungeeMethod getByName(String str) {
for (BungeeMethod method : values()) {
if (method.toString().equalsIgnoreCase(str)) {
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff. Show more