Skip to content

Commit

Permalink
More commands for more events, update checker
Browse files Browse the repository at this point in the history
  • Loading branch information
KartoffelChipss committed Mar 27, 2024
1 parent e9cc588 commit 7b54c0c
Show file tree
Hide file tree
Showing 14 changed files with 179 additions and 25 deletions.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ Here is an example of the configuration file:
# https://docs.advntr.dev/minimessage/format.html
# With these, you can also add HEX colors, gradients, hover and click events, etc

checkForUpdates: true

#A list of worlds, where the plugin should take effect
worlds:
- "world"
Expand Down Expand Up @@ -116,10 +118,19 @@ preventCrystalPVP: false
disablePlayerBanOnElimination: false
# The amount of hp a player should have after getting eliminated
respawnHP: 10
# The command that should be executed when a player gets eliminated

# Execute custom commands on events:
# You can use &player& to insert the player name
# For example: tempban &player& banreason 1d
eliminationCommand: say &player& got eliminated
eliminationCommands:
# - "say &player& got eliminated"
# - "niceCommandtwo"

heartuseCommands:
# - "say &player& used a heart item"

reviveuseCommands:
# - "say &player& revived &target&"

#Here you can modify everything about the custom items
items:
Expand Down Expand Up @@ -173,6 +184,7 @@ items:
#You can modify all messages here
messages:
prefix: "&8[&cLifeStealZ&8]"
newVersionAvailable: "&7A new version of LifeStealZ is available!\n&c<click:OPEN_URL:https://modrinth.com/plugin/lifestealz/versions>https://modrinth.com/plugin/lifestealz/versions</click>"
usageError: "&cUsage: %usage%"
noPermissionError: "&cYou don't have permission to use this!"
noPlayerData: "&cThis player has not played on this server yet!"
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>org.strassburger</groupId>
<artifactId>lifestealz</artifactId>
<version>1.0.8</version>
<version>1.0.9</version>
<packaging>jar</packaging>

<name>lifestealz</name>
Expand Down
121 changes: 118 additions & 3 deletions src/main/java/org/strassburger/lifestealz/Lifestealz.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@ import org.bukkit.entity.Player
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ShapedRecipe
import org.bukkit.plugin.java.JavaPlugin
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import org.strassburger.lifestealz.commands.EliminateCommand
import org.strassburger.lifestealz.commands.ReviveCommand
import org.strassburger.lifestealz.commands.SettingsCommand
import org.strassburger.lifestealz.commands.WithdrawCommand
import org.strassburger.lifestealz.listener.*
import org.strassburger.lifestealz.util.*
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.util.*


