refactor config and add connect / disconnect announcements as debug option

This commit is contained in:
Nikky Ai 2018-02-21 03:13:49 +01:00
parent bce5cd871e
commit 172305482d
21 changed files with 225 additions and 188 deletions

View File

@ -3,7 +3,10 @@ package matterlink
import matterlink.bridge.ServerChatHandler
import matterlink.bridge.USER_ACTION
import matterlink.config.cfg
import matterlink.handlers.*
import matterlink.handlers.ChatProcessor
import matterlink.handlers.DeathHandler
import matterlink.handlers.JoinLeaveHandler
import matterlink.handlers.ProgressHandler
import net.minecraft.command.server.CommandBroadcast
import net.minecraft.command.server.CommandEmote
import net.minecraft.entity.player.EntityPlayer
@ -58,7 +61,7 @@ object EventHandler {
@JvmStatic
fun commandEvent(e: CommandEvent) {
val sender = when {
e.sender is DedicatedServer -> cfg.relay.systemUser
e.sender is DedicatedServer -> cfg.outgoing.systemUser
e.sender is TileEntityCommandBlock -> "CommandBlock"
else -> e.sender.name
}

View File

@ -44,13 +44,12 @@ object MatterLink : IMatterLink() {
fun serverStarting(event: FMLServerStartingEvent) {
logger.debug("Registering server commands")
event.registerServerCommand(CommandMatterlink())
serverStartTime = System.currentTimeMillis()
connect()
start()
}
@Mod.EventHandler
fun serverStopping(event: FMLServerStoppingEvent) {
disconnect()
stop()
}
//FORGE-DEPENDENT

View File

@ -59,7 +59,7 @@ object EventHandler {
@JvmStatic
fun commandEvent(e: CommandEvent) {
val sender = when {
e.sender is DedicatedServer -> cfg.relay.systemUser
e.sender is DedicatedServer -> cfg.outgoing.systemUser
e.sender is TileEntityCommandBlock -> "CommandBlock"
else -> e.sender.name
}

View File

@ -44,13 +44,12 @@ object MatterLink : IMatterLink() {
fun serverStarting(event: FMLServerStartingEvent) {
logger.debug("Registering server commands")
event.registerServerCommand(CommandMatterlink())
serverStartTime = System.currentTimeMillis()
connect()
start()
}
@Mod.EventHandler
fun serverStopping(event: FMLServerStoppingEvent) {
disconnect()
stop()
}
//FORGE-DEPENDENT

View File

@ -51,7 +51,7 @@ object EventHandler {
@JvmStatic
fun commandEvent(e: CommandEvent) {
val sender = when {
e.sender is DedicatedServer -> cfg.relay.systemUser
e.sender is DedicatedServer -> cfg.outgoing.systemUser
e.sender is TileEntityCommandBlock -> "CommandBlock"
else -> e.sender.name
}

View File

@ -49,13 +49,12 @@ object MatterLink : IMatterLink() {
fun serverStarting(event: FMLServerStartingEvent) {
logger.debug("Registering server commands")
event.registerServerCommand(CommandMatterlink())
serverStartTime = System.currentTimeMillis()
connect()
start()
}
@Mod.EventHandler
fun serverStopping(event: FMLServerStoppingEvent) {
disconnect()
stop()
}
//FORGE-DEPENDENT

View File

@ -1,7 +1,6 @@
package matterlink
import matterlink.config.BaseConfig
import matterlink.config.cfg
import net.minecraftforge.common.config.Configuration
import java.io.File

View File

@ -6,7 +6,10 @@ import cpw.mods.fml.common.gameevent.TickEvent
import matterlink.bridge.ServerChatHandler
import matterlink.bridge.USER_ACTION
import matterlink.config.cfg
import matterlink.handlers.*
import matterlink.handlers.ChatProcessor
import matterlink.handlers.DeathHandler
import matterlink.handlers.JoinLeaveHandler
import matterlink.handlers.ProgressHandler
import net.minecraft.command.server.CommandBroadcast
import net.minecraft.command.server.CommandEmote
import net.minecraft.entity.player.EntityPlayer
@ -54,7 +57,7 @@ object EventHandler {
@SubscribeEvent
fun commandEvent(e: CommandEvent) {
val sender = when {
e.sender is DedicatedServer -> cfg.relay.systemUser
e.sender is DedicatedServer -> cfg.outgoing.systemUser
e.sender is TileEntityCommandBlock -> "CommandBlock"
else -> e.sender.commandSenderName
}

View File

@ -46,13 +46,12 @@ class MatterLink : IMatterLink() {
fun serverStarting(event: FMLServerStartingEvent) {
logger.debug("Registering server commands")
event.registerServerCommand(CommandMatterlink())
serverStartTime = System.currentTimeMillis()
connect()
start()
}
@Mod.EventHandler
fun serverStopping(event: FMLServerStoppingEvent) {
disconnect()
stop()
}
//FORGE-DEPENDENT

View File

@ -82,3 +82,5 @@ matterbridge
Now you just need to run MatterBridge on the server, the default configuration works with the provided sample.
and then [RTFM!!!](https://github.com/42wim/matterbridge#configuration)
powered by wishful thinking

View File

@ -5,7 +5,6 @@ import matterlink.bridge.command.BridgeCommandRegistry
import matterlink.bridge.command.IMinecraftCommandSender
import matterlink.config.cfg
import matterlink.update.UpdateChecker
import java.io.File
import java.time.Duration
lateinit var instance: IMatterLink
@ -18,20 +17,18 @@ abstract class IMatterLink {
abstract fun wrappedSendToPlayers(msg: String)
private var firstRun: Boolean = true
fun connect() {
MessageHandler.start(clear = true, firstRun = firstRun)
if (firstRun && cfg.update.enable) {
fun start() {
serverStartTime = System.currentTimeMillis()
MessageHandler.start(clear = true, firstRun = true, message = "Server started, connecting to matterbridge API")
if (cfg.update.enable) {
Thread(UpdateChecker()).start()
}
firstRun = false
}
fun disconnect() {
MessageHandler.stop()
fun stop() {
MessageHandler.stop(message = "Server shutting down, disconnecting from matterbridge API")
}
abstract fun log(level: String, formatString: String, vararg data: Any)
@ -41,12 +38,12 @@ abstract class IMatterLink {
fun warn(formatString: String, vararg data: Any) = log("WARN", formatString, *data)
fun info(formatString: String, vararg data: Any) = log("INFO", formatString, *data)
fun debug(formatString: String, vararg data: Any) {
if (cfg.relay.logLevel == "DEBUG" || cfg.relay.logLevel == "TRACE")
if (cfg.debug.logLevel == "DEBUG" || cfg.debug.logLevel == "TRACE")
log("INFO", "DEBUG: " + formatString.replace("\n", "\nDEBUG: "), *data)
}
fun trace(formatString: String, vararg data: Any) {
if (cfg.relay.logLevel == "TRACE")
if (cfg.debug.logLevel == "TRACE")
log("INFO", "TRACE: " + formatString.replace("\n", "\nTRACE: "), *data)
}

View File

@ -1,15 +1,15 @@
package matterlink.bridge
import matterlink.config.cfg
import matterlink.antiping
import com.google.gson.Gson
import matterlink.antiping
import matterlink.config.cfg
import matterlink.mapFormat
const val USER_ACTION: String = "user_action"
const val JOIN_LEAVE: String = "join_leave"
data class ApiMessage(
val username: String = cfg.relay.systemUser,
val username: String = cfg.outgoing.systemUser,
val text: String = "",
val gateway: String = cfg.connect.gateway,
val channel: String = "",

View File

@ -38,14 +38,19 @@ object MessageHandler {
}
}
fun stop() {
fun stop(message: String?) {
if (message != null && cfg.debug.announceDisconnect) {
transmit(ApiMessage(
text = message
))
}
enabled = false
streamConnection.close()
}
var enabled: Boolean = false
fun start(clear: Boolean = true, firstRun: Boolean = false) {
fun start(message: String?, clear: Boolean = true, firstRun: Boolean = false) {
enabled = when {
firstRun -> cfg.connect.autoConnect
else -> true
@ -58,6 +63,12 @@ object MessageHandler {
if (enabled) {
streamConnection.open()
}
if (message != null && cfg.debug.announceConnect) {
transmit(ApiMessage(
text = message //?: "Connected to matterbridge API"
))
}
}
private fun transmitMessage(message: ApiMessage) {
@ -77,7 +88,7 @@ object MessageHandler {
sendErrors++
if (sendErrors > 5) {
instance.error("Caught too many errors, closing bridge")
stop()
stop("Interrupting Connection to matterbridge API due status code $code")
}
}
sendErrors = 0
@ -86,7 +97,7 @@ object MessageHandler {
sendErrors++
if (sendErrors > 5) {
instance.error("Caught too many errors, closing bridge")
stop()
stop("Interrupting connection to matterbridge API, too many errors trying to send message")
}
}
}
@ -96,12 +107,12 @@ object MessageHandler {
if (connectErrors > 5) {
instance.fatal("Caught too many errors, closing bridge")
stop()
stop("Interrupting connection to matterbridge API due to accumulated connection errors")
return
}
instance.info("Trying to reconnect")
MessageHandler.start(clear = false)
MessageHandler.start(clear = false, message = "Reconnecting to matterbridge API after connection error")
}
}
}

View File

@ -1,8 +1,8 @@
package matterlink.bridge
import matterlink.instance
import matterlink.bridge.command.BridgeCommandRegistry
import matterlink.config.cfg
import matterlink.instance
object ServerChatHandler {
@ -18,13 +18,13 @@ object ServerChatHandler {
if (nextMessage != null && nextMessage.gateway == cfg.connect.gateway) {
if (!nextMessage.text.isBlank()) {
val message = when (nextMessage.event) {
"user_action" -> nextMessage.format(cfg.formatting.action)
"user_action" -> nextMessage.format(cfg.incoming.action)
"" -> {
// try to handle command and do not handle as a chat message
if (BridgeCommandRegistry.handleCommand(nextMessage)) return
nextMessage.format(cfg.formatting.chat)
nextMessage.format(cfg.incoming.chat)
}
"join_leave" -> nextMessage.format(cfg.formatting.joinLeave)
"join_leave" -> nextMessage.format(cfg.incoming.joinPart)
else -> {
val user = nextMessage.username
val text = nextMessage.text

View File

@ -26,7 +26,6 @@ abstract class IMinecraftCommandSender(val user: String, val userId: String, val
fun sendReply(text: String) {
reply = text
MessageHandler.transmit(ApiMessage(
username = cfg.relay.systemUser,
text = text
))
}

View File

@ -1,5 +1,6 @@
package matterlink.command
import matterlink.bridge.ApiMessage
import matterlink.bridge.MessageHandler
import matterlink.bridge.command.BridgeCommandRegistry
import matterlink.config.cfg
@ -17,18 +18,18 @@ object CommandCore {
return when (cmd) {
"connect" -> {
instance.connect()
MessageHandler.start(message = "Bridge connected by console")
"Attempting bridge connection!"
}
"disconnect" -> {
instance.disconnect()
MessageHandler.stop(message = "Bridge disconnected by console")
"Bridge disconnected!"
}
"reload" -> {
if (MessageHandler.connected) instance.disconnect()
if (MessageHandler.connected) MessageHandler.stop(message = "Bridge restarting (reload command issued by console)")
cfg = cfg.load()
BridgeCommandRegistry.reloadCommands()
if (!MessageHandler.connected) instance.connect()
if (!MessageHandler.connected) MessageHandler.start(message = "Bridge reconnected")
"Bridge config reloaded!"
}
else -> {

View File

@ -16,53 +16,51 @@ abstract class BaseConfig(rootDir: File) {
val mainCfgFile: File = cfgDirectory.resolve("matterlink.cfg")
var relay = RelayOptions()
var connect = ConnectOptions()
var formatting = FormattingOptions()
var joinLeave = FormattingJoinLeave()
var debug = DebugOptions()
var incoming = IncomingOption()
var outgoing = OutgoingOptions()
var command = CommandOptions()
var death = DeathOptions()
var update = UpdateOptions()
data class RelayOptions(
var systemUser: String = "Server",
var advancements: Boolean = true,
var logLevel: String = "INFO"
)
data class FormattingOptions(
var chat: String = "<{username}> {text}",
var joinLeave: String = "§6-- {username} {text}",
var action: String = "§5* {username} {text}"
)
data class FormattingJoinLeave(
var showJoin: Boolean = true,
var showLeave: Boolean = true,
var joinServer: String = "{username:antiping} has connected to the server",
var leaveServer: String = "{username:antiping} has disconnected from the server"
data class CommandOptions(
val prefix: String = "$",
val enable: Boolean = true
)
data class ConnectOptions(
var url: String = "http://localhost:4242",
var authToken: String = "",
var gateway: String = "minecraft",
var autoConnect: Boolean = true
val url: String = "http://localhost:4242",
val authToken: String = "",
val gateway: String = "minecraft",
val autoConnect: Boolean = true
)
data class CommandOptions(
var prefix: String = "$",
var enable: Boolean = true
data class DebugOptions(
var logLevel: String = "INFO",
var announceConnect: Boolean = false,
var announceDisconnect: Boolean = false
)
data class UpdateOptions(
var enable: Boolean = true
data class IncomingOption(
val chat: String = "<{username}> {text}",
val joinPart: String = "§6-- {username} {text}",
val action: String = "§5* {username} {text}"
)
data class OutgoingOptions(
val systemUser: String = "Server",
//outgoing toggles
val advancements: Boolean = true,
var death: DeathOptions = DeathOptions(),
var joinPart: JoinPartOptions = JoinPartOptions()
)
data class DeathOptions(
var showDeath: Boolean = true,
var showDamageType: Boolean = true,
var damageTypeMapping: Map<String, String> = mapOf(
val enable: Boolean = true,
val damageType: Boolean = true,
val damageTypeMapping: Map<String, String> = mapOf(
"inFire" to "\uD83D\uDD25", //🔥
"lightningBolt" to "\uD83C\uDF29", //🌩
"onFire" to "\uD83D\uDD25", //🔥
@ -95,37 +93,27 @@ abstract class BaseConfig(rootDir: File) {
)
)
data class JoinPartOptions(
val enable: Boolean = true,
val joinServer: String = "{username:antiping} has connected to the server",
val partServer: String = "{username:antiping} has disconnected from the server"
)
data class UpdateOptions(
val enable: Boolean = true
)
protected fun load(
getBoolean: (key: String, category: String, default: Boolean, comment: String) -> Boolean,
getString: (key: String, category: String, default: String, comment: String) -> String,
getStringValidated: (key: String, category: String, default: String, comment: String, pattern: Pattern) -> String,
getStringValidValues: (key: String, category: String, default: String, comment: String, validValues: Array<String>) -> String,
addCustomCategoryComment: (key: String, comment: String) -> Unit,
getStringList: (name: String, category: String, defaultValues: Array<String>, comment: String) -> Array<String>
getStringList: (name: String, category: String, defaultValues: Array<String>, comment: String) -> Array<String>,
addCustomCategoryComment: (key: String, comment: String) -> Unit
) {
var category = "relay"
addCustomCategoryComment(category, "Relay options")
relay = RelayOptions(
systemUser = getString(
"systemUser",
category,
relay.systemUser,
"Name of the server user (used by death and advancement messages and the /say command)"
),
advancements = getBoolean(
"advancements",
category,
relay.advancements,
"Relay player advancements"
),
logLevel = getStringValidValues(
"logLevel",
category,
relay.logLevel,
"MatterLink log level",
arrayOf("INFO", "DEBUG", "TRACE")
)
)
var category = "root"
category = "commands"
addCustomCategoryComment(category, "User commands")
@ -145,64 +133,6 @@ abstract class BaseConfig(rootDir: File) {
)
)
category = "formatting"
addCustomCategoryComment(category, "Gateway -> Server" +
"Formatting options: " +
"Available variables: {username}, {text}, {gateway}, {channel}, {protocol}, {username:antiping}")
formatting = FormattingOptions(
chat = getString(
"chat",
category,
formatting.chat,
"Generic chat event, just talking"
),
joinLeave = getString(
"joinLeave",
category,
formatting.joinLeave,
"Join and leave events from other gateways"
),
action = getString(
"action",
category,
formatting.action,
"User actions (/me) sent by users from other gateways"
)
)
category = "join_leave"
addCustomCategoryComment(category, "Server -> Gateway" +
"Formatting options: " +
"Available variables: {username}, {username:antiping}")
joinLeave = FormattingJoinLeave(
showJoin = getBoolean(
"showJoin",
category,
joinLeave.showJoin,
"Relay when a player joins the game"
),
showLeave = getBoolean(
"showLeave",
category,
joinLeave.showLeave,
"Relay when a player leaves the game"
),
joinServer = getString(
"joinServer",
category,
joinLeave.joinServer,
"user join message sent to other gateways, available variables: {username}, {username:antiping}"
),
leaveServer = getString(
"leaveServer",
category,
joinLeave.leaveServer,
"user leave message sent to other gateways, available variables: {username}, {username:antiping}"
)
)
category = "connection"
addCustomCategoryComment(category, "Connection settings")
connect = ConnectOptions(
@ -231,29 +161,101 @@ abstract class BaseConfig(rootDir: File) {
"Connect the relay on startup"
)
)
category = "death"
addCustomCategoryComment(category, "Death message settings")
death = DeathOptions(
showDeath = getBoolean(
"showDeath",
category = "debug"
addCustomCategoryComment(category, "Options to help you figure out what happens and why, because computers can be silly")
debug = DebugOptions(
logLevel = getStringValidValues(
"logLevel",
category,
death.showDeath,
debug.logLevel,
"MatterLink log level",
arrayOf("INFO", "DEBUG", "TRACE")
),
announceConnect = getBoolean(
"announceConnect",
category,
debug.announceConnect,
"announce successful connection to the gateway"
),
announceDisconnect = getBoolean(
"announceDisconnect",
category,
debug.announceConnect,
"announce intention to disconnect / reconnect"
)
)
category = "incoming"
addCustomCategoryComment(category, "Gateway -> Server" +
"\nOptions all about receiving messages from the API" +
"\nFormatting options: " +
"\nAvailable variables: {username}, {text}, {gateway}, {channel}, {protocol}, {username:antiping}")
incoming = IncomingOption(
chat = getString(
"chat",
category,
incoming.chat,
"Generic chat event, just talking"
),
joinPart = getString(
"joinPart",
category,
incoming.joinPart,
"Join and part events from other gateways"
),
action = getString(
"action",
category,
incoming.action,
"User actions (/me) sent by users from other gateways"
)
)
category = "outgoing"
addCustomCategoryComment(category, "Server -> Gateway" +
"\nOptions all about sending messages to the API")
outgoing = OutgoingOptions(
systemUser = getString(
"systemUser",
category,
outgoing.systemUser,
"Name of the server user (used by death and advancement messages and the /say command)"
),
//outgoing events toggle
advancements = getBoolean(
"advancements",
category,
outgoing.advancements,
"Relay player achievements / advancements"
)
)
category = "outgoing.death"
addCustomCategoryComment(category, "Death messages settings")
outgoing.death = DeathOptions(
enable = getBoolean(
"enable",
category,
outgoing.death.enable,
"Relay player death messages"
),
showDamageType = getBoolean(
"showDamageType",
damageType = getBoolean(
"damageType",
category,
death.showDamageType,
outgoing.death.damageType,
"Enable Damage type symbols on death messages"
),
damageTypeMapping = getStringList(
"damageTypeMapping",
category,
death.damageTypeMapping.map { entry ->
outgoing.death.damageTypeMapping.map { entry ->
"${entry.key}=${entry.value}"
}
.toTypedArray(),
"Damage type mapping for everything else, " +
"Damage type mapping for death cause, " +
"\nseparate value and key with '=', " +
"\nseparate multiple values with spaces\n"
).associate {
@ -263,6 +265,34 @@ abstract class BaseConfig(rootDir: File) {
}
)
category = "outgoing.join&part"
addCustomCategoryComment(category, "relay join and part messages to the gatway" +
"\nFormatting options: " +
"\nAvailable variables: {username}, {username:antiping}")
outgoing.joinPart = JoinPartOptions(
enable = getBoolean(
"enable",
category,
outgoing.joinPart.enable,
"Relay when a player joins / parts the game" +
"\nany receiving end still needs to be configured with showJoinPart = true" +
"\nto display the messages"
),
joinServer = getString(
"joinServer",
category,
outgoing.joinPart.joinServer,
"user join message sent to other gateways, available variables: {username}, {username:antiping}"
),
partServer = getString(
"partServer",
category,
outgoing.joinPart.partServer,
"user part message sent to other gateways, available variables: {username}, {username:antiping}"
)
)
category = "update"
addCustomCategoryComment(category, "Update Settings")

View File

@ -14,16 +14,15 @@ object DeathHandler {
deathMessage: String,
damageType: String
) {
if (cfg.death.showDeath) {
if (cfg.outgoing.death.enable) {
var msg = deathMessage.replace(player, player.antiping)
if (cfg.death.showDamageType) {
val emojis = cfg.death.damageTypeMapping[damageType]?.split(' ')
if (cfg.outgoing.death.damageType) {
val emojis = cfg.outgoing.death.damageTypeMapping[damageType]?.split(' ')
?: listOf("\uD83D\uDC7B unknown type '$damageType'")
val damageEmoji = emojis[random.nextInt(emojis.size)]
msg += " " + damageEmoji
}
MessageHandler.transmit(ApiMessage(
username = cfg.relay.systemUser,
text = msg
))
}

View File

@ -9,15 +9,14 @@ import matterlink.mapFormat
object JoinLeaveHandler {
fun handleJoin(player: String) {
if (cfg.joinLeave.showJoin) {
val msg = cfg.joinLeave.joinServer.mapFormat(
if (cfg.outgoing.joinPart.enable) {
val msg = cfg.outgoing.joinPart.joinServer.mapFormat(
mapOf(
"{username}" to player,
"{username:antiping}" to player.antiping
)
)
MessageHandler.transmit(ApiMessage(
username = cfg.relay.systemUser,
text = msg,
event = JOIN_LEAVE
))
@ -25,15 +24,14 @@ object JoinLeaveHandler {
}
fun handleLeave(player: String) {
if (cfg.joinLeave.showLeave) {
val msg = cfg.joinLeave.leaveServer.mapFormat(
if (cfg.outgoing.joinPart.enable) {
val msg = cfg.outgoing.joinPart.partServer.mapFormat(
mapOf(
"{username}" to player,
"{username:antiping}" to player.antiping
)
)
MessageHandler.transmit(ApiMessage(
username = cfg.relay.systemUser,
text = msg,
event = JOIN_LEAVE
))

View File

@ -8,10 +8,9 @@ import matterlink.config.cfg
object ProgressHandler {
fun handleProgress(name: String, message: String, display: String) {
if (!cfg.relay.advancements) return
if (!cfg.outgoing.advancements) return
val usr = name.antiping
MessageHandler.transmit(ApiMessage(
username = cfg.relay.systemUser,
text = "$usr $message $display"
))
}

View File

@ -1,5 +1,5 @@
mod_name = MatterLink
mod_version = 1.5
mod_version = 1.5.1
forgelin_version = 1.6.0
curse_id = 287323
curse_release_type = beta