Skip to content

Commit

Permalink
refactor: move final formatting logic into shared handleFinalMessage …
Browse files Browse the repository at this point in the history
…method
  • Loading branch information
Boy0000 committed Jun 8, 2024
1 parent 006adb0 commit 40be843
Show file tree
Hide file tree
Showing 7 changed files with 202 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ package com.mineinabyss.chatty

import com.charleskorn.kaml.YamlComment
import com.mineinabyss.chatty.components.ChannelType
import com.mineinabyss.chatty.components.SpyOnChannels
import com.mineinabyss.chatty.helpers.TranslationLanguage
import com.mineinabyss.chatty.queries.SpyingPlayers
import com.mineinabyss.geary.papermc.tracking.entities.toGeary
import com.mineinabyss.idofront.textcomponents.miniMsg
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
Expand Down Expand Up @@ -42,7 +39,7 @@ data class ChattyChannel(
)
val type: TargetLanguageType = TargetLanguageType.NONE,
@YamlComment("The default language for this channel to translate to.")
val targetLanguage: TranslationLanguage = chatty.config.translation.defaultLanguage,
val targetLanguage: TranslationLanguage = TranslationLanguage.English_US,
//@YamlComment("Whether there should be a rate limitation per player for this channel.")
//val rateLimitPerPlayer: Boolean = true,
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class ChattyPlugin : JavaPlugin() {
val chattyContext = object : ChattyContext {
override val plugin: ChattyPlugin = this@ChattyPlugin
override val config: ChattyConfig by config("config", dataFolder.toPath(), ChattyConfig())
override val translator: Translator = Translator(config.translation.authKey)
override val translator: Translator = Translator(config.translation.authKey.takeUnless { it.isNullOrEmpty() } ?: "x")
override val messages: ChattyMessages by config("messages", dataFolder.toPath(), ChattyMessages())
override val emotefixer: DiscordEmoteFixer by config("emotefixer", dataFolder.toPath(), DiscordEmoteFixer())
override val isPlaceholderApiLoaded: Boolean get() = Plugins.isEnabled("PlaceholderAPI")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
@file:Suppress("ReplaceSizeZeroCheckWithIsEmpty")

package com.mineinabyss.chatty.extensions

interface BaseMutableMap<K, V> : BaseMap<K, V>, MutableMap<K, V> {
override fun putAll(from: Map<out K, V>) {
for ((k, v) in from) put(k, v)
}
}

interface BaseMap<K, V> : Map<K, V> {
override fun isEmpty(): Boolean = size == 0
override fun containsKey(key: K): Boolean = keys.contains(key)
override fun containsValue(value: V): Boolean = values.contains(value)
}

interface BaseMutableList<T> : BaseList<T>, MutableList<T> {
override fun iterator(): MutableIterator<T> = listIterator(0)
override fun listIterator(): MutableListIterator<T> = listIterator(0)
override fun listIterator(index: Int): MutableListIterator<T> = BaseMutableListIterator(this, index)
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> = BaseSubMutableList(this, fromIndex, toIndex)

override fun add(element: T): Boolean {
add(size, element)
return true
}

override fun addAll(elements: Collection<T>): Boolean = addAll(size, elements)

override fun clear() {
while (isNotEmpty()) removeAt(size - 1)
}

override fun remove(element: T): Boolean {
val index = indexOf(element)
val found = index >= 0
if (found) removeAt(index)
return found
}

override fun retainAll(elements: Collection<T>): Boolean {
val set = elements.toSet()
return retainAll { it in set }
}

override fun removeAll(elements: Collection<T>): Boolean {
val set = elements.toSet()
return removeAll { it in set }
}
}

interface BaseList<T> : List<T> {
override fun containsAll(elements: Collection<T>): Boolean {
val elementsSet = elements.toSet()
for (n in 0 until size) if (this[n] in elementsSet) return true
return false
}
override fun contains(element: T): Boolean = indexOf(element) >= 0
override fun isEmpty(): Boolean = size == 0
override fun iterator(): Iterator<T> = listIterator(0)
override fun listIterator(): ListIterator<T> = listIterator(0)
override fun listIterator(index: Int): ListIterator<T> = BaseListIterator(this, index)
override fun subList(fromIndex: Int, toIndex: Int): List<T> = BaseSubList(this, fromIndex, toIndex)
override fun lastIndexOf(element: T): Int {
for (n in size - 1 downTo 0) if (this[n] == element) return n
return -1
}
override fun indexOf(element: T): Int {
for (n in 0 until size) if (this[n] == element) return n
return -1
}
}

open class BaseSubList<T>(val list: List<T>, start: Int, end: Int) : BaseList<T> {
var start: Int = start ; protected set
var end: Int = end ; protected set
override val size: Int get() = end - start
fun checkIndex(index: Int): Int {
if (index < 0 || index >= size) throw IndexOutOfBoundsException()
return start + index
}

override fun get(index: Int): T = list[checkIndex(index)]
}

open class BaseSubMutableList<T>(val mlist: MutableList<T>, start: Int, end: Int) : BaseSubList<T>(mlist, start, end),
BaseMutableList<T> {
override fun add(index: Int, element: T) {
mlist.add(checkIndex(index), element)
end++
}

override fun addAll(index: Int, elements: Collection<T>): Boolean {
val before = mlist.size
val out = mlist.addAll(checkIndex(index), elements)
end += mlist.size - before
return out
}

override fun removeAt(index: Int): T {
end--
return mlist.removeAt(checkIndex(index))
}

override fun set(index: Int, element: T): T = mlist.set(checkIndex(index), element)
}

open class BaseListIterator<T>(val list: List<T>, var index: Int) : ListIterator<T> {
override fun hasNext(): Boolean = index < list.size
override fun hasPrevious(): Boolean = (index > 0)
override fun next(): T = list[index++]
override fun nextIndex(): Int = index
override fun previous(): T = list[--index]
override fun previousIndex(): Int = index - 1
}

open class BaseMutableListIterator<T>(val mlist: MutableList<T>, index: Int) : BaseListIterator<T>(mlist, index), MutableListIterator<T> {
override fun add(element: T) = mlist.add(index, element)
override fun remove() { mlist.removeAt(index) }
override fun set(element: T) { mlist[index] = element }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.mineinabyss.chatty.extensions

open class CacheMap<K, V>(
val maxSize: Int = 16,
) : BaseCacheMap<K, V>() {
override fun mustFree(key: K, value: V): Boolean = size > maxSize
}

open class BaseCacheMap<K, V>() : BaseMutableMap<K, V> {
val map: LinkedHashMap<K, V> = LinkedHashMap()

protected open fun mustFree(key: K, value: V): Boolean = false
protected open fun keyToRemove(key: K, value: V): K = map.keys.first()
protected open fun freed(key: K, value: V) {
}

override val size: Int get() = map.size

override fun remove(key: K): V? {
val value = map.remove(key)
if (value != null) freed(key, value)
return value
}

override fun putAll(from: Map<out K, V>) { for ((k, v) in from) put(k, v) }
override fun put(key: K, value: V): V? {
val oldValue = map[key]
if (oldValue != value) {
remove(key) // refresh if exists
map[key] = value
putNew(key, value)
}
//while (isNotEmpty() && mustFree(key, value) && !map.containsKey(key)) {
while (isNotEmpty() && mustFree(key, value)) {
val keyToRemove = keyToRemove(key, value)
remove(keyToRemove)
}
return oldValue
}

protected open fun putNew(key: K, value: V) {
}

override fun clear() {
val keys = map.keys.toList()
for (key in keys) remove(key)
}

override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = map.entries
override val keys: MutableSet<K> get() = map.keys
override val values: MutableCollection<V> get() = map.values

override fun get(key: K): V? = map.get(key)

override fun toString(): String = map.toString()

override fun equals(other: Any?): Boolean = (other is BaseCacheMap<*, *>) && (this.map == other.map)
override fun hashCode(): Int = this.map.hashCode()
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package com.mineinabyss.chatty.helpers

import com.mineinabyss.chatty.ChattyChannel
import com.mineinabyss.chatty.ChattyConfig
import com.mineinabyss.chatty.ChattyChannel.Translation.*
import com.mineinabyss.chatty.chatty
import com.mineinabyss.chatty.components.ChattyTranslation
import com.mineinabyss.chatty.extensions.CacheMap
import com.mineinabyss.idofront.textcomponents.miniMsg
import com.mineinabyss.idofront.textcomponents.serialize
import korlibs.datastructure.CacheMap
import net.kyori.adventure.chat.SignedMessage
import net.kyori.adventure.text.Component
import org.bukkit.entity.Player
Expand All @@ -33,7 +32,13 @@ fun handleMessageTranslation(source: Player, channel: ChattyChannel, sourceTrans
// We cache translations to avoid translating the same message multiple times
return cachedTranslations.computeIfAbsent(signedMessage) {
TranslatedMessage(targetLanguage,
Component.textOfChildren(chatty.translator.translateText(component.serialize(), sourceTranslation?.language?.languageCode, targetLanguage.languageCode).text.miniMsg().hoverEventShowText(component), Component.text("*"))
Component.textOfChildren(
*component.children().dropLast(1).toTypedArray(),
chatty.translator.translateText(
component.children().last().serialize(), sourceTranslation?.language?.languageCode, targetLanguage.languageCode
).text.miniMsg().hoverEventShowText(component.children().last()),
Component.text("*")
)
)
}.translatedMessage
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import io.papermc.paper.chat.ChatRenderer
import io.papermc.paper.event.player.AsyncChatCommandDecorateEvent
import io.papermc.paper.event.player.AsyncChatDecorateEvent
import io.papermc.paper.event.player.AsyncChatEvent
import net.kyori.adventure.chat.SignedMessage
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.Style
import net.kyori.adventure.text.format.TextDecoration
Expand Down Expand Up @@ -109,13 +110,11 @@ class ChatListener : Listener {
}

viewers().clear()
//isCancelled = true
}

else -> renderer { source, _, message, audience ->
if (audience !is Player) return@renderer Component.empty()

val audienceTranslation = audience.toGearyOrNull()?.get<ChattyTranslation>()
val audienceTranslation = runCatching { audience.toGearyOrNull()?.get<ChattyTranslation>() }.getOrNull()
var finalMessage = message
finalMessage = handleMessageTranslation(player, channel, playerTranslation, audienceTranslation, finalMessage, signedMessage())
finalMessage = handleChatFilters(finalMessage, player, audience)
Expand All @@ -136,6 +135,15 @@ class ChatListener : Listener {
}
}

private fun handleFinalMessage(source: Player, channel: ChattyChannel, message: Component, signedMessage: SignedMessage, simpleMessage: Component, audience: Player, playerTranslation: ChattyTranslation?, audienceTranslation: ChattyTranslation?, pingedPlayer: Player?, playerViewers: Set<Player>) : Component {
return message
.let { handleMessageTranslation(source, channel, playerTranslation, audienceTranslation, it, signedMessage) }
.let { handleChatFilters(it, source, audience) }
.let { formatPlayerPingMessage(source, pingedPlayer, audience, message) }
.let { appendChannelFormat(it, source, channel) }
.let { formatModerationMessage(channel.messageDeletion, it, simpleMessage, signedMessage, audience, source, playerViewers) }
}

private fun handleProxyMessage(
player: Player,
channelId: String,
Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ velocity = { module = "com.velocitypowered:velocity-api", version.ref = "velocit
discordsrv = { module = "com.discordsrv:discordsrv", version.ref = "discordsrv" }
placeholderapi = { module = "me.clip:placeholderapi", version.ref = "placeholderapi" }
imageloader = { module = "com.combimagnetron:imageloader", version.ref = "imageloader" }
deepl = { module = "com.deepl.api:deepl-java", version = "1.4.0" }
deepl = { module = "com.deepl.api:deepl-java", version = "1.5.0" }

0 comments on commit 40be843

Please sign in to comment.