class Lifestealz : JavaPlugin() {
companion object {
lateinit var instance: Lifestealz
Expand All @@ -40,6 +44,9 @@ class Lifestealz : JavaPlugin() {
val HEART_KEY = NamespacedKey("lifesetalz", "heart")
val REVIVEITEM_KEY = NamespacedKey("lifesetalz", "reviveitem")

val MODRINTH_PROJECT_URL = "https://api.modrinth.com/v2/project/l8Uv7FzS"
var NEW_VERSION_AVAILABLE : Boolean = false

private val colorMap = mapOf(
"&0" to "<black>",
"&1" to "<dark_blue>",
Expand Down Expand Up @@ -135,6 +142,14 @@ class Lifestealz : JavaPlugin() {
logger.info("PlaceholderAPI found! Enabled PlaceholderAPI support!")
}

if (config.getBoolean("checkForUpdates")) {
val modrinthVersion = getLatestVersionFromModrinth()
if (modrinthVersion != null && modrinthVersion.trim().lowercase() != description.version.trim().lowercase()) {
logger.info("A new version of LifestealZ is available! Version: $modrinthVersion\nDownload the latest version here: https://modrinth.com/plugin/lifestealz/versions")
NEW_VERSION_AVAILABLE = true
}
}

// Register bstats
val pluginId = 18735
Metrics(this, pluginId)
Expand Down Expand Up @@ -266,6 +281,106 @@ class Lifestealz : JavaPlugin() {
Bukkit.addRecipe(reviveRecipe)
}

private fun getLatestVersionFromModrinth(): String? {
try {
// Query project information
val projectUrl = URL(MODRINTH_PROJECT_URL)
val projectConnection = projectUrl.openConnection() as HttpURLConnection
projectConnection.requestMethod = "GET"
val projectResponseCode = projectConnection.responseCode
if (projectResponseCode == HttpURLConnection.HTTP_OK) {
val projectReader = BufferedReader(InputStreamReader(projectConnection.inputStream))
val projectResponse = StringBuilder()
var projectInputLine: String?
while (projectReader.readLine().also { projectInputLine = it } != null) {
projectResponse.append(projectInputLine)
}
projectReader.close()

val parser = JSONParser()
// Parse JSON response to get the latest version ID
val projectJson = parser.parse(projectResponse.toString()) as JSONObject
val versionArray = projectJson["versions"] as JSONArray
val latestVersionId = versionArray[versionArray.size - 1] as String

// Query version details using latest version ID
val versionUrl = URL("$MODRINTH_PROJECT_URL/version/$latestVersionId")
val versionConnection = versionUrl.openConnection() as HttpURLConnection
versionConnection.requestMethod = "GET"
val versionResponseCode = versionConnection.responseCode
if (versionResponseCode == HttpURLConnection.HTTP_OK) {
val versionReader = BufferedReader(InputStreamReader(versionConnection.inputStream))
val versionResponse = StringBuilder()
var versionInputLine: String?
while (versionReader.readLine().also { versionInputLine = it } != null) {
versionResponse.append(versionInputLine)
}
versionReader.close()

// Parse JSON response to get the latest version number
val versionJson = parser.parse(versionResponse.toString()) as JSONObject
return versionJson["version_number"] as String
} else {
logger.warning("Failed to retrieve version details from Modrinth. Response code: $versionResponseCode")
}
} else {
logger.warning("Failed to retrieve project information from Modrinth. Response code: $projectResponseCode")
}
} catch (e: Exception) {
logger.warning("Failed to check for updates: ${e.message}")
}
return null
}

// private fun getLatestVersionFromModrinth(): String? {
// try {
// // Query project information
// val projectUrl = URL(MODRINTH_PROJECT_URL)
// val projectConnection = projectUrl.openConnection() as HttpURLConnection
// projectConnection.requestMethod = "GET"
// val projectResponseCode = projectConnection.responseCode
// if (projectResponseCode == HttpURLConnection.HTTP_OK) {
// val projectReader = BufferedReader(InputStreamReader(projectConnection.inputStream))
// val projectResponse = StringBuilder()
// var projectInputLine: String?
// while (projectReader.readLine().also { projectInputLine = it } != null) {
// projectResponse.append(projectInputLine)
// }
// projectReader.close()
//
// // Parse JSON response to get the latest version ID
// val projectJson = JSONObject(projectResponse.toString())
// val latestVersionId = projectJson.getJSONArray("versions").getJSONObject(0).getString("id")
//
// // Query version details using latest version ID
// val versionUrl = URL("$MODRINTH_PROJECT_URL/version/$latestVersionId")
// val versionConnection = versionUrl.openConnection() as HttpURLConnection
// versionConnection.requestMethod = "GET"
// val versionResponseCode = versionConnection.responseCode
// if (versionResponseCode == HttpURLConnection.HTTP_OK) {
// val versionReader = BufferedReader(InputStreamReader(versionConnection.inputStream))
// val versionResponse = StringBuilder()
// var versionInputLine: String?
// while (versionReader.readLine().also { versionInputLine = it } != null) {
// versionResponse.append(versionInputLine)
// }
// versionReader.close()
//
// // Parse JSON response to get the latest version number
// val versionJson = JSONObject(versionResponse.toString())
// return versionJson.getString("version_number")
// } else {
// logger.warning("Failed to retrieve version details from Modrinth. Response code: $versionResponseCode")
// }
// } else {
// logger.warning("Failed to retrieve project information from Modrinth. Response code: $projectResponseCode")
// }
// } catch (e: Exception) {
// logger.warning("Failed to check for updates: ${e.message}")
// }
// return null
// }

private fun initializeConfig() {
// Write config file if it is empty

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package org.strassburger.lifestealz.commands

import net.kyori.adventure.text.Component
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.attribute.Attribute
Expand Down Expand Up @@ -60,9 +59,9 @@ class SettingsCommand(private val plugin: JavaPlugin) : CommandExecutor {
if (sender.hasPermission("lifestealz.withdraw")) helpMessage += "\n&c/withdrawheart &8- &7withdraw a heart"
helpMessage += "\n&8----------------------------------------------------\n&r "

helpMessage = ChatColor.translateAlternateColorCodes('&', helpMessage)
val helpMessageFormatted = Lifestealz.formatMsg(helpMessage)

sender.sendMessage(Component.text(helpMessage))
sender.sendMessage(helpMessageFormatted)
}

if (optionOne == "recipe") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ class CraftItemListener(private val plugin: JavaPlugin) : Listener {
if (event.whoClicked !is Player) return
val player = event.whoClicked as Player

val heartRecipeKey = NamespacedKey(plugin, "heartrecipe")
val reviveRecipeKey = NamespacedKey(plugin, "reviverecipe")

if (isHeart(event.recipe.result)) {
val worldWhitelisted = Lifestealz.instance.config.getList("worlds")?.contains(player.location.world.name)
if (worldWhitelisted == null || !worldWhitelisted) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ class InventoryClickListener : Listener {

player.sendMessage(getAndFormatMsg(true, "messages.reviveSuccess", "&7You successfully revived &c%player%&7!", Replaceable("%player%", targetPlayer.name!!)))

val reviveuseCommands = Lifestealz.instance.config.getStringList("reviveuseCommands")
reviveuseCommands.forEach {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), it.replace("&player&", player.name).replace("&target&", targetPlayer.name!!))
}

val mainHandItem = player.inventory.itemInMainHand
val offHandItem = player.inventory.itemInOffHand

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ class PlayerDeathListener : Listener {
val playerData = ManagePlayerdata().getPlayerData(uuid = player.uniqueId.toString(), name = player.name)

if (playerData.maxhp - 2.0 <= 0.0) {
val eleminationCommands = Lifestealz.instance.config.getStringList("eliminationCommands")
eleminationCommands.forEach {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), it.replace("&player&", player.name))
}

if (!disabledBanOnDeath) {
player.inventory.clear()
Expand All @@ -78,9 +82,7 @@ class PlayerDeathListener : Listener {
ManagePlayerdata().manageHearts(player = player, direction = "set", amount = 0.0)
return
} else {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), (Lifestealz.instance.config.getString("eliminationCommand")?: "say &player& got eliminated").replace("&player&", player.name))
var respawnHP = (Lifestealz.instance.config.getInt("respawnHP") * 2).toDouble()

if (respawnHP < 2.0) respawnHP = 2.0

ManagePlayerdata().manageHearts(player = player, direction = "set", amount = respawnHP)
Expand All @@ -95,6 +97,11 @@ class PlayerDeathListener : Listener {
}

if (Lifestealz.instance.config.getBoolean("looseHeartsToNature")) {
val eleminationCommands = Lifestealz.instance.config.getStringList("eliminationCommands")
eleminationCommands.forEach {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), it.replace("&player&", player.name))
}

val playerData = ManagePlayerdata().getPlayerData(uuid = player.uniqueId.toString(), name = player.name)

if (playerData.maxhp - 2.0 <= 0.0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ class PlayerInteractionListener : Listener {
player.health += 2.0
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 500.0f, 1.0f)

val heartuseCommands = Lifestealz.instance.config.getStringList("heartuseCommands")
heartuseCommands.forEach {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), it.replace("&player&", player.name))
}

if (Lifestealz.instance.config.getBoolean("playTotemEffect")) player.playEffect(EntityEffect.TOTEM_RESURRECT)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class PlayerJoinListener(private val plugin: JavaPlugin) : Listener {
applyInvulnerability(player)

setMaxHealth(player, playerData.maxhp)

if (player.isOp && Lifestealz.instance.config.getBoolean("checkForUpdates") && Lifestealz.NEW_VERSION_AVAILABLE) {
player.sendMessage(Lifestealz.getAndFormatMsg(true, "messages.newVersionAvailable", "&7A new version of LifeStealZ is available!\\n&c<click:OPEN_URL:https://modrinth.com/plugin/lifestealz/versions>https://modrinth.com/plugin/lifestealz/versions</click>"))
}
}

private fun setMaxHealth(player: Player, maxHealth: Double) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.strassburger.lifestealz.util

import net.kyori.adventure.text.Component
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemFlag
Expand Down Expand Up @@ -30,7 +29,7 @@ class ManageCustomItems {
itemMeta?.addEnchant(Enchantment.DURABILITY, 1, true)
}

val heartLorelist = Lifestealz.instance.config.getStringList("items.heart.lore") ?: listOf<String>("&7Rightclick to use")
val heartLorelist = Lifestealz.instance.config.getStringList("items.heart.lore")
val itemLore = mutableListOf<Component>()
for (loreItem in heartLorelist) {
itemLore.add(Lifestealz.formatMsg(loreItem))
Expand Down Expand Up @@ -65,7 +64,7 @@ class ManageCustomItems {
itemMeta?.addEnchant(Enchantment.DURABILITY, 1, true)
}

val heartLorelist = Lifestealz.instance.config.getStringList("items.revive.lore") ?: listOf<String>("&7Rightclick to use")
val heartLorelist = Lifestealz.instance.config.getStringList("items.revive.lore")
val itemLore = mutableListOf<Component>()
for (loreItem in heartLorelist) {
itemLore.add(Lifestealz.formatMsg(loreItem))
Expand All @@ -90,7 +89,7 @@ class ManageCustomItems {
val customItemMeta = customItem.itemMeta
customItemMeta.displayName(name)
customItemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES)
customItemMeta.lore = lore
customItemMeta.lore(lore.map { Lifestealz.formatMsg(it) })
customItem.itemMeta = customItemMeta

return customItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ class MyTabCompleter : TabCompleter {
return mutableListOf("heart", "revivecrystal")
}
} else if (args.size == 4) {
if (args[1] == "hearts") {
return mutableListOf("1", "5", "10")
if (args[0] == "hearts" || args[0] == "giveItem") {
return mutableListOf("1", "32", "64")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.flags.StateFlag;
import org.strassburger.lifestealz.Lifestealz;
import org.strassburger.lifestealz.util.worldguardflags.HeartLossFlag;

public class WorldGuardManager {
Expand Down
16 changes: 14 additions & 2 deletions src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# https://docs.advntr.dev/minimessage/format.html
# With these, you can also add HEX colors, gradients, hover and click events, etc

checkForUpdates: true

#A list of worlds, where the plugin should take effect
worlds:
- "world"
Expand Down Expand Up @@ -56,10 +58,19 @@ preventCrystalPVP: false
disablePlayerBanOnElimination: false
# The amount of hp a player should have after getting eliminated
respawnHP: 10
# The command that should be executed when a player gets eliminated

# Execute custom commands on events:
# You can use &player& to insert the player name
# For example: tempban &player& banreason 1d
eliminationCommand: say &player& got eliminated
eliminationCommands:
# - "say &player& got eliminated"
# - "niceCommandtwo"

heartuseCommands:
# - "say &player& used a heart item"

reviveuseCommands:
# - "say &player& revived &target&"

#Here you can modify everything about the custom items
items:
Expand Down Expand Up @@ -113,6 +124,7 @@ items:
#You can modify all messages here
messages:
prefix: "&8[&cLifeStealZ&8]"
newVersionAvailable: "&7A new version of LifeStealZ is available!\n&c<click:OPEN_URL:https://modrinth.com/plugin/lifestealz/versions>https://modrinth.com/plugin/lifestealz/versions</click>"
usageError: "&cUsage: %usage%"
noPermissionError: "&cYou don't have permission to use this!"
noPlayerData: "&cThis player has not played on this server yet!"
Expand Down
Loading

0 comments on commit 7b54c0c

Please sign in to comment.