Skip to content

Commit

Permalink
feat: add i18n support
Browse files Browse the repository at this point in the history
  • Loading branch information
RealHeart committed Feb 7, 2024
1 parent fa4a7af commit aae6fb9
Show file tree
Hide file tree
Showing 11 changed files with 234 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.zhenxin.zmusic;

import me.zhenxin.zmusic.dependencies.annotation.RuntimeDependency;
import me.zhenxin.zmusic.platform.Platform;
import me.zhenxin.zmusic.platform.impl.LoggerBukkit;
import org.bstats.bukkit.Metrics;
import org.bukkit.plugin.java.JavaPlugin;
Expand Down Expand Up @@ -29,12 +30,13 @@ public void onLoad() {
public void onEnable() {
ZMusicKt.setLogger(new LoggerBukkit(getServer().getConsoleSender()));
ZMusicKt.setDataFolder(getDataFolder());
ZMusicKt.setPlatform(Platform.BUKKIT);
new Metrics(this, 7291);
ZMusic.INSTANCE.onEnable();
ZMusic.onEnable();
}

@Override
public void onDisable() {
ZMusic.INSTANCE.onDisable();
ZMusic.onDisable();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.zhenxin.zmusic;

import me.zhenxin.zmusic.dependencies.annotation.RuntimeDependency;
import me.zhenxin.zmusic.platform.Platform;
import me.zhenxin.zmusic.platform.impl.LoggerBungee;
import net.md_5.bungee.api.plugin.Plugin;
import org.bstats.bungeecord.Metrics;
Expand Down Expand Up @@ -29,12 +30,13 @@ public void onLoad() {
public void onEnable() {
ZMusicKt.setLogger(new LoggerBungee(getProxy().getConsole()));
ZMusicKt.setDataFolder(getDataFolder());
ZMusicKt.setPlatform(Platform.BUNGEE);
new Metrics(this, 8864);
ZMusic.INSTANCE.onEnable();
ZMusic.onEnable();
}

@Override
public void onDisable() {
ZMusic.INSTANCE.onDisable();
ZMusic.onDisable();
}
}
32 changes: 27 additions & 5 deletions zmusic-core/src/main/kotlin/me/zhenxin/zmusic/ZMusic.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package me.zhenxin.zmusic

import me.zhenxin.zmusic.config.I18n
import me.zhenxin.zmusic.config.initConfig
import me.zhenxin.zmusic.config.initI18n
import me.zhenxin.zmusic.platform.Logger
import me.zhenxin.zmusic.platform.Platform
import me.zhenxin.zmusic.utils.colored
import me.zhenxin.zmusic.utils.httpGet
import java.io.File
Expand All @@ -27,26 +30,40 @@ object ZMusic {
/**
* 插件启用
*/
@JvmStatic
fun onEnable() {
LOGO.split("\n").forEach { logger.log("&b$it".colored()) }
logger.log("\t&6v${ZMusicConstants.PLUGIN_VERSION}\tby ZhenXin".colored())
logger.log("")
logger.log("&aZMusic is loading...".colored())

logger.info("Initializing ZMusic...")
logger.info("Initializing configuration...")
initConfig()
logger.info("Initializing i18n...")
initI18n()
logger.info("ZMusic is initialized.")

I18n.Init.loaded.forEach {
logger.info(
it.replace("{version}", ZMusicConstants.PLUGIN_VERSION)
.replace("{platform}", platform.name.lowercase())
.replace("{docs-url}", "m.zplu.cc")
.replace("{author}", "ZhenXin")
)
}

thread {
logger.info(I18n.Update.checking)
httpGet("https://api.zplu.cc/version?plugin=zmusic&type=dev")
}

logger.log("&aZMusic is enabled.".colored())
}

/**
* 插件禁用
*/
@JvmStatic
fun onDisable() {
logger.log("ZMusic is disabled.")
logger.info("Disabling ZMusic...")
logger.info("ZMusic is disabled.")
}
}

Expand All @@ -55,6 +72,11 @@ object ZMusic {
*/
lateinit var dataFolder: File

/**
* 当前平台
*/
lateinit var platform: Platform

/**
* 日志
*/
Expand Down
12 changes: 7 additions & 5 deletions zmusic-core/src/main/kotlin/me/zhenxin/zmusic/config/Config.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.zhenxin.zmusic.config

import com.electronwill.nightconfig.core.CommentedConfig
import com.electronwill.nightconfig.core.file.CommentedFileConfig
import me.zhenxin.zmusic.ZMusic
import me.zhenxin.zmusic.dataFolder
Expand Down Expand Up @@ -95,15 +96,16 @@ fun initConfig() {
}

config = CommentedFileConfig.builder(configPath).autoreload().charset(Charsets.UTF_8).build()
config.load()
(config as CommentedFileConfig).load()

val currentVersion = 15
if (Config.version != currentVersion) {
// TODO: 通过语言文件获取消息
logger.error("配置文件版本不匹配,当前版本:$currentVersion,配置文件版本:${Config.version}")
logger.error("Config is outdated, please delete the config file and restart the server.")
// TODO: disablePlugin()
return
} else {
logger.info("Configuration is initialized.")
}

}

private lateinit var config: CommentedFileConfig
private var config: CommentedConfig = CommentedConfig.inMemory()
86 changes: 86 additions & 0 deletions zmusic-core/src/main/kotlin/me/zhenxin/zmusic/config/I18n.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package me.zhenxin.zmusic.config

import com.electronwill.nightconfig.core.CommentedConfig
import com.electronwill.nightconfig.toml.TomlParser
import me.zhenxin.zmusic.ZMusic
import me.zhenxin.zmusic.logger
import java.util.*

/**
* 国际化
*
* @author 真心
* @since 2024/2/7 9:19
*/
object I18n {
object Platform {
val netease: String
get() = i18n.get("platform.netease") ?: ""

val bilibili: String
get() = i18n.get("platform.bilibili") ?: ""
}

object Init {
val loaded: List<String>
get() = i18n.get("init.loaded") ?: emptyList()
}

object Update {
val checking: String
get() = i18n.get("update.checking") ?: ""

val available: List<String>
get() = i18n.get("update.available") ?: emptyList()

val notAvailable: String
get() = i18n.get("update.not_available") ?: ""
}

object Help {
val tips: String
get() = i18n.get("help.tips") ?: ""
}
}

/**
* 初始化国际化配置
*/
fun initI18n() {
// 支持的语言
val languages = arrayOf("en-US", "zh-CN")
logger.debug("Supported languages: ${languages.joinToString()}")

// 获取配置文件中的语言
var language = Config.language

// 如果是自动则使用系统语言
if (language == "auto") {
val locale = Locale.getDefault()
language = "${locale.language}-${locale.country}"
}

// 如果不支持则使用默认语言
if (language !in languages) {
logger.warn("Language $language is not supported, use default language en-US.")
logger.warn("Supported languages: ${languages.joinToString()}")
language = "en-US"
}

// 从资源文件加载
val classLoader = ZMusic::class.java.classLoader
val file = classLoader.getResource("i18n/$language.toml")
logger.debug("I18n file: $file")

// 如果文件存在则加载, 否则禁用插件
if (file != null) {
val parser = TomlParser()
i18n = parser.parse(file)
logger.info("I18n is initialized.")
} else {
logger.error("Failed to load $language.toml, please check your plugin jar.")
// TODO: disablePlugin()
}
}

private lateinit var i18n: CommentedConfig
13 changes: 12 additions & 1 deletion zmusic-core/src/main/kotlin/me/zhenxin/zmusic/platform/Logger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ interface Logger {
log("$prefix$color$message")
}

/**
* 警告日志
* @param msg String 日志信息
*/
fun warn(msg: String) {
val prefix = Config.prefix.colored()
val color = "&e".colored()
val message = msg.colored()
log("$prefix$color$message")
}

/**
* 错误日志
* @param msg String 日志信息
Expand All @@ -40,7 +51,7 @@ interface Logger {
fun debug(msg: String) {
if (Config.debug) {
val prefix = Config.prefix.colored()
val color = "&e[Debug] ".colored()
val color = "&b[Debug] ".colored()
log("$prefix$color$msg")
}
}
Expand Down
13 changes: 13 additions & 0 deletions zmusic-core/src/main/kotlin/me/zhenxin/zmusic/platform/Platform.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package me.zhenxin.zmusic.platform

/**
* 平台
*
* @author 真心
* @since 2024/2/7 14:19
*/
enum class Platform {
BUKKIT,
BUNGEE,
VELOCITY
}
6 changes: 5 additions & 1 deletion zmusic-core/src/main/resources/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ version = 15
debug = false
# 是否检查更新
check-update = true
# 插件使用的语言 (auto: 自动检测, zh_cn: 简体中文, en_us: 英语)
# 插件使用的语言
# 支持的语言:
# auto: 自动检测 (默认)
# en-US: English
# zh-CN: 简体中文
language = "auto"
# 消息前缀
prefix = "&bZMusic &e>>> &r"
Expand Down
36 changes: 36 additions & 0 deletions zmusic-core/src/main/resources/i18n/en-US.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
###############################################
# ______ __ __ _ #
# |___ / | \/ | (_) #
# / / | \ / | _ _ ___ _ ___ #
# / / | |\/| | | | | | / __| | | / __| #
# / /__ | | | | | |_| | \__ \ | | | (__ #
# /_____| |_| |_| \__,_| |___/ |_| \___| #
# #
###############################################

# Language file format: TOML (Please modify according to the specification)
# For specification, please refer to https://toml.io/en/

[platform]
netease = "Netease Cloud Music"
bilibili = "BiliBili"

[init]
loaded = [
"&aPlugin Loaded!",
"&aVersion: &b{version}",
"&aPlatform: &b{platform}",
"&aDocs: &b{docs-url}",
"&aAuthor: &b{author}",
]

[update]
checking = "&aChecking for updates..."
available = [
"&aNew version available: &b{version}",
"&aChangeLog:"
]
not_available = "&aNo new version available."

[help]
tips = "&aInput &a/&e{command} &bhelp &aShow Help."
36 changes: 36 additions & 0 deletions zmusic-core/src/main/resources/i18n/zh-CN.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
###############################################
# ______ __ __ _ #
# |___ / | \/ | (_) #
# / / | \ / | _ _ ___ _ ___ #
# / / | |\/| | | | | | / __| | | / __| #
# / /__ | | | | | |_| | \__ \ | | | (__ #
# /_____| |_| |_| \__,_| |___/ |_| \___| #
# #
###############################################

# 语言文件格式为: TOML (请按规范修改)
# 规范说明请参考 https://toml.io/cn/

[platform]
netease = "网易云音乐"
bilibili = "哔哩哔哩"

[init]
loaded = [
"&a插件加载完毕!",
"&a插件版本: &b{version}",
"&a当前平台: &b{platform}",
"&a使用文档: &b{docs-url}",
"&a插件作者: &b{author}",
]

[update]
checking = "&a正在检查更新..."
available = [
"&a发现新版本: &b{version}",
"&a更新日志:",
]
not_available = "&a当前已是最新版本!"

[help]
tips = "&a输入 &a/&e{command} &bhelp &a查看帮助."
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import me.zhenxin.zmusic.platform.Platform;
import me.zhenxin.zmusic.platform.impl.LoggerVelocity;
import org.bstats.velocity.Metrics;

Expand Down Expand Up @@ -40,12 +41,13 @@ public ZMusicVelocity(ProxyServer server, Logger logger, @DataDirectory Path dat
public void onProxyInitialization(ProxyInitializeEvent event) {
ZMusicKt.setLogger(new LoggerVelocity(server.getConsoleCommandSource()));
ZMusicKt.setDataFolder(dataDirectory.toFile());
ZMusicKt.setPlatform(Platform.VELOCITY);
metricsFactory.make(this, 12426);
ZMusic.INSTANCE.onEnable();
ZMusic.onEnable();
}

@Subscribe
public void onProxyShutdown(ProxyShutdownEvent event) {
ZMusic.INSTANCE.onDisable();
ZMusic.onDisable();
}
}

0 comments on commit aae6fb9

Please sign in to comment.