From 2f871b33971536ddd031a90ad1aca6f585eea099 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 12 Sep 2015 18:40:54 -0700 Subject: [PATCH] Ported over from ASkyBlock. --- WelcomeWarps/config.yml | 3 + WelcomeWarps/locale/locale.yml | 467 ++++++++++++++++++ WelcomeWarps/plugin.yml | 10 +- .../welcomewarpsigns/Metrics.java | 226 --------- .../welcomewarpsigns/Settings.java | 13 - .../welcomewarpsigns/WAdmin.java | 85 ---- .../welcomewarpsigns/WWarpCmd.java | 103 ---- .../welcomewarpsigns/WarpSignsListener.java | 183 ------- .../welcomewarpsigns/WelcomeWarpSigns.java | 460 ----------------- .../src/com/wasteofplastic/wwarps/Locale.java | 233 +++++++++ .../com/wasteofplastic/wwarps/Messages.java | 148 ++++++ .../com/wasteofplastic/wwarps/Settings.java | 39 ++ .../src/com/wasteofplastic/wwarps/WWarps.java | 257 ++++++++++ .../com/wasteofplastic/wwarps/WarpSigns.java | 369 ++++++++++++++ .../wwarps/commands/AdminCmd.java | 76 +++ .../wwarps/commands/WarpCmd.java | 282 +++++++++++ .../wwarps/listeners/JoinLeaveEvents.java | 67 +++ .../wasteofplastic/wwarps/panels/CPItem.java | 115 +++++ .../wwarps/panels/WarpPanel.java | 179 +++++++ .../com/wasteofplastic/wwarps/util/Util.java | 269 ++++++++++ 20 files changed, 2509 insertions(+), 1075 deletions(-) create mode 100644 WelcomeWarps/locale/locale.yml delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Metrics.java delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Settings.java delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WAdmin.java delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WWarpCmd.java delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WarpSignsListener.java delete mode 100644 WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WelcomeWarpSigns.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/Locale.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/Messages.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/Settings.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/WWarps.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/WarpSigns.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/commands/AdminCmd.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/commands/WarpCmd.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/listeners/JoinLeaveEvents.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/panels/CPItem.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/panels/WarpPanel.java create mode 100644 WelcomeWarps/src/com/wasteofplastic/wwarps/util/Util.java diff --git a/WelcomeWarps/config.yml b/WelcomeWarps/config.yml index 5f0092b..9b3d17f 100644 --- a/WelcomeWarps/config.yml +++ b/WelcomeWarps/config.yml @@ -1,3 +1,6 @@ +# Use the GUI warp panel, if false, warps will be listed as text +usewarppanel: true + # Sign worlds - a list of worlds where Welcome Warp Signs work. If this is blank, then they will work in all worlds. Worlds must be correctly capitalized. # Example - # signworlds: diff --git a/WelcomeWarps/locale/locale.yml b/WelcomeWarps/locale/locale.yml new file mode 100644 index 0000000..44b649e --- /dev/null +++ b/WelcomeWarps/locale/locale.yml @@ -0,0 +1,467 @@ +########################################################################################### +# This is a YML file. Be careful when editing. Check your edits in a YAML checker like # +# the one at http://yaml-online-parser.appspot.com # +# If this file is deleted, then it will be recreate at the next reload. # +########################################################################################### + +--- +acidBottle: "Acid Bottle" +acidBucket: "Acid Bucket" +acidLore: | + Do + not drink! + Beware! +adminDeleteIsland: + error: "Use &ldeleteisland confirm &r&cto delete the island you are on." + noid: "Cannot identify island." + use: "Use &ldelete [name] &r&cto delete the player instead." +adminHelp: + add: "adds player to leader's team" + clearreset: "resets the island reset limit for player" + completeChallenge: "marks a challenge as complete" + delete: "delete an island (removes blocks)." + help: "Admin Commands:" + info: "info for the given player" + infoisland: "provide info on the nearest island" + kick: "removes player from any team" + lock: "locks/unlocks player's island" + purge: "delete inactive islands older than [TimeInDays]." + purgeallowdisallow: "allow/disallow island to be purged if it meets purge criteria" + purgeholes: "free up island holes for reuse" + purgeunowned: "remove unowned islands" + register: "set a player's island to your location" + reload: "reload configuration from file." + resetAllChallenges: "resets all of the player's challenges" + resetChallenge: "marks a challenge as incomplete" + resetsign: "Resets the sign you are looking at to the island owner" + setbiome: "sets leader's island biome" + setrange: "changes the island's protection range" + setspawn: "sets the island world spawn to a location close to you" + teamChatSpy: "Spy on team chats (on/off)" + topTen: "manually update the top 10 list" + topbreeders: "lists most populated islands currently loaded" + tp: "Teleport to a player's island" + tpnether: "Teleport to a player's nether island" + unregister: "deletes a player without deleting the island blocks" +adminInfo: + bannedPlayers: "Banned players" + hoppers: "Island has [number] hoppers" + isLocked: "Island is locked" + isProtected: "Island is purge protected" + isSpawn: "Island is spawn" + isUnlocked: "Island is unlocked" + isUnprotected: "Island is not purge protected" + lastLogin: "Last login" + maxSize: "Island max size (distance)" + player: "Player" + teamLeader: "Team Leader" + teamMembers: "Team Members" + title: "This is spawn island" + unowned: "This island is not owned by anyone right now." +adminLock: + adminLockedIsland: "Admin locked your island" + adminUnlockedIsland: "Admin unlocked your island" + errorInGame: "Must use command in-game while on an island!" +adminRegister: + hadIsland: "[name] had an island at [location]" + leadsTeam: "[name] leads a team. Kick players from it first." + noIsland: "There is no known island in this area!" + notSpawn: "You cannot take ownership of spawn!" + taking: "Taking ownership away from [name]" +adminResetSign: + errorExists: "That warp sign is already active and owned by [name]" + found: "Warp sign found!" + noSign: "You must be looking at a sign post to run this command." + rescued: "Warp sign rescued and assigned to [name]" +adminSetHome: + homeSet: "Home set to [location]" + noneFound: "No safe location found!" + notOnPlayersIsland: "You are not on the player's island" + notSafe: "That location is not safe" +adminSetRange: + invalid: "Invalid range!" + set: "Set new range to [number]" + tip: "Use 10 to [max]" + warning: "Warning - range is greater than island range [max]" + warning2: "Overlapped islands will act like spawn!" +adminSetSpawn: + center: "Island center [location]" + coords: "Protection coords [min] to [max]" + limits: "Island limits [min] to [max]" + locked: "Spawn is locked!" + move: "Move further away or unregister the owner." + ownedBy: "This island space is owned by [name]" + range: "Protection range = [number]" + set: "Set island spawn to your location." + setting: "Setting island spawn to your location [location]" +adminTeam: + addLeaderNoIsland: "Team leader does not have their own island so cannot have a team!" + addLeaderToOwn: "Cannot add a leader to their own team." + addedLeader: "Added the leader to this team!" + addingPlayer: "Adding player to team." + alreadyOnTeam: "Player was already on this team!" + kickLeader: "That player is a team leader. Remove team members first. Use '/[label] info [name]' to find team members." + nowUnowned: "[name] had an island at [location] that will become unowned now. You may want to delete it manually." + settingHome: "Setting player's home to the leader's home location" +adminTopBreeders: + checking: "Checking [number] islands..." + finding: "Finding top breeders..." + nothing: "No creatures found." +adminTopTen: + finished: "Finished generation of the Top Ten list" + generating: "Generating the Top Ten list" +adminTp: + manualWarp: "No safe spot found. Manually warp to somewhere near [location]." +adminUnregister: + keepBlocks: "Removing player from world, but keeping island at [location]" + onTeam: "Player is in a team - disband it first." +ban: + alreadybanned: "[name] is already banned!" + banned: "You are banned from [name]'s island!" + fail: "[name] cannot be banned!" + helpBan: "ban a player from your island." + helpUnban: "un-ban a player from your island" + lifted: "Ban lifted from [name]'s island!" + liftedsuccess: "Ban lifted for [name]!" + notbanned: "[name] is not banned!" + notteammember: "You cannot ban a team member!" + notyourself: "You cannot do that to yourself!" + success: "[name] is banned from the island!" +biome: + help: "open the biomes GUI." + paneltitle: "Select A Biome" + set: "Island biome set to [biome]!" + unknown: "Unknown biome!" + youbought: "Purchased for [cost]!" +boats: + warning: "It's unsafe to exit the boat right now..." +challenges: + colors: "Challenges will have different colors depending on if they are:" + complete: "Complete" + completeNotRepeatable: "Completed(not repeatable)" + completeRepeatable: "Completed(repeatable)" + completedtimes: "Completed [donetimes] out of [maxtimes]" + errorIslandLevel: "Your island must be level [level] to complete this challenge!" + errorItemsNotThere: "All required items must be close to you on your island!" + errorNotCloseEnough: "You must be standing within 10 blocks of all required items." + errorNotEnoughItems: "You do not have enough required item(s)" + errorNotOnIsland: "You must be on your island to do that!" + errorRewardProblem: "There was a problem giving your reward. Ask Admin to check log!" + erroryouaremissing: "You are missing" + expReward: "Exp reward" + firstTimeRewards: "First time reward(s)" + guititle: "aSkyBlock Challenges" + help1: "Use /c to view information about a challenge." + help2: "Use /c complete to attempt to complete that challenge." + incomplete: "Incomplete" + invalidChallengeName: "Invalid challenge name! Use /c help for more information" + itemTakeWarning: "All required items are taken when you complete this challenge!" + level: "Level" + maxreached: "Max reached [donetimes] out of [maxtimes]" + moneyReward: "Money reward" + name: "Challenge Name" + nameHasCompleted: "[name] has completed the [challenge] challenge!" + notRepeatable: "This Challenge is not repeatable!" + repeatRewards: "Repeat reward(s)" + rewards: "Reward(s)" + toComplete: "Complete [challengesToDo] more [thisLevel] challenges to unlock this level!" + toCompleteUse: "To complete this challenge, use" + unknownChallenge: "Unknown challenge name (check spelling)!" + youHaveCompleted: "You have completed the [challenge] challenge!" + youHaveNotUnlocked: "You have not unlocked this challenge yet!" + youRepeated: "You repeated the [challenge] challenge!" +changingObsidiantoLava: "Changing obsidian back into lava. Be careful!" +checkteam: + checkingTeam: "Checking Team of [name]" +completechallenge: + challangeCompleted: "Challenge: [challengename] has been completed for [name]" + errorChallengeDoesNotExist: "Challenge doesn't exist or is already completed" +confirm: + errorTimeLimitExpired: "Time limit expired! Issue command again." +coop: + help: "temporarily give a player full access to your island" + invited: "[name] made [player] a coop player!" + madeyoucoopy: "[name] made you a coop player!" + notincoop: "[name] is not in your coop!" + onyourteam: "Player is already on your team!" + removed: "[name] removed your coop status!" + removesuccess: "[name] is no longer a coop player." + success: "[name] is now a coop player until they log out or you uncoop or expel them." + uncoop: "remove full island access from player" + useexpel: "Use expel or uncoop to remove." +delete: + removing: "Removing [name]'s island." +drankAcid: "drank acid." +drankAcidAndDied: "just drank acid and died." +error: + commandNotReady: "You can't use that command right now." + noIsland: "You do not have an island!" + noIslandOther: "That player does not have an island!" + noPermission: "You don't have permission to use that command!" + noTeam: "Player is not in a team." + notOnIsland: "You are not in an island space!" + maxIslands: "The world is full of islands! Try again later!" + offlinePlayer: "That player is offline or doesn't exist." + unknownCommand: "Unknown command." + unknownPlayer: "That player is unknown." + useInGame: "This command must be used in-game." + wrongWorld: "You cannot do that in this world." +expel: + expelled: "You were expelled from that island!" + fail: "[name] cannot be expelled!" + notonisland: "Player is not trespassing on your island!" + notyourself: "You cannot expel yourself!" + success: "You expelled [name]!" +invite: + errorCantJoinIsland: "You couldn't join the island, maybe it's full." + errorCoolDown: "You can invite that player again in [time] minutes" + errorThatPlayerIsAlreadyInATeam: "That player is already in a team." + errorYouCannotInviteYourself: "You can not invite yourself!" + errorYouMustHaveIslandToInvite: "You must have an island in order to invite people to it!" + errorYourIslandIsFull: "Your island is full, you can't invite anyone else." + hasJoinedYourIsland: "[name] has joined your island!" + help: "Use [/island invite ] to invite a player to your island." + inviteSentTo: "Invite sent to [name]" + nameHasInvitedYou: "[name] has invited you to join their island!" + onlyIslandOwnerCanInvite: "Only the leader can invite!" + removingInvite: "Removing your previous invite." + toAcceptOrReject: "to accept or reject the invite." + warningYouWillLoseIsland: "WARNING: You will lose your current island if you accept!" + youCanInvite: "You can invite [number] more players." + youCannotInvite: "You can't invite any more players." + youHaveJoinedAnIsland: "You have joined an island! Use /island team to see the other members." +island: + cannotTeleport: "You cannot teleport when falling!" + donate: "Welcome to A SkyBlock by tastybento" + errorCouldNotCreateIsland: "Could not create your Island. Please contact a server moderator." + errorInvalidPlayer: "That player is invalid or does not have an island!" + errorLevelNotReady: "Can't use that command right now! Try again in a few seconds." + errorYouDoNotHavePermission: "You do not have permission to use that command!" + helpAcceptReject: "accept or reject an invitation." + helpChallenges: "/challenges: &fshow challenges" + helpColor: "&e" + helpControlPanel: "open the island GUI." + helpExpel: "force a player from your island." + helpInvite: "invite a player to join your island." + helpIsland: "start an island, or teleport to your island." + helpIslandSpawn: "go to spawn." + helpKick: "remove a team player from your island." + helpLeave: "leave another player's island." + helpLevel: "calculate your island level" + helpLevelPlayer: "see another player's island level." + helpLock: "Locks island so visitors cannot enter it" + helpMakeLeader: "transfer the island to ." + helpRestart: "restart your island and remove the old one." + helpSetHome: "set your teleport point for /island." + helpSettings: "see island protection and game settings" + helpTeam: "view your team information." + helpTeleport: "teleport to your island." + helpTop: "see the top ranked islands." + helpWarp: "Warp to 's welcome sign." + helpWarps: "Lists all available welcome-sign warps." + islandDeletedLifeboats: "Island deleted! Head to the lifeboats!" + islandLevelis: "Island level is" + new: "Creating a new island for you..." + resetConfirm: "Type /island confirm within [seconds] seconds to delete your island and restart!" + resetMustRemovePlayers: "You must remove all players from your island before you can restart it (/island kick ). See a list of players currently part of your island using /island team." + resetNoMore: "No more resets are allowed for your island!" + resetOnlyOwner: "Only the owner may restart this island. Leave this island in order to start your own (/island leave)." + resetPleaseWait: "Please wait, generating new island" + resetTo: "Cleared reset limit" + resetWait: "You have to wait [time] seconds before you can do that again." + resetYouHave: "You have [number] resets left." + subtitle: "by tastybento" + teleport: "Teleporting you to your island. (/island help for more info)" + title: "A SkyBlock" + url: "" +islandProtected: "Island protected." +islandguardsettings: + TNTdamage: "TNT Damage" + allowed: "Allowed" + anvil: "Anvil use" + armorstand: "Armor Stand use" + beacon: "Beacon use" + bed: "Bed use" + breakblocks: "Break blocks" + breeding: "Breeding" + brewingstand: "Potion Brewing" + bucket: "Bucket use" + chest: "Chest use" + chestdamage: "Chest damage by TNT" + creeperdamage: "Creeper damage" + creepergriefing: "Creeper griefing" + croptrample: "Crop trampling" + disallowed: Disallowed + door: "Door use" + enchantingtable: "Enchanting table use" + enderpearl: "Enderpearl use" + fire: "Fire" + furnace: "Furnace use" + gate: "Gate use" + horseinventoryaccess: "Visitor horse inventory access" + horseriding: "Visitor horse riding" + hurtanimals: "Hurting animals" + hurtmonsters: "Hurting monsters" + jukebox: "Jukebox use" + leash: "Leash use" + lever: "Lever or Button Use" + netherpvp: "Nether PvP" + placeblocks: "Place blocks" + portaluse: "Portal use" + pressureplate: "Visitors activate pressure plates" + pvp: "PvP" + redstone: "Redstone use" + settingsgeneraltitle: "General Island World Settings" + settingsgeneraldesc: "General Island World Settings" + settingsislandtitle: "Island Settings" + settingsislanddesc: "These rules apply to visitors on this island" + settingsspawntitle: "Spawn Settings" + settingsspawndesc: "These rules apply at spawn" + shears: "Shears use" + spawnegg: "Spawn egg use" + teleportwhenfalling: "Teleport when falling" + title: "Island Guard Settings" + visitordrop: "Visitor item dropping" + visitorkeepitems: "Visitor keep item on death" + visitorpickup: "Visitor item pick-up" + withergriefing: "Wither griefing" + workbench: "Workbench use" +kick: + errorNoTeam: "You do not have a team!" + errorNotPartOfTeam: "That player is not part of your island team!" + errorOnlyLeaderCan: "Only the leader can kick people off the island!" + errorPlayerNotInTeam: "That player is not in your team!" + nameRemoved: "[name] has been removed from the island." + nameRemovedYou: "[name] has removed you from their island!" +lavaTip: "Tip: If obsidian was not intended, it can be scooped back up again with a bucket." +leave: + errorLeadersCannotLeave: "Leaders cannot leave an island. Make someone else the leader first." + errorYouAreTheLeader: "You cannot leave because you are the leader. Make someone the leader first." + errorYouCannotLeaveIsland: "You can't leave your island if you are the only person. Try restart if you want a new one!" + errorYouMustBeInWorld: "You must be in the island world to leave your team!" + nameHasLeftYourIsland: "[name] has left your island!" + youHaveLeftTheIsland: "You have left the island and returned to the player spawn." +level: + calculating: "Calculating island level. This will take a few seconds..." + errornotYourIsland: "Only the leader can do that." + islandLevel: "Island level" +lock: + enteringspawn: "Entering Spawn" + islandlocked: "Island is locked to visitors" + leavingspawn: "Leaving Spawn" + locking: "Locking island" + nowentering: "Now entering [name]'s island" + nowleaving: "Now leaving [name]'s island" + unlocking: "Unlocking island" +makeleader: + errorGeneralError: "Could not change leaders." + errorNotYourIsland: "This isn't your island, so you can't give it away!" + errorPlayerMustBeOnline: "That player must be online to transfer the island." + errorRemoveAllPlayersFirst: "Remove all players from your team other than the player you are transferring to." + errorThatPlayerIsNotInTeam: "That player is not part of your island team!" + errorYouMustBeInTeam: "You must be in a team to transfer your island." + nameIsNowTheOwner: "[name] is now the owner of your island!" + youAreNowTheOwner: "You are now the owner of your island." +minishop: + buy: "Buy(Left click)" + buyproblem: "There was a problem purchasing [description]" + islandhelpMiniShop: "Opens the MiniShop" + outofstock: "Out Of Stock" + sell: "Sell(Right click)" + sellproblem: "You do not have enough [description] to sell." + title: "&EMiniShop" + youbought: "You bought [number] [description] for [price]" + youcannotafford: "You cannot afford [description]!" + yousold: "You sold [number] [description] for [price]" +moblimits: + error: "Island animal breeding limit of [number] reached!" + hopper: "Island hopper limit of [number] reached!" + villager: "Island villager breeding limit of [number] reached!" +nether: + spawnisprotected: "The Nether spawn area is protected." +news: + headline: "[A Skyblock News] While you were offline..." +purge: + acidFound: "There are [number] unowned islands. Do '/acid purge unowned confirm' to delete them within 20 seconds." + allowPurge: "Purge protection removed" + alreadyRunning: "Purge is already running, please wait for it to finish!" + calculating: "Calculating which islands have been inactive for more than [time] days." + countingUnowned: "Counting unowned islands and checking player files. This could take some time..." + finished: "Finished purging of inactive islands." + noneFound: "No inactive islands to remove." + nowWaiting: "Now waiting..." + preventPurge: "Island is protected from purging" + purgeCancelled: "Purge cancelled." + removingAt: "Removing island at location [location]" + removingName: "Purge: Removing [name]'s island" + skyblockFound: "There are [number] unowned islands. Do '/asadmin purge unowned confirm' to delete them within 20 seconds." + stillChecking: "Still checking player files..." + thisWillRemove: "[number] inactive islands found. Islands with level < [level] will be removed." + typeConfirm: "Type /[label] confirm to proceed within 10 seconds" + usage: "Usage: /[label] purge [TimeInDays]" + warning: "DANGER! Do not run this with players on the server! MAKE BACKUP OF WORLD!" +register: + errorBedrockNotFound: "Could not register the island!" + settingIsland: "Set [name]'s island to the nearest island." +reject: + nameHasRejectedInvite: "[name] has rejected your island invite!" + youHaveNotBeenInvited: "You had not been invited to join a team." + youHaveRejectedInvitation: "You have rejected the invitation to join an island." +reload: + configReloaded: "Configuration reloaded from file." +resetallchallenges: + success: "[name] has had all challenges reset." +resetchallenge: + challengeReset: "Challenge: [challengename] has been reset for [name]" + errorChallengeDoesNotExist: "Challenge doesn't exist or isn't yet completed" +schematics: + title: "Select island..." +sethome: + errorNoIsland: "You are not part of an island. Returning you the spawn area!" + errorNotOnIsland: "You must be within your island boundaries to set home!" + errorNumHomes: "Homes can be 1 to [max]" + homeSet: "Your island home has been set to your current location." +sign: + line1: "&1[A Skyblock]" + line2: "[player]" + line3: "Do not fall!" + line4: "Beware!" +sign-acidisland: + line1: "&1[AcidIsland]" + line2: "[player]" + line3: "Water is acid!" + line4: "Beware!" +targetInPVPArea: "Target is in a no-PVP area!" +team: + listingMembers: "Listing your island members" +teamchat: + helpChat: "turn on/off team chat" + noTeam: "You are not in a team!" + noTeamAround: "None of your team are online!" + prefix: "[Team Chat]<{ISLAND_PLAYER}> " + statusOff: "Team chat is off" + statusOn: "Team chat is on" +topTen: + errorNotReady: "Top ten list not generated yet!" + header: "These are the Top 10 islands:" +warps: + deactivate: "Deactivating old sign!" + errorDoesNotExist: "That warp doesn't exist!" + errorDuplicate: "Sorry! There is a sign already in that location!" + errorNoPerm: "You do not have permission to place Welcome Signs yet!" + errorNoPlace: "You must be on your island to place a Welcome Sign!" + errorNoRemove: "You can only remove your own Welcome Sign!" + errorNoWarpsYet: "There are no warps available yet!" + errorNotReadyYet: "That warp is not ready yet. Try again later." + errorNotSafe: "That warp is not safe right now. Try again later." + next: "Next" + playerWarped: "[name] &2warped to your island!" + previous: "Previous" + removed: "Welcome sign removed!" + signRemoved: "Your welcome sign was removed!" + success: "Welcome sign placed successfully!" + title: "Island warps" + warpTip: "Create a warp by placing a sign with [WELCOME] at the top." + warpToPlayersSign: "Warping to 's welcome sign." + warpsAvailable: "The following warps are available" + welcomeLine: "[WELCOME]" diff --git a/WelcomeWarps/plugin.yml b/WelcomeWarps/plugin.yml index a3c7c62..4cf80ad 100644 --- a/WelcomeWarps/plugin.yml +++ b/WelcomeWarps/plugin.yml @@ -1,14 +1,14 @@ name: WelcomeWarpSigns -main: com.wasteofplastic.welcomewarpsigns.WelcomeWarpSigns -version: 1.0 +main: com.wasteofplastic.wwarps.WWarps +version: 1.1 description: Easy to use warp signs for players -author: Tastybento +author: tastybento commands: wwarp: - description: Admin Command for Warp Signs + description: Show Welcome Warp Signs aliases: wwarps usage: | - /wwarp to list warps /wwarp to warp + /wwarp to list warps, /wwarp to warp wwadmin: description: Admin Command for Warp Signs aliases: wadmin diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Metrics.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Metrics.java deleted file mode 100644 index 0e91f61..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Metrics.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.wasteofplastic.welcomewarpsigns; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.UUID; -import java.util.logging.Level; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - -public class Metrics { - private static String encode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { - buffer.append('&').append(encode(key)).append('=').append(encode(value)); - } - - private final YamlConfiguration configuration; - private final File configurationFile; - private final boolean debug; - private final String guid; - - private final Object optOutLock = new Object(); - - private final Plugin plugin; - - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - configuration.addDefault("opt-out", Boolean.valueOf(false)); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", Boolean.valueOf(false)); - - if (configuration.get("guid", null) == null) { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - public void disable() throws IOException { - synchronized (optOutLock) { - if (!isOptOut()) { - configuration.set("opt-out", Boolean.valueOf(true)); - configuration.save(configurationFile); - } - - if (task != null) { - task.cancel(); - task = null; - } - } - } - - public void enable() throws IOException { - synchronized (optOutLock) { - if (isOptOut()) { - configuration.set("opt-out", Boolean.valueOf(false)); - configuration.save(configurationFile); - } - - if (task == null) { - start(); - } - } - } - - public File getConfigFile() { - final File pluginsFolder = plugin.getDataFolder().getParentFile(); - - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (final Exception e) { - } - return false; - } - - public boolean isOptOut() { - synchronized (optOutLock) { - try { - configuration.load(getConfigFile()); - } catch (final IOException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } catch (final InvalidConfigurationException ex) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - private void postPlugin(final boolean isPing) throws IOException { - final PluginDescriptionFile description = plugin.getDescription(); - final String pluginName = description.getName(); - final boolean onlineMode = Bukkit.getServer().getOnlineMode(); - final String pluginVersion = description.getVersion(); - final String serverVersion = Bukkit.getVersion(); - final int playersOnline = Bukkit.getServer().getOnlinePlayers().length; - - final StringBuilder data = new StringBuilder(); - - data.append(encode("guid")).append('=').append(encode(guid)); - encodeDataPair(data, "version", pluginVersion); - encodeDataPair(data, "server", serverVersion); - encodeDataPair(data, "players", Integer.toString(playersOnline)); - encodeDataPair(data, "revision", String.valueOf(6)); - - final String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - final String osversion = System.getProperty("os.version"); - final String java_version = System.getProperty("java.version"); - final int coreCount = Runtime.getRuntime().availableProcessors(); - - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - - encodeDataPair(data, "osname", osname); - encodeDataPair(data, "osarch", osarch); - encodeDataPair(data, "osversion", osversion); - encodeDataPair(data, "cores", Integer.toString(coreCount)); - encodeDataPair(data, "online-mode", Boolean.toString(onlineMode)); - encodeDataPair(data, "java_version", java_version); - - if (isPing) { - encodeDataPair(data, "ping", "true"); - } - - final URL url = new URL("http://mcstats.org" + String.format("/report/%s", new Object[] { encode(pluginName) })); - URLConnection connection; - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - - connection.setDoOutput(true); - - final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(data.toString()); - writer.flush(); - - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - final String response = reader.readLine(); - - writer.close(); - reader.close(); - - if (response == null || response.startsWith("ERR")) { - throw new IOException(response); - } - } - - public boolean start() { - synchronized (optOutLock) { - if (isOptOut()) { - return false; - } - - if (task != null) { - return true; - } - - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { - private boolean firstPost = true; - - public void run() { - try { - synchronized (optOutLock) { - if (Metrics.this.isOptOut() && task != null) { - task.cancel(); - task = null; - } - - } - - Metrics.this.postPlugin(!firstPost); - - firstPost = false; - } catch (final IOException e) { - if (debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0L, 12000L); - - return true; - } - } -} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Settings.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Settings.java deleted file mode 100644 index 9779407..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/Settings.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.wasteofplastic.welcomewarpsigns; - -import java.util.List; - - -/** - * @author ben - * Where all the settings are - */ -public class Settings { - public static List worldName; - -} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WAdmin.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WAdmin.java deleted file mode 100644 index f6482dd..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WAdmin.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * - */ -package com.wasteofplastic.welcomewarpsigns; - -import java.util.HashMap; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -/** - * @author ben - * - */ -public class WAdmin implements CommandExecutor { - private WelcomeWarpSigns plugin; - /** - * - */ - public WAdmin(WelcomeWarpSigns plugin) { - this.plugin = plugin; - } - - /* (non-Javadoc) - * @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) - */ - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (sender instanceof Player) { - // Check permissions - if (!sender.hasPermission("welcomewarpsigns.admin")) { - sender.sendMessage(ChatColor.RED + "You do not have permission to use that command!"); - return true; - } - } - switch (args.length) { - // Switch on arguments - case 1: - // List - if (args[0].equalsIgnoreCase("list")) { - // Step through warp table - HashMap warpList = plugin.listWarpsAndLocs(); - if (warpList.isEmpty()) { - sender.sendMessage(ChatColor.YELLOW + "There are no warps created yet!"); - } else { - sender.sendMessage(ChatColor.YELLOW + "[Warp Name] - [World: X:Y:Z location]"); - for (String name : warpList.keySet()) { - sender.sendMessage(ChatColor.AQUA + name + ChatColor.GRAY + " - " + ChatColor.WHITE + warpList.get(name)); - } - } - return true; - } - if (args[0].equalsIgnoreCase("remove")) { - sender.sendMessage(ChatColor.YELLOW + "/wwadmin remove - removed warp, deactivates sign"); - return true; - } - case 2: - // Remove warp command - if (args[0].equalsIgnoreCase("remove")) { - if (!plugin.checkWarp(args[1].toLowerCase())) { - sender.sendMessage(ChatColor.RED + "That warp doesn't exist."); - return true; - } else { - // Remove warp - if (plugin.removeWarp(args[1].toLowerCase())) { - sender.sendMessage(ChatColor.GREEN + "Warp removed."); - } else { - sender.sendMessage(ChatColor.RED + "Warp could not be found. Check warps.yml for corruption."); - } - return true; - } - } - sender.sendMessage(ChatColor.RED + "Unknown command"); - default: - // No argument so print the help - sender.sendMessage(ChatColor.YELLOW + "[Welcome Warp Signs Help]"); - sender.sendMessage(ChatColor.YELLOW + "/wwadmin list - lists all known warps and their locations"); - sender.sendMessage(ChatColor.YELLOW + "/wwadmin remove - removed warp, deactivates sign"); - return true; - } - } -} diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WWarpCmd.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WWarpCmd.java deleted file mode 100644 index a2264d6..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WWarpCmd.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.wasteofplastic.welcomewarpsigns; - -import java.util.Collection; - -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public class WWarpCmd implements CommandExecutor { - private WelcomeWarpSigns plugin; - - - public WWarpCmd(WelcomeWarpSigns plugin) { - this.plugin = plugin; - } - - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (!(sender instanceof Player)) { - sender.sendMessage("/wwarp is for players only. Try /wwadmin?"); - return true; - } - final Player player = (Player) sender; - if (!Settings.worldName.isEmpty() && !Settings.worldName.contains(player.getWorld().getName())) { - // Wrong world - player.sendMessage(ChatColor.RED + "Welcome Warp Signs are not available in this world!"); - return true; - } - switch (args.length) { - case 0: - if (player.hasPermission("welcomewarpsigns.use")) { - // Step through warp table - Collection warpList = plugin.listWarps(); - if (warpList.isEmpty()) { - player.sendMessage(ChatColor.YELLOW + "There are no warps available yet!"); - if (player.hasPermission("welcomewarpsigns.add")) { - player.sendMessage(ChatColor.YELLOW + "Create a warp by placing a sign with [WELCOME] at the top."); - } - return true; - } else { - String wlist = ""; - for (String w : warpList) { - if (wlist.isEmpty()) { - wlist = w; - } else { - wlist += ", " + w; - - } - } - player.sendMessage(ChatColor.YELLOW + "The following warps are available: " + ChatColor.WHITE + wlist); - if (plugin.getWarp(player)==null && player.hasPermission("welcomewarpsigns.add")) { - player.sendMessage(ChatColor.YELLOW + "Create a warp by placing a sign with [WELCOME] at the top."); - } - return true; - } - } - case 1: - // Warp somewhere command - if (player.hasPermission("welcomewarpsigns.use")) { - final Collection warpList = plugin.listWarps(); - if (warpList.isEmpty()) { - player.sendMessage(ChatColor.YELLOW + "There are no warps available yet!"); - if (player.hasPermission("welcomewarpsigns.add")) { - player.sendMessage(ChatColor.YELLOW + "Create a warp by placing a sign with [WELCOME] at the top."); - } - return true; - } else if (!plugin.checkWarp(args[0].toLowerCase())) { - player.sendMessage(ChatColor.RED + "That warp doesn't exist."); - return true; - } else { - // Warp exists! - final Location warpSpot = plugin.getWarp(args[0].toLowerCase()); - // Check if the warp spot is safe - if (warpSpot == null) { - player.sendMessage(ChatColor.RED + "That warp is not ready yet! Try again later!"); - plugin.getLogger().warning("Null warp found, owned by " + args[0]); - return true; - } - if (!(WelcomeWarpSigns.isSafeLocation(warpSpot))) { - player.sendMessage(ChatColor.RED + "That warp is not safe right now! Try again later!"); - plugin.getLogger().warning("Unsafe warp found at " + warpSpot.toString() + " owned by " + args[0]); - return true; - } else { - final Location actualWarp = new Location(warpSpot.getWorld(), warpSpot.getBlockX() + 0.5D, warpSpot.getBlockY(), - warpSpot.getBlockZ() + 0.5D); - player.teleport(actualWarp); - player.getWorld().playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1F, 1F); - return true; - } - } - } - return false; - - } - return false; - } - -} diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WarpSignsListener.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WarpSignsListener.java deleted file mode 100644 index c75ccf5..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WarpSignsListener.java +++ /dev/null @@ -1,183 +0,0 @@ -/** - * - */ -package com.wasteofplastic.welcomewarpsigns; - -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.material.Attachable; -import org.bukkit.material.MaterialData; - -/** - * Handles warping in AcidIsland Players can add one sign - * - * @author ben - * - */ -public class WarpSignsListener implements Listener { - private final WelcomeWarpSigns plugin; - - public WarpSignsListener(WelcomeWarpSigns acidIsland) { - plugin = acidIsland; - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) - public void onSignPopped(BlockPhysicsEvent e) { - // Block b = e.getBlock().getRelative(BlockFace.UP); - Block b = e.getBlock(); - if (!Settings.worldName.isEmpty() && !Settings.worldName.contains(b.getWorld().getName())) { - // Wrong world - return; - } - // plugin.getLogger().info("Block type " + b.getType().toString()); - if (plugin.checkWarp(b.getLocation())) { - //plugin.getLogger().info("Known warp location!"); - // This is the sign block - check to see if it is still a sign - if (b.getType().equals(Material.SIGN_POST)) { - // Check to see if it is still attached - MaterialData m = b.getState().getData(); - BlockFace face = BlockFace.DOWN; // Most of the time it's going - // to be down - if (m instanceof Attachable) { - face = ((Attachable) m).getAttachedFace(); - } - if (b.getRelative(face).getType().isSolid()) { - //plugin.getLogger().info("Attached to some solid block"); - } else { - /* - * } MaterialData m = b.getState().getData(); BlockFace face - * = BlockFace.DOWN; if (m instanceof Attachable) { face = - * ((Attachable) m).getAttachedFace(); } - */ - // b.getRelative(face); - //plugin.getLogger().info("Not attached!"); - plugin.removeWarp(b.getLocation()); - //plugin.getLogger().info("Warp removed"); - } - } - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) - public void onSignBreak(BlockBreakEvent e) { - Block b = e.getBlock(); - Player player = e.getPlayer(); - if (Settings.worldName.contains(b.getWorld().getName()) || Settings.worldName.isEmpty()) { - if (b.getType().equals(Material.SIGN_POST)) { - Sign s = (Sign) b.getState(); - if (s != null) { - if (s.getLine(0).equalsIgnoreCase(ChatColor.GREEN + "[WELCOME]")) { - // Do a quick check to see if this sign location is in - // the list of warp signs - if (plugin.checkWarp(s.getLocation())) { - // Welcome sign detected - check to see if it is - // this player's sign - final Location playerSignLoc = plugin.getWarp(player); - if (playerSignLoc != null) { - if (playerSignLoc.equals(s.getLocation())) { - // This is the player's sign, so allow it to - // be destroyed - player.sendMessage(ChatColor.GREEN + "Welcome sign removed"); - plugin.removeWarp(player); - } else { - player.sendMessage(ChatColor.RED + "You can only remove your own Welcome Sign"); - e.setCancelled(true); - } - } else { - // Someone else's sign because this player has - // none registered - player.sendMessage(ChatColor.RED + "You can only remove your own Welcome Sign"); - e.setCancelled(true); - } - } - } - } - } - } - } - - /** - * Event handler for Sign Changes - * - * @param e - */ - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) - public void onSignWarpCreate(SignChangeEvent e) { - //plugin.getLogger().info("SignChangeEvent called"); - String title = e.getLine(0); - Player player = e.getPlayer(); - if (Settings.worldName.contains(player.getWorld().getName()) || Settings.worldName.isEmpty()) { - plugin.getLogger().info("Correct world"); - if (e.getBlock().getType().equals(Material.SIGN_POST)) { - plugin.getLogger().info("The first line of the sign says " + title); - if (title.equalsIgnoreCase("[WELCOME]")) { - plugin.getLogger().info("Welcome sign detected"); - // Welcome sign detected - check permissions - if (!(player.hasPermission("welcomewarpsigns.add"))) { - player.sendMessage(ChatColor.RED + "You do not have permission to place Welcome Signs yet"); - return; - } - // Check if the sign is in an acceptable location - if (!WelcomeWarpSigns.isSafeLocation(e.getBlock().getLocation())) { - player.sendMessage(ChatColor.RED + "Sorry! That is not a safe place to put a Welcome Sign!"); - e.setLine(0, ChatColor.RED + "[WELCOME]"); - return; - } - // Check if the player already has a sign - final Location oldSignLoc = plugin.getWarp(player); - if (oldSignLoc == null) { - //plugin.getLogger().info("Player does not have a sign already"); - // First time the sign has been placed or this is a new sign - if (plugin.addWarp(player, e.getBlock().getLocation())) { - player.sendMessage(ChatColor.GREEN + "Welcome sign placed successfully!"); - e.setLine(0, ChatColor.GREEN + "[WELCOME]"); - } else { - player.sendMessage(ChatColor.RED + "Sorry! There is a sign already in that location!"); - e.setLine(0, ChatColor.RED + "[WELCOME]"); - } - } else { - //plugin.getLogger().info("Player already has a Sign"); - // A sign already exists. Check if it still there and if so, - // deactivate it - Block oldSignBlock = oldSignLoc.getBlock(); - if (oldSignBlock.getType().equals(Material.SIGN_POST)) { - // The block is still a sign - //plugin.getLogger().info("The block is still a sign"); - Sign oldSign = (Sign) oldSignBlock.getState(); - if (oldSign != null) { - //plugin.getLogger().info("Sign block is a sign"); - if (oldSign.getLine(0).equalsIgnoreCase(ChatColor.GREEN + "[WELCOME]")) { - //plugin.getLogger().info("Old sign had a green welcome"); - oldSign.setLine(0, ChatColor.RED + "[WELCOME]"); - oldSign.update(); - player.sendMessage(ChatColor.RED + "Deactivating old sign."); - plugin.removeWarp(player); - } - } - } - // Set up the warp - if (plugin.addWarp(player, e.getBlock().getLocation())) { - player.sendMessage(ChatColor.GREEN + "Welcome sign placed successfully!"); - e.setLine(0, ChatColor.GREEN + "[WELCOME]"); - } else { - player.sendMessage(ChatColor.RED + "Sorry! There is a sign already in that location!"); - e.setLine(0, ChatColor.RED + "[WELCOME]"); - } - } - } - } - } - } - -} diff --git a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WelcomeWarpSigns.java b/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WelcomeWarpSigns.java deleted file mode 100644 index 21653f2..0000000 --- a/WelcomeWarps/src/com/wasteofplastic/welcomewarpsigns/WelcomeWarpSigns.java +++ /dev/null @@ -1,460 +0,0 @@ -package com.wasteofplastic.welcomewarpsigns; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - -/** - * @author ben - * Main WelcomeWarpSigns class - provides an island minigame in a sea of acid - */ -public class WelcomeWarpSigns extends JavaPlugin { - // This plugin - private static WelcomeWarpSigns plugin; - // Where warps are stored - public YamlConfiguration welcomeWarps; - // Map of all warps stored as warp owner's UUID as string, warp sign Location as String - private HashMap warpList = new HashMap(); - // Warp names are owner's UUID as string: owner's name when they made the warp - private HashMap warpNames = new HashMap(); - // File locations - String pluginMainDir = getDataFolder().toString(); - /** - * @return WelcomeWarpSigns object instance - */ - public static WelcomeWarpSigns getPlugin() { - return plugin; - } - - - /** - * Converts a serialized location to a Location - * @param s - serialized location in format "world:x:y:z" - * @return Location - */ - static public Location getLocationString(final String s) { - if (s == null || s.trim() == "") { - return null; - } - final String[] parts = s.split(":"); - if (parts.length == 4) { - final World w = Bukkit.getServer().getWorld(parts[0]); - final int x = Integer.parseInt(parts[1]); - final int y = Integer.parseInt(parts[2]); - final int z = Integer.parseInt(parts[3]); - return new Location(w, x, y, z); - } - return null; - } - - /** - * Converts a location to a simple string representation - * - * @param l - * @return - */ - static public String getStringLocation(final Location l) { - if (l == null) { - return ""; - } - return l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ(); - } - - /** - * Checks if this location is safe for a player to teleport to. Used by - * warps and boat exits Unsafe is any liquid or air and also if there's no - * space - * - * @param l - * - Location to be checked - * @return true if safe, otherwise false - */ - public static boolean isSafeLocation(final Location l) { - if (l == null) { - return false; - } - final Material ground = l.getBlock().getRelative(BlockFace.DOWN).getType(); - // Check the ground - switch (ground) { - case AIR: - case CACTUS: - case LAVA: - case STATIONARY_LAVA: - case SIGN: - case WALL_SIGN: - case SIGN_POST: - case BOAT: - case STONE_PLATE: - case WOOD_PLATE: - case GOLD_PLATE: - case IRON_PLATE: - return false; - default: - break; - } - final Block space1 = l.getBlock(); - final Block space2 = l.getBlock().getRelative(BlockFace.UP); - if (space1.isLiquid() || space2.isLiquid()) { - return false; - } - if (space1.getType().isSolid()) { - // Do a few other checks - if (!(space1.getType().equals(Material.SIGN_POST)) && !(space1.getType().equals(Material.WALL_SIGN))) { - return false; - } - } - if (space2.getType().isSolid()) { - // Do a few other checks - if (!(space2.getType().equals(Material.SIGN_POST)) && !(space2.getType().equals(Material.WALL_SIGN))) { - return false; - } - } - // Safe - return true; - } - - - /** - * Saves a YAML file - * - * @param yamlFile - * @param fileLocation - */ - public static void saveYamlFile(YamlConfiguration yamlFile, String fileLocation) { - File dataFolder = plugin.getDataFolder(); - File file = new File(dataFolder, fileLocation); - - try { - yamlFile.save(file); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Loads a YAML file - * - * @param file - * @return - */ - public static YamlConfiguration loadYamlFile(String file) { - File dataFolder = plugin.getDataFolder(); - File yamlFile = new File(dataFolder, file); - - YamlConfiguration config = null; - if (yamlFile.exists()) { - try { - config = new YamlConfiguration(); - config.load(yamlFile); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - // Create the missing file - config = new YamlConfiguration(); - getPlugin().getLogger().info("No " + file + " found. Creating it..."); - } - return config; - } - - /** - * Creates the warp list if it does not exist - */ - public void loadWarpList() { - getLogger().info("Loading warps..."); - // warpList.clear(); - welcomeWarps = loadYamlFile("warps.yml"); - if (welcomeWarps.getConfigurationSection("warps") == null || welcomeWarps.getConfigurationSection("names") == null) { - welcomeWarps.createSection("warps"); - welcomeWarps.createSection("names"); - } - // Load the locations - HashMap temp = (HashMap) welcomeWarps.getConfigurationSection("warps").getValues(true); - for (String s : temp.keySet()) { - warpList.put(s, temp.get(s).toString()); - } - HashMap temp2 = (HashMap) welcomeWarps.getConfigurationSection("names").getValues(true); - for (String s : temp2.keySet()) { - // Convert to lower case just in case someone fiddled with the YML file - warpNames.put(s,temp2.get(s).toString().toLowerCase()); - } - - } - - /** - * Saves the warp lists to file - */ - public void saveWarpList() { - getLogger().info("Saving warps..."); - // Warp locations UUID as String:Location as String - final HashMap warps = new HashMap(); - for (String s : warpList.keySet()) { - // We store the UUID - warps.put(s,warpList.get(s)); - } - welcomeWarps.set("warps", warps); - - // Warp names UUID as string: name - final HashMap names = new HashMap(); - for (String s : warpNames.keySet()) { - // We store the UUID and the name - names.put(s, warpNames.get(s).toLowerCase()); - } - welcomeWarps.set("names", names); - - saveYamlFile(welcomeWarps, "warps.yml"); - } - - /** - * Stores warps in the warp array - * - * @param player - * @param loc - */ - public boolean addWarp(Player player, Location loc) { - final String locS = getStringLocation(loc); - final String uuid = player.getUniqueId().toString(); - // Do not allow warps to be in the same location - if (warpList.containsValue(locS)) { - return false; - } - // Remove the old warp if it existed - warpList.remove(uuid); - warpNames.remove(uuid); - warpList.put(uuid, locS); - warpNames.put(uuid, player.getName().toLowerCase()); - saveWarpList(); - return true; - } - - /** - * Removes a warp when the welcome sign is destroyed. Called by - * WarpSigns.java. - * - * @param uuid - */ - public void removeWarp(Player player) { - warpList.remove(player.getUniqueId().toString()); - warpNames.remove(player.getUniqueId().toString()); - saveWarpList(); - } - - /** - * Removes a warp at a location. Called by WarpSigns.java. - * - * @param loc - */ - public void removeWarp(Location loc) { - final String locS = getStringLocation(loc); - getLogger().info("Asked to remove warp at " + locS); - if (warpList.containsValue(locS)) { - String uuid = getKeyByValue(warpList,locS); - warpList.remove(uuid); - warpNames.remove(uuid); - try { - // Try to tell the player if they are online that their welcome sign was removed - plugin.getServer().getPlayer(UUID.fromString(uuid)).sendMessage(ChatColor.RED + "Your welcome sign was removed!"); - } catch (Exception e) {} - saveWarpList(); - } - } - - /** - * Removes the warp sign based on the name of the owner. Called by wadmin. - * Also breaks the sign if it exists - * @param name - * @return true if the sign was removed - */ - public boolean removeWarp(String name) { - if (!warpNames.containsValue(name.toLowerCase())) { - return false; - } - String uuid = getKeyByValue(warpNames,name); - Location signLoc = getLocationString(warpList.get(uuid)); - if (signLoc != null) { - // Remove the sign too - try { - if (signLoc.getBlock().getType().equals(Material.SIGN_POST)) { - signLoc.getBlock().breakNaturally(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - warpList.remove(uuid); - warpNames.remove(uuid); - return true; - } - - /** - * Returns true if the location supplied is a warp location - * - * @param loc - * @return true if this location has a warp sign, false if not - */ - public boolean checkWarp(Location loc) { - final String locS = getStringLocation(loc); - if (warpList.containsValue(locS)) { - return true; - } - return false; - } - - /* - * Checks the name of a warp - * @param name - * @return true if the warp is know otherwise false - */ - public boolean checkWarp(String name) { - if (warpNames.containsValue(name.toLowerCase())) { - return true; - } - return false; - } - - /** - * Lists all the known warps - * - * @return String set of warps - */ - public Collection listWarps() { - return warpNames.values(); - } - - /** - * Provides the location of the warp for player - * - * @param player - * - the warp requested - * @return Location of warp - */ - public Location getWarp(Player player) { - if (warpList.containsKey(player.getUniqueId().toString())) { - return getLocationString((String) warpList.get(player.getUniqueId().toString())); - } else { - return null; - } - } - - /** - * Gets a warp based on name - * @param name - * @return - */ - public Location getWarp(String name) { - if (warpNames.containsValue(name)) { - return getLocationString(warpList.get(getKeyByValue(warpNames,name))); - } else { - return null; - } - } - - /** - * Loads the various settings from the config.yml file into the plugin - */ - public void loadPluginConfig() { - try { - getConfig(); - } catch (final Exception e) { - e.printStackTrace(); - } - Settings.worldName = getConfig().getStringList("signworlds"); - } - - /* - * (non-Javadoc) - * - * @see org.bukkit.plugin.java.JavaPlugin#onDisable() - */ - @Override - public void onDisable() { - try { - saveWarpList(); - } catch (final Exception e) { - plugin.getLogger().severe("Something went wrong saving the warp list!"); - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.bukkit.plugin.java.JavaPlugin#onEnable() - */ - @Override - public void onEnable() { - // instance of this plugin - plugin = this; - saveDefaultConfig(); - // Metrics - try { - final Metrics metrics = new Metrics(this); - metrics.start(); - } catch (final IOException localIOException) { - } - loadPluginConfig(); - // Set up commands for this plugin - getCommand("wwarp").setExecutor(new WWarpCmd(this)); - getCommand("wwadmin").setExecutor(new WAdmin(this)); - // Register events that this plugin uses - registerEvents(); - // Load warps - loadWarpList(); - } - - /** - * Registers events - */ - public void registerEvents() { - final PluginManager manager = getServer().getPluginManager(); - // Enables warp signs in WelcomeWarpSigns - manager.registerEvents(new WarpSignsListener(this), this); - } - - /** - * One-to-one relationship, you can return the first matched key - * @param map - * @param value - * @return - */ - public static T getKeyByValue(Map map, E value) { - for (Entry entry : map.entrySet()) { - if (value.equals(entry.getValue())) { - return entry.getKey(); - } - } - return null; - } - - - /** - * Provides a list of names and locations - * @return Hasmap of names and locations as strings - */ - public HashMap listWarpsAndLocs() { - HashMap list = new HashMap(); - // Link the tables together so they are name : location - for (String uuid : warpList.keySet()) { - list.put(warpNames.get(uuid), warpList.get(uuid)); - } - return list; - } - - -} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/Locale.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/Locale.java new file mode 100644 index 0000000..070cd3f --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/Locale.java @@ -0,0 +1,233 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps; + +import java.io.File; +import java.io.InputStream; + +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + + +/** + * All the text strings in the game sent to players + * This version enables different players to have different locales. + * + * @author tastybento + */ +public class Locale { + + // Localization Strings + private FileConfiguration locale = null; + private File localeFile = null; + private WWarps plugin; + + // Errors + public String errorUnknownPlayer; + public String errorNoPermission; + public String errorCommandNotReady; + public String errorOfflinePlayer; + public String errorUnknownCommand; + // WarpSigns + public String warpswelcomeLine; + public String warpswarpTip; + public String warpssuccess; + public String warpsremoved; + public String warpssignRemoved; + public String warpsdeactivate; + public String warpserrorNoRemove; + public String warpserrorNoPerm; + public String warpserrorNoPlace; + public String warpserrorDuplicate; + public String warpserrorDoesNotExist; + public String warpserrorNotReadyYet; + public String warpserrorNotSafe; + // island warp help + public String warpswarpToPlayersSign; + public String warpserrorNoWarpsYet; + public String warpswarpsAvailable; + public String warpsPlayerWarped; + + public String islanderrorYouDoNotHavePermission; + + // /island warps; + public String islandhelpWarps; + // /island warp + public String islandhelpWarp; + public String islanderrorInvalidPlayer; + + + + + // //////////////////////////////////// + // /island commands // + // //////////////////////////////////// + + + + + + // ////////////////////////////////////////////////////////////// + // Admin commands that use /acid // + // ////////////////////////////////////////////////////////////// + + // acid reload + public String reloadconfigReloaded; + public String errorWrongWorld; + public String prefix; + public String helpColor; + public String warpsPrevious; + public String warpsNext; + public String warpsTitle; + public String errorUseInGame; + public String adminHelpResetSign; + public String adminResetSignNoSign; + public String adminResetSignFound; + public String adminResetSignRescued; + public String adminResetSignErrorExists; + public String newsHeadline; + public String adminHelpreload; + public String adminHelpHelp; + /** + * Creates a locale object full of localized strings for a language + * @param plugin + * @param localeName - name of the yml file that will be used + */ + public Locale(WWarps plugin, String localeName) { + this.plugin = plugin; + getLocale(localeName); + loadLocale(); + } + + /** + * @return locale FileConfiguration object + */ + public FileConfiguration getLocale(String localeName) { + if (this.locale == null) { + reloadLocale(localeName); + } + return locale; + } + + /** + * Reloads the locale file + */ + public void reloadLocale(String localeName) { + //plugin.getLogger().info("DEBUG: loading local file " + localeName + ".yml"); + // Make directory if it doesn't exist + File localeDir = new File(plugin.getDataFolder() + File.separator + "locale"); + if (!localeDir.exists()) { + localeDir.mkdir(); + } + if (localeFile == null) { + localeFile = new File(localeDir.getPath(), localeName + ".yml"); + } + if (localeFile.exists()) { + //plugin.getLogger().info("DEBUG: File exists!"); + locale = YamlConfiguration.loadConfiguration(localeFile); + } else { + // Look for defaults in the jar + InputStream defLocaleStream = plugin.getResource("locale/" + localeName + ".yml"); + if (defLocaleStream != null) { + //plugin.getLogger().info("DEBUG: Saving from jar"); + plugin.saveResource("locale/" + localeName + ".yml", true); + localeFile = new File(plugin.getDataFolder() + File.separator + "locale", localeName + ".yml"); + locale = YamlConfiguration.loadConfiguration(localeFile); + //locale.setDefaults(defLocale); + } else { + // Use the default file + localeFile = new File(plugin.getDataFolder() + File.separator + "locale", "locale.yml"); + if (localeFile.exists()) { + locale = YamlConfiguration.loadConfiguration(localeFile); + } else { + // Look for defaults in the jar + defLocaleStream = plugin.getResource("locale/locale.yml"); + if (defLocaleStream != null) { + plugin.saveResource("locale/locale.yml", true); + localeFile = new File(plugin.getDataFolder() + File.separator + "locale", "locale.yml"); + locale = YamlConfiguration.loadConfiguration(localeFile); + } else { + plugin.getLogger().severe("Could not find any locale file!"); + } + } + } + } + } + + public void loadLocale() { + // Localization Locale Setting + // Command prefix - can be added to the beginning of any message + prefix = ChatColor.translateAlternateColorCodes('&', ChatColor.translateAlternateColorCodes('&', locale.getString("prefix", ""))); + errorUnknownPlayer = ChatColor.translateAlternateColorCodes('&', locale.getString("error.unknownPlayer", "That player is unknown.")); + errorNoPermission = ChatColor.translateAlternateColorCodes('&', + locale.getString("error.noPermission", "You don't have permission to use that command!")); + errorCommandNotReady = ChatColor.translateAlternateColorCodes('&', + locale.getString("error.commandNotReady", "You can't use that command right now.")); + errorOfflinePlayer = ChatColor.translateAlternateColorCodes('&', + locale.getString("error.offlinePlayer", "That player is offline or doesn't exist.")); + errorUnknownCommand = ChatColor.translateAlternateColorCodes('&', locale.getString("error.unknownCommand", "Unknown command.")); + errorWrongWorld = ChatColor.translateAlternateColorCodes('&', locale.getString("error.wrongWorld", "You cannot do that in this world.")); + newsHeadline = ChatColor.translateAlternateColorCodes('&', locale.getString("newsheadline", "Welcome Warp News")); + warpswelcomeLine = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.welcomeLine", "[WELCOME]")); + warpswarpTip = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.warpTip", "Create a warp by placing a sign with [WELCOME] at the top.")); + warpssuccess = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.success", "Welcome sign placed successfully!")); + warpsremoved = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.removed", "Welcome sign removed!")); + warpssignRemoved = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.signRemoved", "Your welcome sign was removed!")); + warpsdeactivate = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.deactivate", "Deactivating old sign!")); + warpserrorNoRemove = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNoRemove", "You can only remove your own Welcome Sign!")); + warpserrorNoPerm = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNoPerm", "You do not have permission to place Welcome Signs yet!")); + warpserrorNoPlace = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNoPlace", "You must be on your island to place a Welcome Sign!")); + warpserrorDuplicate = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorDuplicate", "Sorry! There is a sign already in that location!")); + warpserrorDoesNotExist = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.errorDoesNotExist", "That warp doesn't exist!")); + warpserrorNotReadyYet = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNotReadyYet", "That warp is not ready yet. Try again later.")); + warpserrorNotSafe = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNotSafe", "That warp is not safe right now. Try again later.")); + warpswarpToPlayersSign = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.warpToPlayersSign", "Warping to 's welcome sign.")); + warpserrorNoWarpsYet = ChatColor.translateAlternateColorCodes('&', + locale.getString("warps.errorNoWarpsYet", "There are no warps available yet!")); + warpswarpsAvailable = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.warpsAvailable", "The following warps are available")); + warpsPlayerWarped = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.playerWarped", "[name] &2warped to your island!")); + warpsPrevious = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.previous", "Previous")); + warpsNext = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.next", "Next")); + warpsTitle = ChatColor.translateAlternateColorCodes('&', locale.getString("warps.title", "Island warps")); + islanderrorYouDoNotHavePermission = ChatColor.translateAlternateColorCodes('&', + locale.getString("island.errorYouDoNotHavePermission", "You do not have permission to use that command!")); + islandhelpWarps = ChatColor.translateAlternateColorCodes('&', locale.getString("island.helpWarps", "Lists all available welcome-sign warps.")); + islandhelpWarp = ChatColor.translateAlternateColorCodes('&', locale.getString("island.helpWarp", "Warp to 's welcome sign.")); + islanderrorInvalidPlayer = ChatColor.translateAlternateColorCodes('&', + locale.getString("island.errorInvalidPlayer", "That player is invalid or does not have an island!")); + reloadconfigReloaded = ChatColor.translateAlternateColorCodes('&', + locale.getString("reload.configReloaded", "Configuration reloaded from file.")); + helpColor = ChatColor.translateAlternateColorCodes('&', locale.getString("island.helpColor", "&e")); + errorUseInGame = ChatColor.translateAlternateColorCodes('&', locale.getString("error.useInGame", "This command must be used in-game.")); + adminHelpResetSign = ChatColor.translateAlternateColorCodes('&', locale.getString("adminHelp.resetSign", "Resets the sign you are looking at to the island owner")); + adminHelpHelp = ChatColor.translateAlternateColorCodes('&', locale.getString("adminHelp.help", "Admin Help")); + adminHelpreload = ChatColor.translateAlternateColorCodes('&', locale.getString("adminHelp.reload", "reload plugin settings")); + adminResetSignNoSign = ChatColor.translateAlternateColorCodes('&', locale.getString("adminResetSign.noSign", "You must be looking at a sign post to run this command.")); + adminResetSignFound = ChatColor.translateAlternateColorCodes('&', locale.getString("adminResetSign.found", "Warp Sign found!")); + adminResetSignRescued = ChatColor.translateAlternateColorCodes('&', locale.getString("adminResetSign.rescued", "Warp sign rescued and assigned to [name]")); + adminResetSignErrorExists = ChatColor.translateAlternateColorCodes('&', locale.getString("adminResetSign.errorExists", "That warp sign is already active and owned by [name]")); + } +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/Messages.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/Messages.java new file mode 100644 index 0000000..f616399 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/Messages.java @@ -0,0 +1,148 @@ +package com.wasteofplastic.wwarps; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; + +import com.wasteofplastic.wwarps.util.Util; + +/** + * Handles offline messaging to players and teams + * + * @author tastybento + * + */ +public class Messages { + private WWarps plugin; + // Offline Messages + private HashMap> messages = new HashMap>(); + private YamlConfiguration messageStore; + + + /** + * @param plugin + */ + public Messages(WWarps plugin) { + this.plugin = plugin; + } + + /** + * Returns what messages are waiting for the player or null if none + * + * @param playerUUID + * @return + */ + public List getMessages(UUID playerUUID) { + List playerMessages = messages.get(playerUUID); + return playerMessages; + } + + /** + * Clears any messages for player + * + * @param playerUUID + */ + public void clearMessages(UUID playerUUID) { + messages.remove(playerUUID); + } + + public void saveMessages() { + if (messageStore == null) { + return; + } + plugin.getLogger().info("Saving offline messages..."); + try { + // Convert to a serialized string + final HashMap offlineMessages = new HashMap(); + for (UUID p : messages.keySet()) { + offlineMessages.put(p.toString(), messages.get(p)); + } + // Convert to YAML + messageStore.set("messages", offlineMessages); + Util.saveYamlFile(messageStore, "messages.yml"); + return; + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + + public boolean loadMessages() { + plugin.getLogger().info("Loading offline messages..."); + try { + messageStore = Util.loadYamlFile("messages.yml"); + if (messageStore.getConfigurationSection("messages") == null) { + messageStore.createSection("messages"); // This is only used to + // create + } + HashMap temp = (HashMap) messageStore.getConfigurationSection("messages").getValues(true); + for (String s : temp.keySet()) { + List messageList = messageStore.getStringList("messages." + s); + if (!messageList.isEmpty()) { + messages.put(UUID.fromString(s), messageList); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * Provides the messages for the player + * + * @param playerUUID + * @return List of messages + */ + public List get(UUID playerUUID) { + return messages.get(playerUUID); + } + + /** + * Stores a message for player + * + * @param playerUUID + * @param playerMessages + */ + public void put(UUID playerUUID, List playerMessages) { + messages.put(playerUUID, playerMessages); + + } + + + /** + * Sets a message for the player to receive next time they login + * + * @param player + * @param message + * @return true if player is offline, false if online + */ + public boolean setMessage(UUID playerUUID, String message) { + // getLogger().info("DEBUG: received message - " + message); + Player player = plugin.getServer().getPlayer(playerUUID); + // Check if player is online + if (player != null) { + if (player.isOnline()) { + // player.sendMessage(message); + return false; + } + } + // Player is offline so store the message + // getLogger().info("DEBUG: player is offline - storing message"); + List playerMessages = get(playerUUID); + if (playerMessages != null) { + playerMessages.add(message); + } else { + playerMessages = new ArrayList(Arrays.asList(message)); + } + put(playerUUID, playerMessages); + return true; + } + +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/Settings.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/Settings.java new file mode 100644 index 0000000..1a45a42 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/Settings.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps; + +import java.util.List; + + +/** + * Where all the settings are + * + * @author tastybento + */ +public class Settings { + // Permission prefix + public final static String PERMPREFIX = "welcomewarpsigns."; + // Admin command + public static final String ADMINCOMMAND = "wwadmin"; + + public static List worldName; + public static int debug; + public static boolean useWarpPanel = true; + + + +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/WWarps.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/WWarps.java new file mode 100644 index 0000000..d0e5b1a --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/WWarps.java @@ -0,0 +1,257 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ + +package com.wasteofplastic.wwarps; + +import java.util.HashMap; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.material.MaterialData; +import org.bukkit.material.SimpleAttachableMaterialData; +import org.bukkit.material.TrapDoor; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import com.wasteofplastic.wwarps.commands.AdminCmd; +import com.wasteofplastic.wwarps.commands.WarpCmd; +import com.wasteofplastic.wwarps.listeners.JoinLeaveEvents; +import com.wasteofplastic.wwarps.panels.WarpPanel; + +/** + * @author tastybento + * Main ASkyBlock class - provides an island minigame in a sea of acid + */ +public class WWarps extends JavaPlugin { + /** + * Checks if this location is safe for a player to teleport to. Used by + * warps and boat exits Unsafe is any liquid or air and also if there's no + * space + * + * @param l + * - Location to be checked + * @return true if safe, otherwise false + */ + public static boolean isSafeLocation(final Location l) { + if (l == null) { + return false; + } + // TODO: improve the safe location finding. + //Bukkit.getLogger().info("DEBUG: " + l.toString()); + final Block ground = l.getBlock().getRelative(BlockFace.DOWN); + final Block space1 = l.getBlock(); + final Block space2 = l.getBlock().getRelative(BlockFace.UP); + //Bukkit.getLogger().info("DEBUG: ground = " + ground.getType()); + //Bukkit.getLogger().info("DEBUG: space 1 = " + space1.getType()); + //Bukkit.getLogger().info("DEBUG: space 2 = " + space2.getType()); + // Portals are not "safe" + if (space1.getType() == Material.PORTAL || ground.getType() == Material.PORTAL || space2.getType() == Material.PORTAL + || space1.getType() == Material.ENDER_PORTAL || ground.getType() == Material.ENDER_PORTAL || space2.getType() == Material.ENDER_PORTAL) { + return false; + } + // If ground is AIR, then this is either not good, or they are on slab, + // stair, etc. + if (ground.getType() == Material.AIR) { + // Bukkit.getLogger().info("DEBUG: air"); + return false; + } + // liquid may be unsafe + if (ground.getType().equals(Material.STATIONARY_LAVA) || ground.getType().equals(Material.LAVA) + || space1.getType().equals(Material.STATIONARY_LAVA) || space1.getType().equals(Material.LAVA) + || space2.getType().equals(Material.STATIONARY_LAVA) || space2.getType().equals(Material.LAVA)) { + // Lava check only + // Bukkit.getLogger().info("DEBUG: lava"); + return false; + } + + MaterialData md = ground.getState().getData(); + if (md instanceof SimpleAttachableMaterialData) { + //Bukkit.getLogger().info("DEBUG: trapdoor/button/tripwire hook etc."); + if (md instanceof TrapDoor) { + TrapDoor trapDoor = (TrapDoor)md; + if (trapDoor.isOpen()) { + //Bukkit.getLogger().info("DEBUG: trapdoor open"); + return false; + } + } else { + return false; + } + //Bukkit.getLogger().info("DEBUG: trapdoor closed"); + } + if (ground.getType().equals(Material.CACTUS) || ground.getType().equals(Material.BOAT) || ground.getType().equals(Material.FENCE) + || ground.getType().equals(Material.NETHER_FENCE) || ground.getType().equals(Material.SIGN_POST) || ground.getType().equals(Material.WALL_SIGN)) { + // Bukkit.getLogger().info("DEBUG: cactus"); + return false; + } + // Check that the space is not solid + // The isSolid function is not fully accurate (yet) so we have to + // check + // a few other items + // isSolid thinks that PLATEs and SIGNS are solid, but they are not + if (space1.getType().isSolid() && !space1.getType().equals(Material.SIGN_POST) && !space1.getType().equals(Material.WALL_SIGN)) { + return false; + } + if (space2.getType().isSolid()&& !space2.getType().equals(Material.SIGN_POST) && !space2.getType().equals(Material.WALL_SIGN)) { + return false; + } + // Safe + //Bukkit.getLogger().info("DEBUG: safe!"); + return true; + } + // Localization Strings + private HashMap availableLocales = new HashMap(); + // Listeners + private WarpSigns warpSignsListener; + // Island command object + private WarpCmd warpCmd; + // Warp panel + private WarpPanel warpPanel; + // Messages + private Messages messages; + private static WWarps plugin; + + + /** + * @return the messages + */ + public Messages getMessages() { + if (messages == null) { + messages = new Messages(this); + } + return messages; + } + + /** + * @return the warpPanel + */ + public WarpPanel getWarpPanel() { + if (warpPanel == null) { + // Probably due to a reload + warpPanel = new WarpPanel(this); + getServer().getPluginManager().registerEvents(warpPanel, this); + } + return warpPanel; + } + + + /** + * @return the warpSignsListener + */ + public WarpSigns getWarpSignsListener() { + return warpSignsListener; + } + + /** + * Loads the various settings from the config.yml file into the plugin + */ + public boolean loadPluginConfig() { + // getLogger().info("*********************************************"); + try { + getConfig(); + } catch (final Exception e) { + e.printStackTrace(); + } + //CompareConfigs.compareConfigs(); + // Get the localization strings + //getLocale(); + // Add this to the config + // Default is locale.yml + availableLocales.put("locale", new Locale(this, "locale")); + // Debug + Settings.debug = getConfig().getInt("debug", 0); + // Settings from config.yml + Settings.useWarpPanel = getConfig().getBoolean("usewarppanel", true); + Settings.worldName = getConfig().getStringList("signworlds"); + // All done + return true; + } + + /** + * @return System locale + */ + public Locale myLocale() { + return availableLocales.get("locale"); + } + + /* + * (non-Javadoc) + * @see org.bukkit.plugin.java.JavaPlugin#onDisable() + */ + @Override + public void onDisable() { + try { + // Save the warps and do not reload the panel + if (warpSignsListener != null) { + warpSignsListener.saveWarpList(false); + } + } catch (final Exception e) { + getLogger().severe("Something went wrong saving files!"); + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * @see org.bukkit.plugin.java.JavaPlugin#onEnable() + */ + @Override + public void onEnable() { + plugin = this; + saveDefaultConfig(); + // Load all the configuration of the plugin and localization strings + loadPluginConfig(); + // Set up commands for this plugin + warpCmd = new WarpCmd(this); + AdminCmd adminCmd = new AdminCmd(this); + + getCommand("wwarp").setExecutor(warpCmd); + getCommand("wwarp").setTabCompleter(warpCmd); + getCommand("wwadmin").setExecutor(adminCmd); + // Register events + registerEvents(); + // Have to do this a tick later to wait for all the worlds to load + getServer().getScheduler().runTask(this, new Runnable() { + + @Override + public void run() { + // Load warps + getWarpSignsListener().loadWarpList(); + // Load the warp panel + warpPanel = new WarpPanel(plugin); + getServer().getPluginManager().registerEvents(warpPanel, plugin); + }}); + } + + /** + * Registers events + */ + public void registerEvents() { + final PluginManager manager = getServer().getPluginManager(); + // Events for when a player joins or leaves the server + manager.registerEvents(new JoinLeaveEvents(this), this); + // Enables warp signs in ASkyBlock + warpSignsListener = new WarpSigns(this); + manager.registerEvents(warpSignsListener, this); + } + + public static WWarps getPlugin() { + return plugin; + } + +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/WarpSigns.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/WarpSigns.java new file mode 100644 index 0000000..4820070 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/WarpSigns.java @@ -0,0 +1,369 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; + +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.SignChangeEvent; + +import com.wasteofplastic.wwarps.util.Util; + +/** + * Handles warping in ASkyBlock Players can add one sign + * + * @author tastybento + * + */ +public class WarpSigns implements Listener { + private final WWarps plugin; + // Map of all warps stored as player, warp sign Location + private HashMap warpList = new HashMap(); + // Where warps are stored + private YamlConfiguration welcomeWarps; + + /** + * @param plugin + */ + public WarpSigns(WWarps plugin) { + this.plugin = plugin; + this.warpList = new HashMap(); + } + + /** + * Checks to see if a sign has been broken + * @param e + */ + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) + public void onSignBreak(BlockBreakEvent e) { + Block b = e.getBlock(); + Player player = e.getPlayer(); + if (Settings.worldName.isEmpty() || Settings.worldName.contains(b.getWorld().getName())) { + if (b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { + Sign s = (Sign) b.getState(); + if (s != null) { + //plugin.getLogger().info("DEBUG: sign found at location " + s.toString()); + if (s.getLine(0).equalsIgnoreCase(ChatColor.GREEN + plugin.myLocale().warpswelcomeLine)) { + // Do a quick check to see if this sign location is in + //plugin.getLogger().info("DEBUG: welcome sign"); + // the list of warp signs + if (warpList.containsValue(s.getLocation())) { + //plugin.getLogger().info("DEBUG: warp sign is in list"); + // Welcome sign detected - check to see if it is + // this player's sign + if ((warpList.containsKey(player.getUniqueId()) && warpList.get(player.getUniqueId()).equals(s.getLocation()))) { + // Player removed sign + removeWarp(s.getLocation()); + } else if (player.isOp() || player.hasPermission(Settings.PERMPREFIX + "admin")) { + // Op or mod removed sign + player.sendMessage(ChatColor.GREEN + plugin.myLocale().warpsremoved); + removeWarp(s.getLocation()); + } else { + // Someone else's sign - not allowed + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorNoRemove); + e.setCancelled(true); + } + } + } + } + } + } + } + + /** + * Event handler for Sign Changes + * + * @param e + */ + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) + public void onSignWarpCreate(SignChangeEvent e) { + //plugin.getLogger().info("DEBUG: SignChangeEvent called"); + String title = e.getLine(0); + Player player = e.getPlayer(); + //plugin.getLogger().info("DEBUG: The first line of the sign says " + title); + if (title.equalsIgnoreCase(plugin.myLocale().warpswelcomeLine)) { + //plugin.getLogger().info("DEBUG: Welcome sign detected"); + if (!Settings.worldName.isEmpty() && !Settings.worldName.contains(player.getWorld().getName())) { + //plugin.getLogger().info("DEBUG: Incorrect world"); + player.sendMessage(ChatColor.RED + plugin.myLocale().errorWrongWorld); + return; + } + // Welcome sign detected - check permissions + if (!player.hasPermission(Settings.PERMPREFIX + "add")) { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorNoPerm); + return; + } + plugin.getLogger().info("DEBUG: has permission"); + // Check if the player already has a sign + final Location oldSignLoc = getWarp(player.getUniqueId()); + if (oldSignLoc == null) { + //plugin.getLogger().info("DEBUG: Player does not have a sign already"); + // First time the sign has been placed or this is a new + // sign + if (addWarp(player.getUniqueId(), e.getBlock().getLocation())) { + player.sendMessage(ChatColor.GREEN + plugin.myLocale().warpssuccess); + e.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); + for (int i = 1; i<4; i++) { + e.setLine(i, ChatColor.translateAlternateColorCodes('&', e.getLine(i))); + } + } else { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorDuplicate); + e.setLine(0, ChatColor.RED + plugin.myLocale().warpswelcomeLine); + for (int i = 1; i<4; i++) { + e.setLine(i, ChatColor.translateAlternateColorCodes('&', e.getLine(i))); + } + } + } else { + //plugin.getLogger().info("DEBUG: Player already has a Sign"); + // A sign already exists. Check if it still there and if + // so, + // deactivate it + Block oldSignBlock = oldSignLoc.getBlock(); + if (oldSignBlock.getType().equals(Material.SIGN_POST) || oldSignBlock.getType().equals(Material.WALL_SIGN)) { + // The block is still a sign + //plugin.getLogger().info("DEBUG: The block is still a sign"); + Sign oldSign = (Sign) oldSignBlock.getState(); + if (oldSign != null) { + //plugin.getLogger().info("DEBUG: Sign block is a sign"); + if (oldSign.getLine(0).equalsIgnoreCase(ChatColor.GREEN + plugin.myLocale().warpswelcomeLine)) { + //plugin.getLogger().info("DEBUG: Old sign had a green welcome"); + oldSign.setLine(0, ChatColor.RED + plugin.myLocale().warpswelcomeLine); + oldSign.update(); + player.sendMessage(ChatColor.RED + plugin.myLocale().warpsdeactivate); + removeWarp(player.getUniqueId()); + } + } + } + // Set up the warp + if (addWarp(player.getUniqueId(), e.getBlock().getLocation())) { + player.sendMessage(ChatColor.GREEN + plugin.myLocale().warpssuccess); + e.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); + } else { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorDuplicate); + e.setLine(0, ChatColor.RED + plugin.myLocale().warpswelcomeLine); + } + } + } + } + + /** + * Saves the warp lists to file + */ + public void saveWarpList(boolean reloadPanel) { + if (warpList == null || welcomeWarps == null) { + return; + } + //plugin.getLogger().info("Saving warps..."); + final HashMap warps = new HashMap(); + for (UUID p : warpList.keySet()) { + warps.put(p.toString(), Util.getStringLocation(warpList.get(p))); + } + welcomeWarps.set("warps", warps); + Util.saveYamlFile(welcomeWarps, "warps.yml"); + // Update the warp panel - needs to be done 1 tick later so that the sign + // text will be updated. + if (reloadPanel) { + // This is not done on shutdown + if (plugin.getWarpPanel() != null) { + plugin.getServer().getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + plugin.getWarpPanel().updatePanel(); + }}); + } + } + //plugin.getLogger().info("End of saving warps"); + } + + /** + * Creates the warp list if it does not exist + */ + public void loadWarpList() { + plugin.getLogger().info("Loading warps..."); + // warpList.clear(); + welcomeWarps = Util.loadYamlFile("warps.yml"); + if (welcomeWarps.getConfigurationSection("warps") == null) { + welcomeWarps.createSection("warps"); // This is only used to create + // the warp.yml file so forgive + // this code + } + HashMap temp = (HashMap) welcomeWarps.getConfigurationSection("warps").getValues(true); + for (String s : temp.keySet()) { + try { + UUID playerUUID = UUID.fromString(s); + plugin.getLogger().info("DEBUG: Player UUID = " + playerUUID); + plugin.getLogger().info("DEBUG: text loc = " + (String) temp.get(s)); + Location l = Util.getLocationString((String) temp.get(s)); + plugin.getLogger().info("DEBUG: Loading warp at " + l); + Block b = l.getBlock(); + // Check that a warp sign is still there + if (b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { + warpList.put(playerUUID, l); + } else { + plugin.getLogger().warning("Warp at location " + temp.get(s) + " has no sign - removing."); + } + } catch (Exception e) { + plugin.getLogger().severe("Problem loading warp at location " + temp.get(s) + " - removing."); + e.printStackTrace(); + } + } + } + + /** + * Stores warps in the warp array + * + * @param player + * @param loc + */ + public boolean addWarp(UUID player, Location loc) { + // Do not allow warps to be in the same location + if (warpList.containsValue(loc)) { + return false; + } + // Remove the old warp if it existed + if (warpList.containsKey(player)) { + warpList.remove(player); + } + warpList.put(player, loc); + saveWarpList(true); + return true; + } + + /** + * Removes a warp when the welcome sign is destroyed. Called by + * WarpSigns.java. + * + * @param uuid + */ + public void removeWarp(UUID uuid) { + if (warpList.containsKey(uuid)) { + popSign(warpList.get(uuid)); + warpList.remove(uuid); + } + saveWarpList(true); + } + + /** + * Changes the sign to red if it exists + * @param loc + */ + private void popSign(Location loc) { + Block b = loc.getBlock(); + if (b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { + Sign s = (Sign) b.getState(); + if (s != null) { + if (s.getLine(0).equalsIgnoreCase(ChatColor.GREEN + plugin.myLocale().warpswelcomeLine)) { + s.setLine(0, ChatColor.RED + plugin.myLocale().warpswelcomeLine); + s.update(); + } + } + } + } + + /** + * Removes a warp at a location. Called by WarpSigns.java. + * + * @param loc + */ + public void removeWarp(Location loc) { + //plugin.getLogger().info("Asked to remove warp at " + loc); + popSign(loc); + Iterator> it = warpList.entrySet().iterator(); + while (it.hasNext()) { + Entry en = it.next(); + if (en.getValue().equals(loc)) { + // Inform player + Player p = plugin.getServer().getPlayer(en.getKey()); + if (p != null) { + // Inform the player + p.sendMessage(ChatColor.RED + plugin.myLocale().warpssignRemoved); + } else { + plugin.getMessages().setMessage(en.getKey(), ChatColor.RED + plugin.myLocale().warpssignRemoved); + } + it.remove(); + } + } + saveWarpList(true); + } + + /** + * Lists all the known warps + * + * @return String set of warps + */ + public Set listWarps() { + return warpList.keySet(); + } + + /** + * @return Sorted list of warps with most recent players listed first + */ + public Collection listSortedWarps() { + // Bigger value of time means a more recent login + TreeMap map = new TreeMap(); + for (UUID uuid : warpList.keySet()) { + map.put(plugin.getServer().getOfflinePlayer(uuid).getLastPlayed(), uuid); + } + Collection result = map.descendingMap().values(); + return result; + } + /** + * Provides the location of the warp for player or null if one is not found + * + * @param player + * - the warp requested + * @return Location of warp + */ + public Location getWarp(UUID player) { + if (warpList.containsKey(player)) { + return warpList.get(player); + } else { + return null; + } + } + + /** + * @param location + * @return Name of warp owner + */ + public String getWarpOwner(Location location) { + for (UUID playerUUID : warpList.keySet()) { + if (location.equals(warpList.get(playerUUID))) { + return plugin.getServer().getOfflinePlayer(playerUUID).getName(); + } + } + return ""; + } + +} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/AdminCmd.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/AdminCmd.java new file mode 100644 index 0000000..cf406e1 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/AdminCmd.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ + +package com.wasteofplastic.wwarps.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; + +import com.wasteofplastic.wwarps.Settings; +import com.wasteofplastic.wwarps.WWarps; + +/** + * This class handles admin commands + * + */ +public class AdminCmd implements CommandExecutor { + private WWarps plugin; + public AdminCmd(WWarps aSkyBlock) { + this.plugin = aSkyBlock; + } + + /* + * (non-Javadoc) + * @see + * org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender + * , org.bukkit.command.Command, java.lang.String, java.lang.String[]) + */ + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] split) { + // Console commands + Player player; + if (sender instanceof Player) { + player = (Player) sender; + if (!player.hasPermission(Settings.PERMPREFIX + "admin")) { + player.sendMessage(ChatColor.RED + plugin.myLocale().errorNoPermission); + return true; + } + } + if (split.length == 0) { + sender.sendMessage(plugin.myLocale().adminHelpHelp); + sender.sendMessage(ChatColor.YELLOW + "/" + label + " reload:" + ChatColor.WHITE + " " + plugin.myLocale().adminHelpreload); + return true; + } + if (split.length == 1) { + if (split[0].equalsIgnoreCase("reload")) { + // reload + plugin.reloadConfig(); + plugin.loadPluginConfig(); + sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().reloadconfigReloaded); + return true; + } else { + sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); + return true; + } + } + sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); + return true; + } +} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/WarpCmd.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/WarpCmd.java new file mode 100644 index 0000000..e6de72c --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/commands/WarpCmd.java @@ -0,0 +1,282 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps.commands; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Sign; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; + +import com.wasteofplastic.wwarps.Settings; +import com.wasteofplastic.wwarps.WWarps; +import com.wasteofplastic.wwarps.util.Util; + +public class WarpCmd implements CommandExecutor, TabCompleter { + private WWarps plugin; + /** + * Constructor + * + * @param aSkyBlock + * @param players + */ + public WarpCmd(WWarps aSkyBlock) { + // Plugin instance + this.plugin = aSkyBlock; + } + + /** + * One-to-one relationship, you can return the first matched key + * + * @param map + * @param value + * @return + */ + public static T getKeyByValue(Map map, E value) { + for (Entry entry : map.entrySet()) { + if (value.equals(entry.getValue())) { + return entry.getKey(); + } + } + return null; + } + + /* + * (non-Javadoc) + * @see + * org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender + * , org.bukkit.command.Command, java.lang.String, java.lang.String[]) + */ + @Override + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] split) { + if (!(sender instanceof Player)) { + return false; + } + final Player player = (Player) sender; + final UUID playerUUID = player.getUniqueId(); + if (label.equalsIgnoreCase("wwarps")) { + if (player.hasPermission(Settings.PERMPREFIX + "use")) { + if (Settings.useWarpPanel) { + // Step through warp table + Set warpList = plugin.getWarpSignsListener().listWarps(); + if (warpList.isEmpty()) { + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpserrorNoWarpsYet); + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpswarpTip); + return true; + } else { + // Try the warp panel + int panelNum = 0; + try { + panelNum = Integer.valueOf(split[0]) - 1; + } catch (Exception e) { + panelNum = 0; + } + player.openInventory(plugin.getWarpPanel().getWarpPanel(panelNum)); + return true; + } + } else { + // Step through warp table + Collection warpList = plugin.getWarpSignsListener().listWarps(); + if (warpList.isEmpty()) { + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpserrorNoWarpsYet); + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpswarpTip); + return true; + } else { + if (Settings.useWarpPanel) { + // Try the warp panel + player.openInventory(plugin.getWarpPanel().getWarpPanel(0)); + } else { + Boolean hasWarp = false; + String wlist = ""; + for (UUID w : warpList) { + if (wlist.isEmpty()) { + wlist = plugin.getServer().getOfflinePlayer(w).getName(); + } else { + wlist += ", " + plugin.getServer().getOfflinePlayer(w).getName(); + } + if (w.equals(playerUUID)) { + hasWarp = true; + } + } + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpswarpsAvailable + ": " + ChatColor.WHITE + wlist); + if (!hasWarp && (player.hasPermission(Settings.PERMPREFIX + "addwarp"))) { + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpswarpTip); + } + } + return true; + } + } + } else { + player.sendMessage(ChatColor.RED + plugin.myLocale().errorNoPermission); + return true; + } + } + if (label.equalsIgnoreCase("wwarp")) { + switch (split.length) { + case 1: + // Warp somewhere command + if (!player.hasPermission(Settings.PERMPREFIX + "use")) { + player.sendMessage(ChatColor.RED + plugin.myLocale().errorNoPermission); + return true; + } + final Set warpList = plugin.getWarpSignsListener().listWarps(); + if (warpList.isEmpty()) { + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpserrorNoWarpsYet); + if (player.hasPermission(Settings.PERMPREFIX + "add")) { + player.sendMessage(ChatColor.YELLOW + plugin.myLocale().warpswarpTip); + } else { + player.sendMessage(ChatColor.RED + plugin.myLocale().errorNoPermission); + } + return true; + } else { + // Check if this is part of a name + UUID foundWarp = null; + for (UUID warp : warpList) { + if (plugin.getServer().getOfflinePlayer(warp).getName().toLowerCase().startsWith(split[0].toLowerCase())) { + foundWarp = warp; + break; + } + } + if (foundWarp == null) { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorDoesNotExist); + return true; + } else { + // Warp exists! + final Location warpSpot = plugin.getWarpSignsListener().getWarp(foundWarp); + // Check if the warp spot is safe + if (warpSpot == null) { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorNotReadyYet); + plugin.getLogger().warning("Null warp found, owned by " + plugin.getServer().getOfflinePlayer(foundWarp).getName()); + return true; + } + // Find out which direction the warp is facing + Block b = warpSpot.getBlock(); + if (b.getType().equals(Material.SIGN_POST) || b.getType().equals(Material.WALL_SIGN)) { + Sign sign = (Sign) b.getState(); + org.bukkit.material.Sign s = (org.bukkit.material.Sign) sign.getData(); + BlockFace directionFacing = s.getFacing(); + Location inFront = b.getRelative(directionFacing).getLocation(); + Location oneDown = b.getRelative(directionFacing).getRelative(BlockFace.DOWN).getLocation(); + if ((WWarps.isSafeLocation(inFront))) { + warpPlayer(player, inFront, foundWarp, directionFacing); + return true; + } else if (b.getType().equals(Material.WALL_SIGN) && WWarps.isSafeLocation(oneDown)) { + // Try one block down if this is a wall sign + warpPlayer(player, oneDown, foundWarp, directionFacing); + return true; + } + } else { + // Warp has been removed + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorDoesNotExist); + plugin.getWarpSignsListener().removeWarp(warpSpot); + return true; + } + if (!(WWarps.isSafeLocation(warpSpot))) { + player.sendMessage(ChatColor.RED + plugin.myLocale().warpserrorNotSafe); + // WALL_SIGN's will always be unsafe if the place in front is obscured. + if (b.getType().equals(Material.SIGN_POST)) { + plugin.getLogger().warning( + "Unsafe warp found at " + warpSpot.toString() + " owned by " + plugin.getServer().getOfflinePlayer(foundWarp).getName()); + } + return true; + } else { + final Location actualWarp = new Location(warpSpot.getWorld(), warpSpot.getBlockX() + 0.5D, warpSpot.getBlockY(), + warpSpot.getBlockZ() + 0.5D); + player.teleport(actualWarp); + player.getWorld().playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1F, 1F); + + return true; + } + } + } + default: + player.performCommand("wwarps"); + return true; + } + } + return false; + } + + + /** + * Warps a player to a spot in front of a sign + * @param player + * @param inFront + * @param foundWarp + * @param directionFacing + */ + private void warpPlayer(Player player, Location inFront, UUID foundWarp, BlockFace directionFacing) { + // convert blockface to angle + float yaw = Util.blockFaceToFloat(directionFacing); + final Location actualWarp = new Location(inFront.getWorld(), inFront.getBlockX() + 0.5D, inFront.getBlockY(), + inFront.getBlockZ() + 0.5D, yaw, 30F); + player.teleport(actualWarp); + player.getWorld().playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1F, 1F); + Player warpOwner = plugin.getServer().getPlayer(foundWarp); + if (warpOwner != null && !warpOwner.equals(player)) { + warpOwner.sendMessage(plugin.myLocale().warpsPlayerWarped.replace("[name]", player.getDisplayName())); + } + } + + @Override + public List onTabComplete(final CommandSender sender, final Command command, final String label, final String[] args) { + final List options = new ArrayList(); + if (!(sender instanceof Player)) { + //plugin.getLogger().info("DEBUG: not a player"); + return options; + } + if (!label.equalsIgnoreCase("wwarp")) { + //plugin.getLogger().info("DEBUG: not right command"); + return options; + } + final Player player = (Player) sender; + if (!player.hasPermission(Settings.PERMPREFIX + "use")) { + //plugin.getLogger().info("DEBUG: not right permission"); + return options; + } + String lastArg = (args.length != 0 ? args[args.length - 1] : ""); + //plugin.getLogger().info("DEBUG: args length = " + args.length); + switch (args.length) { + case 1: + final Set warpList = plugin.getWarpSignsListener().listWarps(); + //plugin.getLogger().info("DEBUG: warp list = " + warpList); + for (UUID warp : warpList) { + //plugin.getLogger().info("DEBUG: adding " + plugin.getServer().getOfflinePlayer(warp).getName()); + options.add(plugin.getServer().getOfflinePlayer(warp).getName()); + } + break; + default: + break; + } + return Util.tabLimit(options, lastArg); + } +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/listeners/JoinLeaveEvents.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/listeners/JoinLeaveEvents.java new file mode 100644 index 0000000..44c8e17 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/listeners/JoinLeaveEvents.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps.listeners; + +import java.util.List; +import java.util.UUID; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +import com.wasteofplastic.wwarps.WWarps; + +public class JoinLeaveEvents implements Listener { + private WWarps plugin; + + public JoinLeaveEvents(WWarps plugin) { + this.plugin = plugin; + } + + /** + * @param event + */ + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerJoin(final PlayerJoinEvent event) { + final Player player = event.getPlayer(); + final UUID playerUUID = player.getUniqueId(); + // Load any messages for the player + // plugin.getLogger().info("DEBUG: Checking messages for " + + // player.getName()); + final List messages = plugin.getMessages().getMessages(playerUUID); + if (messages != null) { + // plugin.getLogger().info("DEBUG: Messages waiting!"); + plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() { + @Override + public void run() { + player.sendMessage(ChatColor.AQUA + plugin.myLocale().newsHeadline); + int i = 1; + for (String message : messages) { + player.sendMessage(i++ + ": " + message); + } + // Clear the messages + plugin.getMessages().clearMessages(playerUUID); + } + }, 40L); + } // else { + // plugin.getLogger().info("no messages"); + // } + } +} \ No newline at end of file diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/CPItem.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/CPItem.java new file mode 100644 index 0000000..409643e --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/CPItem.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * This file is part of ASkyBlock. + * + * ASkyBlock is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ASkyBlock is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with ASkyBlock. If not, see . + *******************************************************************************/ +package com.wasteofplastic.wwarps.panels; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +/** + * @author tastybento + * This class is for a control panel button that has an icon, a command + * to run if pressed or a link to + * another control panel. + */ +public class CPItem { + + private ItemStack item; + private String command; + private String nextSection; + + /** + * @param item + * @param material + * @param name + * @param command + * @param nextSection + */ + public CPItem(Material material, String name, String command, String nextSection) { + this.command = command; + this.nextSection = nextSection; + item = new ItemStack(material); + ItemMeta meta = item.getItemMeta(); + // Handle multi line names (split by |) + List desc = new ArrayList(Arrays.asList(name.split("\\|"))); + meta.setDisplayName(desc.get(0)); + if (desc.size() > 1) { + desc.remove(0); // Remove the name + meta.setLore(desc); + } + item.setItemMeta(meta); + } + + public CPItem(ItemStack itemStack, String name, String command, String nextSection) { + this.command = command; + this.nextSection = nextSection; + this.item = itemStack; + ItemMeta meta = item.getItemMeta(); + // Handle multi line names (split by |) + List desc = new ArrayList(Arrays.asList(name.split("\\|"))); + meta.setDisplayName(desc.get(0)); + if (desc.size() > 1) { + desc.remove(0); // Remove the name + meta.setLore(desc); + } + item.setItemMeta(meta); + } + + // For warps + public CPItem(ItemStack itemStack, String command) { + this.command = command; + this.nextSection = ""; + this.item = itemStack; + } + + public void setLore(List lore) { + ItemMeta meta = item.getItemMeta(); + meta.setLore(lore); + item.setItemMeta(meta); + } + + /** + * @return the command + */ + public String getCommand() { + return command; + } + + /** + * @return the nextSection + */ + public String getNextSection() { + return nextSection; + } + + /** + * @param nextSection + * the nextSection to set + */ + public void setNextSection(String nextSection) { + this.nextSection = nextSection; + } + + public ItemStack getItem() { + return item; + } + +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/WarpPanel.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/WarpPanel.java new file mode 100644 index 0000000..9df423b --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/panels/WarpPanel.java @@ -0,0 +1,179 @@ +package com.wasteofplastic.wwarps.panels; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import com.wasteofplastic.wwarps.WWarps; + +public class WarpPanel implements Listener { + private WWarps plugin; + private List warpPanel; + + /** + * @param plugin + */ + public WarpPanel(WWarps plugin) { + this.plugin = plugin; + warpPanel = new ArrayList(); + updatePanel(); + } + + /** + * This needs to be called if a warp is added or deleted + */ + public void updatePanel() { + warpPanel.clear(); + int panelSize = 45; // Must be a multiple of 9 + // Create the warp panels + Collection warps = plugin.getWarpSignsListener().listSortedWarps(); + //plugin.getLogger().info("DEBUG: warps size = " + warps.size()); + int panelNumber = warps.size() / (panelSize-2); + int remainder = (warps.size() % (panelSize-2)) + 8 + 2; + remainder -= (remainder % 9); + //plugin.getLogger().info("DEBUG: panel number = " + panelNumber + " remainder = " + remainder); + int i = 0; + // TODO: Make panel title a string + for (i = 0; i < panelNumber; i++) { + //plugin.getLogger().info("DEBUG: created panel " + (i+1)); + warpPanel.add(Bukkit.createInventory(null, panelSize, plugin.myLocale().warpsTitle + " #" + (i+1))); + } + // Make the last panel + //plugin.getLogger().info("DEBUG: created panel " + (i+1)); + warpPanel.add(Bukkit.createInventory(null, remainder, plugin.myLocale().warpsTitle + " #" + (i+1))); + panelNumber = 0; + int slot = 0; + int count = 0; + // Add this buttons to each panel + for (UUID playerUUID : warps) { + count++; + // Make a head if the player is known + String playerName = plugin.getServer().getOfflinePlayer(playerUUID).getName(); + if (playerName != null) { + ItemStack playerSkull = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + SkullMeta meta = (SkullMeta) playerSkull.getItemMeta(); + meta.setOwner(playerName); + meta.setDisplayName(playerName); + //get the sign info + Location signLocation = plugin.getWarpSignsListener().getWarp(playerUUID); + //plugin.getLogger().info("DEBUG: " + playerName + ": block type = " + signLocation.getBlock().getType()); + if (signLocation.getBlock().getType().equals(Material.SIGN_POST) || signLocation.getBlock().getType().equals(Material.WALL_SIGN)) { + Sign sign = (Sign)signLocation.getBlock().getState(); + List lines = new ArrayList(Arrays.asList(sign.getLines())); + meta.setLore(lines); + //plugin.getLogger().info("DEBUG: " + playerName + ": lines = " + lines); + } + /* else // TEST CODE + if (signLocation.getBlock().getType().equals(Material.AIR)) { + signLocation.getBlock().getRelative(BlockFace.DOWN).setType(Material.BEDROCK); + signLocation.getBlock().setType(Material.SIGN_POST); + Sign sign = (Sign)signLocation.getBlock().getState(); + for (int line = 0; line < 4; line++) { + sign.setLine(line, "Line #" + line); + } + sign.update(); + }*/ + + playerSkull.setItemMeta(meta); + // Add item to the panel + //plugin.getLogger().info("DEBUG: adding item to panel number = " + panelNumber + " slot = " + slot); + CPItem newButton = new CPItem(playerSkull, "wwarp " + playerName); + warpPanel.get(panelNumber).setItem(slot++, newButton.getItem()); + } else { + // Just make a blank space + //warpPanel.get(panelNumber).setItem(slot, new ItemStack(Material.AIR)); + // TEST CODE + ItemStack playerSkull = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); + SkullMeta meta = (SkullMeta) playerSkull.getItemMeta(); + meta.setDisplayName("#" + count); + playerSkull.setItemMeta(meta); + warpPanel.get(panelNumber).setItem(slot++,playerSkull); + } + // Check if the panel is full + if (slot == panelSize-2) { + // Add navigation buttons + if (panelNumber > 0) { + warpPanel.get(panelNumber).setItem(slot++, new CPItem(Material.SIGN,plugin.myLocale().warpsPrevious,"warps " + (panelNumber-1),"").getItem()); + } + warpPanel.get(panelNumber).setItem(slot, new CPItem(Material.SIGN,plugin.myLocale().warpsNext,"warps " + (panelNumber+1),"").getItem()); + // Move onto the next panel + panelNumber++; + slot = 0; + } + } + if (remainder != 0 && panelNumber > 0) { + warpPanel.get(panelNumber).setItem(slot++, new CPItem(Material.SIGN,plugin.myLocale().warpsPrevious,"warps " + (panelNumber-1),"").getItem()); + } + } + + public Inventory getWarpPanel(int panelNumber) { + //makePanel(); + if (panelNumber < 0) { + panelNumber = 0; + } else if (panelNumber > warpPanel.size()-1) { + panelNumber = warpPanel.size()-1; + } + return warpPanel.get(panelNumber); + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) + public void onInventoryClick(InventoryClickEvent event) { + Inventory inventory = event.getInventory(); // The inventory that was clicked in + String title = inventory.getTitle(); + if (!inventory.getTitle().startsWith(plugin.myLocale().warpsTitle + " #")) { + return; + } + // The player that clicked the item + Player player = (Player) event.getWhoClicked(); + event.setCancelled(true); + if (event.getSlotType().equals(SlotType.OUTSIDE)) { + player.closeInventory(); + return; + } + ItemStack clicked = event.getCurrentItem(); // The item that was clicked + //plugin.getLogger().info("DEBUG: inventory size = " + inventory.getSize()); + //plugin.getLogger().info("DEBUG: clicked = " + clicked); + //plugin.getLogger().info("DEBUG: rawslot = " + event.getRawSlot()); + if (event.getRawSlot() >= event.getInventory().getSize() || clicked.getType() == Material.AIR) { + return; + } + int panelNumber = 0; + try { + panelNumber = Integer.valueOf(title.substring(title.indexOf('#')+ 1)); + } catch (Exception e) { + panelNumber = 0; + } + String command = clicked.getItemMeta().getDisplayName(); + //plugin.getLogger().info("DEBUG: command = " + command); + if (command != null) { + if (command.equalsIgnoreCase(plugin.myLocale().warpsNext)) { + player.closeInventory(); + player.performCommand("wwarps " + (panelNumber+1)); + } else if (command.equalsIgnoreCase(plugin.myLocale().warpsPrevious)) { + player.closeInventory(); + player.performCommand("wwarps " + (panelNumber-1)); + } else { + player.closeInventory(); + player.sendMessage(ChatColor.GREEN + plugin.myLocale().warpswarpToPlayersSign.replace("", command)); + player.performCommand("wwarp " + command); + } + } + } +} diff --git a/WelcomeWarps/src/com/wasteofplastic/wwarps/util/Util.java b/WelcomeWarps/src/com/wasteofplastic/wwarps/util/Util.java new file mode 100644 index 0000000..dc88d18 --- /dev/null +++ b/WelcomeWarps/src/com/wasteofplastic/wwarps/util/Util.java @@ -0,0 +1,269 @@ +package com.wasteofplastic.wwarps.util; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.BlockFace; +import org.bukkit.configuration.file.YamlConfiguration; + +import com.wasteofplastic.wwarps.WWarps; + +/** + * A set of utility methods + * + * @author tastybento + * + */ +public class Util { + private static WWarps plugin = WWarps.getPlugin(); + + /** + * Loads a YAML file and if it does not exist it is looked for in the JAR + * + * @param file + * @return + */ + public static YamlConfiguration loadYamlFile(String file) { + File dataFolder = plugin.getDataFolder(); + File yamlFile = new File(dataFolder, file); + + YamlConfiguration config = null; + if (yamlFile.exists()) { + try { + config = new YamlConfiguration(); + config.load(yamlFile); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + // Create the missing file + config = new YamlConfiguration(); + plugin.getLogger().info("No " + file + " found. Creating it..."); + try { + if (plugin.getResource(file) != null) { + plugin.getLogger().info("Using default found in jar file."); + plugin.saveResource(file, false); + config = new YamlConfiguration(); + config.load(yamlFile); + } else { + config.save(yamlFile); + } + } catch (Exception e) { + plugin.getLogger().severe("Could not create the " + file + " file!"); + } + } + return config; + } + + /** + * Saves a YAML file + * + * @param yamlFile + * @param fileLocation + */ + public static void saveYamlFile(YamlConfiguration yamlFile, String fileLocation) { + File dataFolder = plugin.getDataFolder(); + File file = new File(dataFolder, fileLocation); + + try { + yamlFile.save(file); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Cuts up a string into multiple lines with the same color code at the + * start of each line + * + * @param color + * @param longLine + * @param length + * @return List containing the colored lines + */ + public static List chop(ChatColor color, String longLine, int length) { + List result = new ArrayList(); + // int multiples = longLine.length() / length; + int i = 0; + for (i = 0; i < longLine.length(); i += length) { + // for (int i = 0; i< (multiples*length); i += length) { + int endIndex = Math.min(i + length, longLine.length()); + String line = longLine.substring(i, endIndex); + // Do the following only if i+length is not the end of the string + if (endIndex < longLine.length()) { + // Check if last character in this string is not a space + if (!line.substring(line.length() - 1).equals(" ")) { + // If it is not a space, check to see if the next character + // in long line is a space. + if (!longLine.substring(endIndex, endIndex + 1).equals(" ")) { + // If it is not, then we are cutting a word in two and + // need to backtrack to the last space if possible + int lastSpace = line.lastIndexOf(" "); + // Only do this if there is a space in the line to + // backtrack to... + if (lastSpace != -1 && lastSpace < line.length()) { + line = line.substring(0, lastSpace); + i -= (length - lastSpace - 1); + } + } + } + } + // } + result.add(color + line); + } + // result.add(color + longLine.substring(i, longLine.length())); + return result; + } + + /** + * Converts block face direction to radial degrees. Returns 0 if block face + * is not radial. + * + * @param face + * @return degrees + */ + public static float blockFaceToFloat(BlockFace face) { + switch (face) { + case EAST: + return 90F; + case EAST_NORTH_EAST: + return 67.5F; + case EAST_SOUTH_EAST: + return 0F; + case NORTH: + return 0F; + case NORTH_EAST: + return 45F; + case NORTH_NORTH_EAST: + return 22.5F; + case NORTH_NORTH_WEST: + return 337.5F; + case NORTH_WEST: + return 315F; + case SOUTH: + return 180F; + case SOUTH_EAST: + return 135F; + case SOUTH_SOUTH_EAST: + return 157.5F; + case SOUTH_SOUTH_WEST: + return 202.5F; + case SOUTH_WEST: + return 225F; + case WEST: + return 270F; + case WEST_NORTH_WEST: + return 292.5F; + case WEST_SOUTH_WEST: + return 247.5F; + default: + return 0F; + } + } + + /** + * Converts a name like IRON_INGOT into Iron Ingot to improve readability + * + * @param ugly + * The string such as IRON_INGOT + * @return A nicer version, such as Iron Ingot + * + * Credits to mikenon on GitHub! + */ + public static String prettifyText(String ugly) { + if (!ugly.contains("_") && (!ugly.equals(ugly.toUpperCase()))) + return ugly; + String fin = ""; + ugly = ugly.toLowerCase(); + if (ugly.contains("_")) { + String[] splt = ugly.split("_"); + int i = 0; + for (String s : splt) { + i += 1; + fin += Character.toUpperCase(s.charAt(0)) + s.substring(1); + if (i < splt.length) + fin += " "; + } + } else { + fin += Character.toUpperCase(ugly.charAt(0)) + ugly.substring(1); + } + return fin; + } + + /** + * Converts a serialized location to a Location. Returns null if string is + * empty + * + * @param s + * - serialized location in format "world:x:y:z" + * @return Location + */ + static public Location getLocationString(final String s) { + if (s == null || s.trim() == "") { + return null; + } + final String[] parts = s.split(":"); + if (parts.length == 4) { + final World w = Bukkit.getServer().getWorld(parts[0]); + if (w == null) { + plugin.getLogger().info("DEBUG: world is null"); + return null; + } + final int x = Integer.parseInt(parts[1]); + final int y = Integer.parseInt(parts[2]); + final int z = Integer.parseInt(parts[3]); + return new Location(w, x, y, z); + } else if (parts.length == 6) { + final World w = Bukkit.getServer().getWorld(parts[0]); + if (w == null) { + return null; + } + final int x = Integer.parseInt(parts[1]); + final int y = Integer.parseInt(parts[2]); + final int z = Integer.parseInt(parts[3]); + final float yaw = Float.intBitsToFloat(Integer.parseInt(parts[4])); + final float pitch = Float.intBitsToFloat(Integer.parseInt(parts[5])); + return new Location(w, x, y, z, yaw, pitch); + } + return null; + } + + /** + * Converts a location to a simple string representation + * If location is null, returns empty string + * + * @param l + * @return + */ + static public String getStringLocation(final Location l) { + if (l == null || l.getWorld() == null) { + return ""; + } + return l.getWorld().getName() + ":" + l.getBlockX() + ":" + l.getBlockY() + ":" + l.getBlockZ() + ":" + Float.floatToIntBits(l.getYaw()) + ":" + Float.floatToIntBits(l.getPitch()); + } + + /** + * Returns all of the items that begin with the given start, + * ignoring case. Intended for tabcompletion. + * + * @param list + * @param start + * @return + */ + public static List tabLimit(final List list, final String start) { + final List returned = new ArrayList(); + for (String s : list) { + if (s.toLowerCase().startsWith(start.toLowerCase())) { + returned.add(s); + } + } + + return returned; + } + +}