refactor: rewrite all

This commit is contained in:
Caixukun1919810
2024-02-16 13:52:46 +08:00
committed by GitHub
Unverified
15 changed files with 604 additions and 7528 deletions
-229
View File
@@ -1,229 +0,0 @@
#include "Config.h"
#include "Global.h"
#include <GMLIB/Event/Entity/ItemActorSpawnEvent.h>
#include <GMLIB/Event/Entity/MobPickupItemEvent.h>
#include <GMLIB/Server/PlayerAPI.h>
#include <regex>
using namespace ll::schedule;
using namespace ll::chrono_literals;
int item_despawn_time = 3000;
ServerTimeAsyncScheduler scheduler;
bool auto_clean_triggerred = false;
namespace Cleaner {
bool isMatch(std::string& A, std::string& B) {
// 如果B是正则表达式
if (B.find_first_of(".*+?()[]{}|^$") != std::string::npos) {
try {
std::regex regex(B);
return std::regex_match(A, regex);
} catch (...) {
return false;
}
}
return (A == B);
}
bool shouldIgnore(GMLIB_Actor* ac) {
if (ac->isMob() || ac->isItemActor()) {
if (ac->isTame() || ac->isTrusting() || ac->getNameTag() != "") {
return true;
}
auto nbt = ac->getNbt();
if (nbt->getByte("ShowBottom") == 1) { // End Crystal Used Only, if has this tag 1b, it is modified by cleaner.
return true;
}
}
return false;
}
bool ShouldClean(Actor* actor) {
// Players
auto en = (GMLIB_Actor*)actor;
if (en->isPlayer() || shouldIgnore(en)) {
return false;
}
auto type = en->getTypeName();
// Items
if (en->isItemActor()) {
if (Config->getValue<bool>({"CleanItem", "Enabled"}, false)) {
auto itac = (ItemActor*)en;
if (itac->age() <= Config->getValue<int>({"CleanItem", "ExistTicks"}, 0)) {
return false;
}
auto itemType = itac->item().getTypeName();
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanItem", "Whitelist"}, {});
for (auto& key : whitelist) {
if (isMatch(itemType, key)) {
return false;
}
}
return true;
}
return false;
}
// Mobs
else if (en->isMob()) {
if (Config->getValue<bool>({"CleanMobs", "Enabled"}, false)) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanMobs", "Blacklist"}, {});
for (auto& key : blacklist) {
if (isMatch(type, key)) {
return true;
}
}
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanMobs", "Whitelist"}, {});
for (auto& key : whitelist) {
if (isMatch(type, key)) {
return false;
}
}
if (Config->getValue<bool>({"CleanMobs", "CleanMonstors"}, false)
&& en->hasCategory(ActorCategory::Monster)) {
return true;
}
if (Config->getValue<bool>({"CleanMobs", "CleanPeacefulMobs"}, false)) {
return true;
}
}
return false;
}
// Others
else {
if (Config->getValue<bool>({"CleanInanimate", "Enabled"}, false)) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanInanimate", "Blacklist"}, {});
for (auto& key : blacklist) {
if (isMatch(type, key)) {
return true;
}
}
}
return false;
}
}
int ExecuteClean() {
int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities();
for (auto entity : all_entities) {
if (ShouldClean(entity)) {
entity->despawn();
clean_count++;
}
}
return clean_count;
}
int CountEntities() {
int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities();
for (auto entity : all_entities) {
if (ShouldClean(entity)) {
clean_count++;
}
}
return clean_count;
}
void CleanTask() {
auto time = Config->getValue<int>({"Basic", "Notice1"}, 20);
auto announce_time = Config->getValue<int>({"Basic", "Notice2"}, 15);
auto time_1 = std::chrono::seconds::duration(time);
auto time_2 = std::chrono::seconds::duration(time - announce_time);
logger.info(tr("cleaner.output.count1", {S(time_1.count())}));
scheduler.add<DelayTask>(time_2, [announce_time] { logger.info(tr("cleaner.output.count2", {S(announce_time)})); });
scheduler.add<DelayTask>(time_1, [] {
auto count = ExecuteClean();
logger.info(tr("cleaner.output.finish", {S(count)}));
auto_clean_triggerred = false;
});
}
void AutoCleanTask(int seconds) {
auto time = std::chrono::seconds::duration(seconds);
mAutoCleanTask = scheduler.add<RepeatTask>(time, [] { CleanTask(); });
}
void CheckCleanTask(int max_entities, float min_tps) {
mCheckCleanTask = scheduler.add<RepeatTask>(10s, [max_entities, min_tps] {
auto count = CountEntities();
if (auto_clean_triggerred == false) {
if (count >= max_entities) {
auto_clean_triggerred = true;
logger.warn(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
CleanTask();
} else if (GMLIB_Level::getLevel()->getServerAverageTps() <= min_tps) {
auto_clean_triggerred = true;
logger.warn(
tr("cleaner.output.triggerAutoCleanCount", {S(GMLIB_Level::getLevel()->getServerAverageTps())})
);
CleanTask();
}
}
});
}
void setShouldIgnore(GMLIB_Actor* ac) {
auto nbt = ac->getNbt();
nbt->put("ShowBottom", ByteTag(1));
ac->setNbt(*nbt);
}
void ListenEvents() {
auto eventBus = &ll::event::EventBus::getInstance();
// ItemSpawnEvent
eventBus->emplaceListener<GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent>(
[](GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent& event) {
auto& item = event.getItemActor();
auto pl = (GMLIB_Player*)event.getSpawner();
if (pl) {
if (pl->isPlayer() && !pl->isAlive()) { // Death Drop
auto ac = (GMLIB_Actor*)&item;
setShouldIgnore(ac);
return;
}
}
item.lifeTime() = item_despawn_time;
}
);
// MobTakeItemEvent
eventBus->emplaceListener<GMLIB::Event::EntityEvent::MobPickupItemAfterEvent>(
[](GMLIB::Event::EntityEvent::MobPickupItemAfterEvent& event) {
// auto item = event.getItemActor().item().getTypeName();
auto mob = (GMLIB_Actor*)&event.self();
setShouldIgnore(mob);
}
);
}
void reloadCleaner() {
unloadCleaner();
loadCleaner();
}
void loadCleaner() {
ListenEvents();
RegisterCommands();
if (Config->getValue<bool>({"ScheduleClean", "Enabled"}, false)) {
Cleaner::AutoCleanTask(Config->getValue<int>({"ScheduleClean", "CleanInterval"}, 3000));
}
if (Config->getValue<bool>({"AutoCleanCount", "Enabled"}, false)
|| Config->getValue<bool>({"AutoCleanTPS", "Enabled"}, false)) {
Cleaner::CheckCleanTask(
Config->getValue<int>({"AutoCleanCount", "TriggerCount"}, 900),
Config->getValue<int>({"AutoCleanTPS", "TriggerTPS"}, 15)
);
}
item_despawn_time = Config->getValue<int>({"ItemDespawn", "DespawnTime"}, 6000);
}
void unloadCleaner() {
mAutoCleanTask->cancel();
mCheckCleanTask->cancel();
delete Config;
}
} // namespace Cleaner
+19 -19
View File
@@ -1,16 +1,20 @@
#pragma once
#include "Global.h"
inline std::string defaultConfig = R"({
std::string defaultConfig = R"({
"Basic": {
"Language": "en_US",
"ConsoleLog": true,
"Command": "cleaner",
"Notice1": 20,
"Notice2": 5,
"ConsoleLog": true,
"SendBroadcast": true,
"SendToast": false
"SendToast": true
},
"IgnoreTags": [
"ignore",
"不清理"
],
"AutoCleanCount": {
"Enabled": true,
"TriggerCount": 900
@@ -27,6 +31,7 @@ inline std::string defaultConfig = R"({
]
},
"CleanInanimate": {
"Enabled": true,
"Blacklist": [
"minecraft:xp_orb",
"minecraft:arrow",
@@ -35,8 +40,7 @@ inline std::string defaultConfig = R"({
"minecraft:wither_skull",
"minecraft:wither_skull_dangerous",
"minecraft:dragon_fireball"
],
"Enabled": true
]
},
"CleanItem": {
"Enabled": true,
@@ -66,17 +70,13 @@ inline std::string defaultConfig = R"({
]
},
"CleanMobs": {
"BlackList": [
"minecraft:guardian",
"minecraft:zombie_pigman"
],
"Enabled": true,
"CleanMonstors": true,
"CleanPeacefulMobs": false,
"EnableAutoExclude": true,
"Enabled": true,
"IgnoreTags": [
"ignore",
"不清理"
"BlackList": [
"minecraft:guardian",
"minecraft:zombie_pigman"
],
"Whitelist": [
"minecraft:ender_dragon",
@@ -89,14 +89,14 @@ inline std::string defaultConfig = R"({
]
},
"ScheduleClean": {
"CleanInterval": 3600,
"Enabled": true
"Enabled": true,
"CleanInterval": 3600
},
"VoteClean": {
"CD": 120,
"Delay": 30,
"Enabled": true,
"Percentage": 50,
"VoteCleanCommand": "voteclean"
"VoteCleanCommand": "voteclean",
"Cooldown": 120,
"CheckDelay": 30,
"Percentage": 50
}
})";
+124
View File
@@ -0,0 +1,124 @@
#include "Cleaner.h"
namespace Cleaner {
bool isMatch(std::string& A, std::string& B) {
// 如果B是正则表达式
if (B.find_first_of(".*+?()[]{}|^$") != std::string::npos) {
try {
std::regex regex(B);
return std::regex_match(A, regex);
} catch (...) {
return false;
}
}
return (A == B);
}
bool shouldIgnore(GMLIB_Actor* ac) {
if (ac->isMob() || ac->isItemActor()) {
if (ac->isTame() || ac->isTrusting() || ac->getNameTag() != "") {
return true;
}
auto nbt = ac->getNbt();
if (nbt->getByte("ShowBottom") == 1) { // End Crystal Used Only, if has this tag 1b, it is modified by cleaner.
return true;
}
}
return false;
}
bool ShouldClean(Actor* actor) {
// Players
auto en = (GMLIB_Actor*)actor;
if (en->isPlayer() || shouldIgnore(en)) {
return false;
}
auto type = en->getTypeName();
auto tags = Config->getValue<std::vector<std::string>>({"IgnoreTags"}, {});
for (auto& tag : tags) {
if (en->hasTag(tag)) {
return false;
}
}
// Items
if (en->isItemActor()) {
if (Config->getValue<bool>({"CleanItem", "Enabled"}, false)) {
auto itac = (ItemActor*)en;
if (itac->age() <= Config->getValue<int>({"CleanItem", "ExistTicks"}, 0)) {
return false;
}
auto itemType = itac->item().getTypeName();
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanItem", "Whitelist"}, {});
for (auto& key : whitelist) {
if (isMatch(itemType, key)) {
return false;
}
}
return true;
}
return false;
}
// Mobs
else if (en->isMob()) {
if (Config->getValue<bool>({"CleanMobs", "Enabled"}, false)) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanMobs", "Blacklist"}, {});
for (auto& key : blacklist) {
if (isMatch(type, key)) {
return true;
}
}
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanMobs", "Whitelist"}, {});
for (auto& key : whitelist) {
if (isMatch(type, key)) {
return false;
}
}
if (Config->getValue<bool>({"CleanMobs", "CleanMonstors"}, false)
&& en->hasCategory(ActorCategory::Monster)) {
return true;
}
if (Config->getValue<bool>({"CleanMobs", "CleanPeacefulMobs"}, false)) {
return true;
}
}
return false;
}
// Others
else {
if (Config->getValue<bool>({"CleanInanimate", "Enabled"}, false)) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanInanimate", "Blacklist"}, {});
for (auto& key : blacklist) {
if (isMatch(type, key)) {
return true;
}
}
}
return false;
}
}
int ExecuteClean() {
int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities();
for (auto entity : all_entities) {
if (ShouldClean(entity)) {
entity->despawn();
clean_count++;
}
}
return clean_count;
}
int CountEntities() {
int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities();
for (auto entity : all_entities) {
if (ShouldClean(entity)) {
clean_count++;
}
}
return clean_count;
}
} // namespace Cleaner
+105
View File
@@ -0,0 +1,105 @@
#include "Cleaner.h"
namespace ConfigFile {
bool mConsoleLog = true;
bool mAnnounce = true;
bool mSendToast = true;
} // namespace ConfigFile
namespace Cleaner {
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mAutoCleanTask;
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mCheckCleanTask;
ServerTimeScheduler scheduler;
bool auto_clean_triggerred = false;
void CleanTask() {
auto time = Config->getValue<int>({"Basic", "Notice1"}, 20);
auto announce_time = Config->getValue<int>({"Basic", "Notice2"}, 5);
auto time_1 = std::chrono::seconds::duration(time);
auto time_2 = std::chrono::seconds::duration(time - announce_time);
if (ConfigFile::mConsoleLog) {
logger.info(tr("cleaner.output.count1", {S(time_1.count())}));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.count1", {S(time_1.count())}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)}));
}
scheduler.add<DelayTask>(time_2, [announce_time] {
if (ConfigFile::mConsoleLog) {
logger.info(tr("cleaner.output.count2", {S(announce_time)}));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.count2", {S(announce_time)}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)}));
}
});
scheduler.add<DelayTask>(time_1, [] {
auto count = ExecuteClean();
if (ConfigFile::mConsoleLog) {
logger.info(tr("cleaner.output.finish", {S(count)}));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.finish", {S(count)}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.finish", {S(count)}));
}
auto_clean_triggerred = false;
});
}
void AutoCleanTask(int seconds) {
auto time = std::chrono::seconds::duration(seconds);
mAutoCleanTask = scheduler.add<RepeatTask>(time, [] { CleanTask(); });
}
void CheckCleanTask(int max_entities, float min_tps) {
mCheckCleanTask = scheduler.add<RepeatTask>(10s, [max_entities, min_tps] {
auto count = CountEntities();
if (auto_clean_triggerred == false) {
if (count >= max_entities) {
auto_clean_triggerred = true;
if (ConfigFile::mConsoleLog) {
logger.warn(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
}
CleanTask();
} else if (GMLIB_Level::getLevel()->getServerAverageTps() <= min_tps) {
auto_clean_triggerred = true;
auto mspt = S(GMLIB_Level::getLevel()->getServerAverageTps());
if (ConfigFile::mConsoleLog) {
logger.warn(tr("cleaner.output.triggerAutoCleanCount", {mspt}));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanCount", {mspt}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanCount", {mspt}));
}
CleanTask();
}
}
});
}
void stopAllTasks() {
mCheckCleanTask->cancel();
mAutoCleanTask->cancel();
}
} // namespace Cleaner
+33
View File
@@ -0,0 +1,33 @@
#include "Cleaner.h"
namespace Cleaner {
void loadCleaner() {
if (Config->getValue<bool>({"ScheduleClean", "Enabled"}, false)) {
Cleaner::AutoCleanTask(Config->getValue<int>({"ScheduleClean", "CleanInterval"}, 3000));
}
if (Config->getValue<bool>({"AutoCleanCount", "Enabled"}, false)
|| Config->getValue<bool>({"AutoCleanTPS", "Enabled"}, false)) {
Cleaner::CheckCleanTask(
Config->getValue<int>({"AutoCleanCount", "TriggerCount"}, 900),
Config->getValue<int>({"AutoCleanTPS", "TriggerTPS"}, 15)
);
}
ConfigFile::mItemDespawnTicks = Config->getValue<int>({"ItemDespawn", "DespawnTime"}, 6000);
ConfigFile::mAnnounce = Config->getValue<bool>({"Basic", "SendBroadcast"}, true);
ConfigFile::mConsoleLog = Config->getValue<bool>({"Basic", "ConsoleLog"}, true);
ConfigFile::mSendToast = Config->getValue<bool>({"Basic", "SendToast"}, true);
}
void unloadCleaner() { stopAllTasks(); }
void reloadCleaner() {
unloadCleaner();
Config->init();
std::string languageCode = Config->getValue<std::string>({"Basic", "Language"}, "en_US");
Language->loadAllLanguages();
Language->chooseLanguage(languageCode);
loadCleaner();
}
} // namespace Cleaner
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "Global.h"
using namespace ll::schedule;
using namespace ll::chrono_literals;
namespace Cleaner {
extern ServerTimeScheduler scheduler;
extern int ExecuteClean();
extern int CountEntities();
extern void AutoCleanTask(int seconds);
extern void CheckCleanTask(int max_entities, float min_tps);
extern void ListenEvents();
extern void stopAllTasks();
extern void CleanTask();
extern void reloadCleaner();
extern void loadCleaner();
extern void unloadCleaner();
} // namespace Cleaner
namespace VoteClean {
extern void voteCommandExecute(Player* pl);
}
+44
View File
@@ -0,0 +1,44 @@
#include "Cleaner.h"
namespace ConfigFile {
int mItemDespawnTicks = 3000;
} // namespace ConfigFile
namespace Cleaner {
void setShouldIgnore(GMLIB_Actor* ac) {
auto nbt = ac->getNbt();
nbt->put("ShowBottom", ByteTag(1));
ac->setNbt(*nbt);
}
void ListenEvents() {
auto& eventBus = ll::event::EventBus::getInstance();
// ItemSpawnEvent
eventBus.emplaceListener<GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent>(
[](GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent& event) {
auto& item = event.getItemActor();
auto pl = (GMLIB_Player*)event.getSpawner();
if (pl) {
if (pl->isPlayer() && !pl->isAlive()) { // Death Drop
auto ac = (GMLIB_Actor*)&item;
setShouldIgnore(ac);
return;
}
}
item.lifeTime() = ConfigFile::mItemDespawnTicks;
}
);
// MobTakeItemEvent
eventBus.emplaceListener<GMLIB::Event::EntityEvent::MobPickupItemAfterEvent>(
[](GMLIB::Event::EntityEvent::MobPickupItemAfterEvent& event) {
auto mob = (GMLIB_Actor*)&event.self();
setShouldIgnore(mob);
}
);
}
} // namespace Cleaner
+14
View File
@@ -0,0 +1,14 @@
#include "Global.h"
namespace Helper {
void broadcastMessage(std::string msg) {
TextPacket::createRawMessage(tr("cleaner.info.prefix") + msg).sendToClients();
}
void broadcastToast(std::string msg) {
auto pkt = ToastRequestPacket(tr("cleaner.info.prefix"), msg);
pkt.sendToClients();
}
} // namespace Helper
+138
View File
@@ -0,0 +1,138 @@
#include "Cleaner.h"
#include "Global.h"
namespace VoteClean {
bool hasVote = false;
bool canVote = true;
int playerCount = 0;
std::unordered_map<mce::UUID, bool> voteList;
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mAutoCleanTask;
int getPlayerCount() {
int result = 0;
ll::service::getLevel()->forEachPlayer([&](Player& pl) -> bool {
if (!pl.isSimulatedPlayer()) {
result++;
}
return true;
});
return result;
}
void sendVoteForm(Player* pl) {
auto fm = ll::form::ModalForm(
tr("cleaner.vote.title"),
tr("cleaner.vote.subtitle", {pl->getRealName()}),
tr("cleaner.vote.ok"),
tr("cleaner.vote.no")
);
ll::service::getLevel()->forEachPlayer([&](Player& pl) -> bool {
fm.sendTo(pl, [](Player& player, ll::form::ModalForm::SelectedButton button) {
switch (button) {
case ll::form::ModalForm::SelectedButton::Upper: {
voteList[player.getUuid()] = true;
player.sendMessage(tr("cleaner.vote.accept"));
return;
}
case ll::form::ModalForm::SelectedButton::Lower: {
voteList[player.getUuid()] = false;
player.sendMessage(tr("cleaner.vote.deny"));
return;
}
default:
return;
}
});
return true;
});
}
void checkVote() {
float percentage = Config->getValue<float>({"VoteClean", "Percentage"}, 50.0f) / 100.0f;
int voteCount = 0;
for (auto& key : voteList) {
if (key.second == true) {
voteCount++;
}
}
float result = ((float)voteCount) / ((float)playerCount);
if (result >= percentage) {
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.vote.succeed"));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.vote.succeed"));
}
Cleaner::CleanTask();
} else {
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.vote.failed"));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.vote.failed"));
}
}
hasVote = false;
playerCount = 0;
}
void voteClean(Player* pl) {
voteList.clear();
canVote = false;
hasVote = true;
playerCount = getPlayerCount();
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.vote.voteMessage", {pl->getRealName()}));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.vote.voteMessage", {pl->getRealName()}));
}
sendVoteForm(pl);
auto cooldown = std::chrono::seconds::duration(Config->getValue<int>({"VoteClean", "Cooldown"}, 120));
auto waitTime = std::chrono::seconds::duration(Config->getValue<int>({"VoteClean", "CheckDelay"}, 30));
Cleaner::scheduler.add<DelayTask>(cooldown, [] { canVote = false; });
Cleaner::scheduler.add<DelayTask>(waitTime, [] { checkVote(); });
}
void confirmForm(Player* pl) {
auto fm = ll::form::ModalForm(
tr("cleaner.vote.title"),
tr("cleaner.vote.confirmTubtitle"),
tr("cleaner.vote.confirmOk"),
tr("cleaner.vote.confirmNo")
);
fm.sendTo(*pl, [](Player& player, ll::form::ModalForm::SelectedButton button) {
switch (button) {
case ll::form::ModalForm::SelectedButton::Upper: {
return voteClean(&player);
}
case ll::form::ModalForm::SelectedButton::Lower: {
return player.sendMessage(tr("cleaner.vote.cancel"));
}
default:
return;
}
});
}
void voteCommandExecute(Player* pl) {
if (!hasVote) {
if (canVote) {
confirmForm(pl);
} else {
pl->sendMessage(tr("cleaner.vote.cooldown"));
}
} else {
if (voteList.count(pl->getUuid())) {
pl->sendMessage(tr("cleaner.vote.voted"));
} else {
voteList[pl->getUuid()] = true;
pl->sendMessage(tr("cleaner.vote.accept"));
}
}
}
} // namespace VoteClean
+13 -12
View File
@@ -1,27 +1,28 @@
#pragma once
#include "Plugin.h"
#include <include_all.h>
#include <regex>
#define S(x) std::to_string(x)
extern ll::Logger logger;
extern GMLIB::Files::JsonConfig* Config;
extern GMLIB::Files::I18n::JsonI18n* Language;
extern void RegisterCommands();
extern void initPlugin();
extern int item_despawn_time;
namespace ConfigFile {
extern int mItemDespawnTicks;
extern bool mConsoleLog;
extern bool mAnnounce;
extern bool mSendToast;
} // namespace ConfigFile
namespace Cleaner {
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mAutoCleanTask;
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mCheckCleanTask;
extern void loadCleaner();
extern void unloadCleaner();
extern void reloadCleaner();
extern void CleanTask();
} // namespace Cleaner
namespace Helper {
extern void broadcastMessage(std::string msg);
extern void broadcastToast(std::string msg);
} // namespace Helper
extern std::string tr(std::string key, std::vector<std::string> data = {});
+1 -2
View File
@@ -12,10 +12,9 @@ void initPlugin() {
std::string langPath = "./plugins/Cleaner/language/";
std::string languageCode = Config->getValue<std::string>({"Basic", "Language"}, "en_US");
Language = new GMLIB::Files::I18n::JsonI18n(langPath, languageCode);
// Language->updateOrCreateLanguage("en_US", defaultLanguage_en_US);
Language->updateOrCreateLanguage("en_US", defaultLanguage_en_US);
Language->updateOrCreateLanguage("zh_CN", defaultLanguage_zh_CN);
Language->loadAllLanguages();
logger.warn("language {}", languageCode);
Language->chooseLanguage(languageCode);
}
+44 -4
View File
@@ -1,13 +1,51 @@
#pragma once
#include "Global.h"
std::string defaultLanguage_en_US = R"({
"cleaner.info.prefix": "§e§l[Cleaner] §r",
"cleaner.command.cleaner": "Cleaner admin command.",
"cleaner.command.despawnSuccess": "Successfully despawned %1$s entities.",
"cleaner.command.error.noTarget": "No targets matched the selector.",
"cleaner.command.error.playerOnly": "This command can only be executed by players!",
"cleaner.command.tps.output": "Current server real-time TPS %1$s §r, average TPS %2$s.",
"cleaner.command.mspt.output": "Current server MSPT %1$s.",
"cleaner.command.clean.output": "Clean task successfully initiated!",
"cleaner.command.voteclean": "Initiate entity clean vote.",
"cleaner.command.despawntime": "Despawn time for items set to %1$s game ticks.",
"cleaner.output.count1": "The system will automatically clean server entities in %1$s seconds!",
"cleaner.output.count2": "Attention! The system will automatically clean server entities in %1$s seconds!",
"cleaner.output.finish": "Cleaning complete! A total of %1$s entities have been cleaned this time.",
"cleaner.output.opClean": "Admin has enabled server entity cleaning.",
"cleaner.output.reload": "Cleaner plugin reloaded. Some configurations may require a server restart to take effect.",
"cleaner.output.triggerAutoCleanCount": "Too many server entities detected! There are %1$s cleanable entities currently on the server. Auto-clean program has been activated.",
"cleaner.output.triggerAutoCleanTps": "Low TPS detected! Server average TPS %1$s\nClean program has been initiated.",
"cleaner.vote.cooldown": "Vote cleaning cooldown...",
"cleaner.vote.cancel": "Vote canceled!",
"cleaner.vote.confirmNo": "Think again",
"cleaner.vote.confirmOk": "Initiate vote",
"cleaner.vote.confirmTubtitle": "Do you want to initiate a clean vote?",
"cleaner.vote.accept": "You have agreed to entity cleaning.",
"cleaner.vote.deny": "You have declined entity cleaning.",
"cleaner.vote.no": "Deny",
"cleaner.vote.ok": "Agree",
"cleaner.vote.subtitle": "%1$s lunched a clean vote.\n\n Do you agree to clean server entities now?",
"cleaner.vote.timeout": "Vote has expired!",
"cleaner.vote.succeed": "Vote cleaning successful!",
"cleaner.vote.failed": "Vote cleaning did not passed!",
"cleaner.vote.title": "Vote Cleaning",
"cleaner.vote.voted": "You have been voted!",
"cleaner.vote.voteMessage": "%1$s lunched a clean vote. If you agree cleaning entities but did not received a form, please type command /voteclean to vote."
})";
std::string defaultLanguage_zh_CN = R"({
"cleaner.toast.title": "§e§lCleaner",
"cleaner.command.cleaner": "Cleaner管理员命令。",
"cleaner.command.despawnSuccess": "已成功清除了 %1$s 个实体",
"cleaner.command.error.noTarget": "没有与选择器匹配的目标",
"cleaner.command.error.playerOnly": "该命令只能由玩家执行!",
"cleaner.command.tps.output": "当前服务器实时TPS %1$s §r,平均TPS %2$s",
"cleaner.command.mspt.output": "当前服务器实MSPT %1$s",
"cleaner.command.clean.output": "已成功启动清理任务!",
"cleaner.command.voteclean": "发起实体清理投票。",
"cleaner.command.despawntime" : "已成功将物品消失时间设置为 %1$s 游戏刻",
"cleaner.output.count1": "系统将在 %1$s 秒后自动清理服务器实体!",
@@ -17,7 +55,7 @@ std::string defaultLanguage_zh_CN = R"({
"cleaner.output.reload": "已重载Cleaner插件,部分配置可能需要重启服务器才能生效。",
"cleaner.output.triggerAutoCleanCount": "检测到服务器实体过多!!当前服务器存在 %1$s 个可清理实体,已启动自动清理程序。",
"cleaner.output.triggerAutoCleanTps": "当前服务器TPS过低!!服务器平均TPS %1$s\n系统已启动清理程序。",
"cleaner.vote.cooldown": "投票清理冷却...",
"cleaner.vote.cooldown": "投票清理正在冷却...",
"cleaner.vote.cancel": "投票已取消!",
"cleaner.vote.confirmNo": "我再想想",
"cleaner.vote.confirmOk": "发起投票",
@@ -26,9 +64,11 @@ std::string defaultLanguage_zh_CN = R"({
"cleaner.vote.deny": "你已拒绝实体清理。",
"cleaner.vote.no": "拒绝",
"cleaner.vote.ok": "同意",
"cleaner.vote.Subtitle": "你是否同意现在清理服务器实体?",
"cleaner.vote.Timeout": "投票已过期!",
"cleaner.vote.subtitle": "%1$s 发起了服务器实体清理投票!\n\n你是否同意现在清理服务器实体?",
"cleaner.vote.timeout": "投票已过期!",
"cleaner.vote.succeed": "投票清理成功!",
"cleaner.vote.failed": "投票清理未通过。",
"cleaner.vote.title": "投票清理",
"cleaner.vote.toastNotice": "通知"
"cleaner.vote.voted": "你已经投过票了!",
"cleaner.vote.voteMessage": "%1$s 发起了服务器实体清理投票!如果同意清理但是未收到表单,请输入命令 /voteclean 投票。拒绝清理请忽略此信息。"
})";
+3
View File
@@ -1,3 +1,4 @@
#include "Features/Cleaner.h"
#include "Global.h"
ll::Logger logger("Cleaner");
@@ -10,6 +11,8 @@ Plugin::Plugin(ll::plugin::NativePlugin& self) : mSelf(self) {
}
bool Plugin::enable() {
Cleaner::ListenEvents();
RegisterCommands();
Cleaner::loadCleaner();
logger.info("Cleaner Loaded!");
logger.info("Author: GroupMountain");
+32 -19
View File
@@ -1,3 +1,4 @@
#include "Features/Cleaner.h"
#include "Global.h"
struct CleanerParam {
@@ -33,7 +34,16 @@ void RegCleanerCommand() {
switch (param.action) {
case CleanerParam::Action::clean: {
Cleaner::CleanTask();
return output.success(tr("cleaner.output.opClean"));
if (ConfigFile::mConsoleLog) {
logger.info(tr("cleaner.output.opClean"));
}
if (ConfigFile::mAnnounce) {
Helper::broadcastMessage(tr("cleaner.output.opClean"));
}
if (ConfigFile::mSendToast) {
Helper::broadcastToast(tr("cleaner.output.opClean"));
}
return output.success(tr("cleaner.command.clean.output"));
}
case CleanerParam::Action::tps: {
return output.success(
@@ -55,27 +65,30 @@ void RegCleanerCommand() {
.required("despawntime")
.required("ticks")
.execute<[&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) {
item_despawn_time = param.ticks;
Config->setValue({"ItemDespawn", "DespawnTime"}, item_despawn_time);
return output.success(tr("cleaner.command.despawntime", {S(item_despawn_time)}));
ConfigFile::mItemDespawnTicks = param.ticks;
Config->setValue({"ItemDespawn", "DespawnTime"}, ConfigFile::mItemDespawnTicks);
return output.success(tr("cleaner.command.despawntime", {S(ConfigFile::mItemDespawnTicks)}));
}>();
};
void RegisterCommands() {
RegCleanerCommand();
// RegVoteCommand(registry);
void RegVoteCommand() {
auto& cmd = ll::command::CommandRegistrar::getInstance().getOrCreateCommand(
Config->getValue<std::string>({"VoteClean", "VoteCleanCommand"}, "voteclean"),
tr("cleaner.command.voteclean"),
CommandPermissionLevel::Any
);
cmd.overload().execute<[&](CommandOrigin const& origin, CommandOutput& output) {
if (origin.getOriginType() == CommandOriginType::Player) {
auto pl = (Player*)origin.getEntity();
return VoteClean::voteCommandExecute(pl);
}
return output.error(tr("cleaner.command.error.playerOnly"));
}>();
}
/*
void RegVoteCommand(CommandRegistry& registry) {
auto command = DynamicCommand::createCommand(registry, "voteclean", "Clean entities", CommandPermissionLevel::Any);
command->addOverload();
command->setCallback([](DynamicCommand const& cmd,
CommandOrigin const& origin,
CommandOutput& output,
std::unordered_map<std::string, DynamicCommand::Result>& result) {
// vote clean command
});
DynamicCommand::setup(registry, std::move(command));
void RegisterCommands() {
RegCleanerCommand();
if (Config->getValue<bool>({"VoteClean", "Enabled"}, false)) {
RegVoteCommand();
}
}
*/
-7238
View File
File diff suppressed because it is too large Load Diff