Skip to content

Commit

Permalink
PlaceholderAPI, config fixes, code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
KruASe76 committed Jun 9, 2024
1 parent 420484a commit 12af746
Show file tree
Hide file tree
Showing 14 changed files with 252 additions and 279 deletions.
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,19 @@ A Spigot (Bukkit) Minecraft that improves the player list (shown on Tab button p
- ![](https://via.placeholder.com/15/ff5555/ff5555.png) Red for Nether
- ![](https://via.placeholder.com/15/ff55ff/ff55ff.png) Purple for The End
- The "idle" badge is placed after the player's name if they haven't moved for some time
- [Placeholders](#compatibility)


## Compatibility
**Tablist tweaks is compatible with [TAB](https://modrinth.com/plugin/tab-was-taken)!**
As for other similar plugins - most likely not.
### [PlaceholderAPI](https://www.spigotmc.org/resources/placeholderapi.6245/) placeholders
(they can be used in other plugins such as [TAB](https://modrinth.com/plugin/tab-was-taken))

| Placeholder | Description |
|-----------------------------------|------------------------------------------------------------------------------------------------|
| `%tablisttweaks_dimension_color%` | corresponding color code from config<br/>(obviously can be used to color anything) |
| `%tablisttweaks_dimension_dot%` | Dimension Dot with corresponding color<br/>(even if the "dimension-dots" feature is disabled) |
| `%tablisttweaks_idle_badge%` | empty or the "idle" badge with color from config<br/>(always empty if the feature is disabled) |
| `%tablisttweaks_idle_flag%` | either `true` or `false`<br/>(always `false` if the feature is disabled) |


## Usage
Expand All @@ -46,13 +54,15 @@ As for other similar plugins - most likely not.
- The time player has to stand still to get the "idle" badge (in seconds)
- Enable/disable features
- Dimension colors
- Dot format (see images)
- Idle badge
- Dimension Dot format (see images)
- "Idle" badge
- Colors
- dimensions
- "idle" badge
- Plugin messages
- error
- help
- warning
- info


## Permissions
Expand Down
12 changes: 6 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>me.kruase</groupId>
<artifactId>tablist-tweaks</artifactId>
<version>1.5</version>
<version>1.6</version>
<packaging>jar</packaging>

<name>TablistTweaks</name>
Expand Down Expand Up @@ -73,8 +73,8 @@
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
<repository>
<id>krypton</id>
<url>https://repo.kryptonmc.org/releases</url>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>

Expand All @@ -91,9 +91,9 @@
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>me.neznamy</groupId>
<artifactId>tab-api</artifactId>
<version>4.0.2</version>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
Expand Down
12 changes: 7 additions & 5 deletions src/main/kotlin/me/kruase/tablisttweaks/TTCommands.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package me.kruase.tablisttweaks

import me.kruase.tablisttweaks.commands.*
import me.kruase.tablisttweaks.TablistTweaks.Companion.userConfig
import me.kruase.tablisttweaks.commands.help
import me.kruase.tablisttweaks.commands.reload
import org.bukkit.ChatColor
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
Expand All @@ -16,11 +18,11 @@ class TTCommands : TabExecutor {
): List<String> {
val fullArgs = args.dropLast(1)
return when (fullArgs.getOrNull(0)) {
null -> TablistTweaks.userConfig.messages.help.keys
null -> userConfig.messages.help.keys
.filter { sender.hasPermission("tablisttweaks.${it.replace("-", ".")}") } - "header"
"help" -> when {
sender.hasPermission("tablisttweaks.help") -> when (fullArgs.getOrNull(1)) {
null -> TablistTweaks.userConfig.messages.help.keys
null -> userConfig.messages.help.keys
.filter { sender.hasPermission("tablisttweaks.${it.replace("-", ".")}") } - "header"
else -> listOf()
}
Expand All @@ -39,12 +41,12 @@ class TTCommands : TabExecutor {
}
} catch (e: UnsupportedOperationException) {
sender.sendMessage(
"${ChatColor.RED}${TablistTweaks.userConfig.messages.error["no-permission"] ?: "Error: no-permission"}"
"${ChatColor.RED}${userConfig.messages.error["no-permission"] ?: "Error: no-permission"}"
)
} catch (e: IllegalArgumentException) {
sender.sendMessage(
"${ChatColor.RED}${
TablistTweaks.userConfig.messages.error["invalid-command"] ?: "Error: invalid-command"
userConfig.messages.error["invalid-command"] ?: "Error: invalid-command"
}"
)
} catch (e: IllegalStateException) {
Expand Down
86 changes: 52 additions & 34 deletions src/main/kotlin/me/kruase/tablisttweaks/TTConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,68 +4,86 @@ import org.bukkit.configuration.file.FileConfiguration
import java.io.File


val allPaths = listOf(
"idle-badge-timeout-seconds",
"features.dimension-colors",
"features.idle-badge",
"messages.error.no-permission",
"messages.error.invalid-command",
"messages.help.header",
"messages.help.help",
"messages.help.reload",
)


data class TTConfig(private val config: FileConfiguration) {
val idleTimeout = config.getLong("idle-badge-timeout-seconds") * 20
val enabledFeatures = EnabledFeaturesConfig(config)
val colors = ColorsConfig(config)
val messages = MessagesConfig(config)
}


fun TablistTweaks.getUserConfig(): TTConfig {
val configFile = File(dataFolder, "config.yml")
val tempConfigFile = File(dataFolder, "temp-config.yml")
val oldConfigFile = File(dataFolder, "old-config-${System.currentTimeMillis()}.yml")

return try {
saveDefaultConfig()
reloadConfig()

if ((allPaths - config.getKeys(true)).isNotEmpty()) throw NullPointerException()
// validating current config
val currentConfigKeys = config.getKeys(true)

configFile.renameTo(tempConfigFile)
saveDefaultConfig()
reloadConfig()

val defaultConfigKeys = config.getKeys(true)

if ((defaultConfigKeys - currentConfigKeys).isNotEmpty())
throw NullPointerException()
else {
configFile.delete()
tempConfigFile.renameTo(configFile)
reloadConfig()
}

TTConfig(config)
} catch (e: Exception) {
when (e) {
is NullPointerException -> {
newDefaultConfig()
logger.severe("Invalid $name config detected! Creating a new one (default)...")

tempConfigFile.renameTo(oldConfigFile)

logger.info("New (default) config created!")

TTConfig(config)
}
else -> throw e
}
}.also { logger.info("Config loaded!") }
}

fun TablistTweaks.newDefaultConfig() {
logger.severe("Invalid $name config detected! Creating a new one (default)...")
File(dataFolder, "config.yml").renameTo(
File(dataFolder, "config.yml.old-${System.currentTimeMillis()}")
)
saveDefaultConfig()
reloadConfig()
logger.info("New (default) config created!")
}
.also { logger.info("Config loaded!") }
}


data class EnabledFeaturesConfig(private val config: FileConfiguration) {
val dimensionColors = config.getBoolean("features.dimension-colors")
val dimensionColorDots = config.getBoolean("features.dimension-color-dots")
val dimensionDots = config.getBoolean("features.dimension-dots")
val idleTracking = config.getBoolean("features.idle-badge")
}

data class ColorsConfig(private val config: FileConfiguration) {
val overworld = config.getString("colors.overworld")!!
val nether = config.getString("colors.nether")!!
val end = config.getString("colors.end")!!
val idleBadge = config.getString("colors.idle-badge")!!
}

data class MessagesConfig(private val config: FileConfiguration) {
val help: Map<String, String> = config.getConfigurationSection("messages.help")!!
.getKeys(false).associateWith { config.getString("messages.help.$it")!! }
val error: Map<String, String> = config.getConfigurationSection("messages.error")!!
.getKeys(false).associateWith { config.getString("messages.error.$it")!! }
val info: Map<String, String> = config.getConfigurationSection("messages.info")!!
.getKeys(false).associateWith { config.getString("messages.info.$it")!! }
val warning: Map<String, String> = config.getConfigurationSection("messages.warning")!!
.getKeys(false).associateWith { config.getString("messages.warning.$it")!! }
val help: Map<String, String?> =
config
.getConfigurationSection("messages.help")!!
.getKeys(false)
.associateWith { config.getString("messages.help.$it") }
val error: Map<String, String?> =
config
.getConfigurationSection("messages.error")!!
.getKeys(false)
.associateWith { config.getString("messages.error.$it") }
val warning: Map<String, String?> =
config
.getConfigurationSection("messages.warning")!!
.getKeys(false)
.associateWith { config.getString("messages.warning.$it") }
}
40 changes: 7 additions & 33 deletions src/main/kotlin/me/kruase/tablisttweaks/TTEvents.kt
Original file line number Diff line number Diff line change
@@ -1,68 +1,42 @@
package me.kruase.tablisttweaks

import me.kruase.tablisttweaks.TablistTweaks.Companion.userConfig
import me.kruase.tablisttweaks.util.initFeatures
import me.kruase.tablisttweaks.util.refreshIdleTracking
import me.kruase.tablisttweaks.util.startIdleTracking
import me.kruase.tablisttweaks.util.stopIdleTracking
import me.kruase.tablisttweaks.util.updateDimension
import me.neznamy.tab.api.event.player.PlayerLoadEvent
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.*


class TTEvents : Listener {
init {
registerTabApiEvents()
}

@EventHandler
fun onPlayerJoin(event: PlayerJoinEvent) {
if (TablistTweaks.tabApiInstance == null)
event.player.joinHandle()
event.player.initFeatures()
}

@EventHandler
fun onPlayerTeleport(event: PlayerTeleportEvent) {
if (TablistTweaks.userConfig.enabledFeatures.dimensionColors)
if (userConfig.enabledFeatures.dimensionColors)
event.player.updateDimension(destinationLocation = event.to!!)
}

@EventHandler
fun onPlayerRespawn(event: PlayerRespawnEvent) {
if (TablistTweaks.userConfig.enabledFeatures.dimensionColors)
if (userConfig.enabledFeatures.dimensionColors)
event.player.updateDimension(destinationLocation = event.respawnLocation)
}

@EventHandler
fun onPlayerLeave(event: PlayerQuitEvent) {
if (TablistTweaks.userConfig.enabledFeatures.idleTracking)
if (userConfig.enabledFeatures.idleTracking)
event.player.stopIdleTracking()
}

@EventHandler
fun onPlayerMove(event: PlayerMoveEvent) {
if (TablistTweaks.userConfig.enabledFeatures.idleTracking)
if (userConfig.enabledFeatures.idleTracking)
event.player.refreshIdleTracking()
}
}


fun Player.joinHandle() {
if (TablistTweaks.userConfig.enabledFeatures.dimensionColors)
updateDimension(isInitial = true)

if (TablistTweaks.userConfig.enabledFeatures.idleTracking)
startIdleTracking()
}


fun registerTabApiEvents() {
TablistTweaks.tabApiInstance
?.run {
eventBus?.register(PlayerLoadEvent::class.java) { event ->
TablistTweaks.instance.server.getPlayer(event.player.uniqueId)
?.joinHandle()
}
}
}
27 changes: 27 additions & 0 deletions src/main/kotlin/me/kruase/tablisttweaks/TTPlaceholderExpansion.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package me.kruase.tablisttweaks

import me.clip.placeholderapi.expansion.PlaceholderExpansion
import me.kruase.tablisttweaks.TablistTweaks.Companion.instance
import me.kruase.tablisttweaks.util.placeholders
import org.bukkit.entity.Player


class TTPlaceholderExpansion : PlaceholderExpansion() {
override fun getIdentifier() = "tablisttweaks"
override fun getAuthor() = instance.description.authors.joinToString()
override fun getVersion() = instance.description.version
override fun persist(): Boolean = true

override fun onPlaceholderRequest(player: Player?, name: String): String? {
if (player == null)
return null

return when (name) {
"dimension_color" -> player.placeholders?.dimensionColor ?: ""
"dimension_dot" -> player.placeholders?.dimensionDot ?: ""
"idle_badge" -> player.placeholders?.idleBadge ?: ""
"idle_flag" -> player.placeholders?.idleFlag ?: ""
else -> null
}
}
}
13 changes: 5 additions & 8 deletions src/main/kotlin/me/kruase/tablisttweaks/TablistTweaks.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package me.kruase.tablisttweaks

import me.kruase.tablisttweaks.commands.reload
import me.kruase.tablisttweaks.util.infoNotNull
import me.neznamy.tab.api.TabAPI
import me.kruase.tablisttweaks.util.PlayerPlaceholders
import org.bukkit.plugin.java.JavaPlugin
import java.util.*

Expand All @@ -12,19 +11,17 @@ class TablistTweaks : JavaPlugin() {
lateinit var instance: TablistTweaks
lateinit var userConfig: TTConfig

var tabApiInstance: TabAPI? = null

val idlePlayerTaskIds = mutableMapOf<UUID, Int>()
val playerIdleTaskIds = mutableMapOf<UUID, Int>()
val playerPlaceholders = mutableMapOf<UUID, PlayerPlaceholders>()
}

override fun onEnable() {
instance = this

reload()

if (server.pluginManager.isPluginEnabled("TAB")) {
tabApiInstance = TabAPI.getInstance()
logger.infoNotNull(userConfig.messages.info["tab-found"])
if (server.pluginManager.isPluginEnabled("PlaceholderAPI")) {
TTPlaceholderExpansion().register()
}

getCommand("tablisttweaks")!!.setExecutor(TTCommands())
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/me/kruase/tablisttweaks/commands/help.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package me.kruase.tablisttweaks.commands

import org.bukkit.command.CommandSender
import me.kruase.tablisttweaks.TablistTweaks.Companion.userConfig
import me.kruase.tablisttweaks.util.hasPluginPermission
import org.bukkit.command.CommandSender


fun help(sender: CommandSender, args: Array<out String>) {
Expand Down
Loading

0 comments on commit 12af746

Please sign in to comment.