Skip to content

Commit

Permalink
feat: Improve notify service (Close #9)
Browse files Browse the repository at this point in the history
  • Loading branch information
blank038 committed Jul 16, 2024
1 parent 7013f00 commit b6d21e4
Show file tree
Hide file tree
Showing 19 changed files with 311 additions and 38 deletions.
1 change: 1 addition & 0 deletions bukkit/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies {
implementation "com.aystudio.core:AyCore:1.1.0-BETA"
implementation "de.tr7zw:item-nbt-api-plugin:2.11.1"
implementation "net.milkbowl.vault:VaultAPI:1.7"
implementation group: 'io.netty', name: 'netty-all', version: '4.1.111.Final'

compileOnly("org.projectlombok:lombok:1.18.24")
annotationProcessor("org.projectlombok:lombok:1.18.24")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import com.blank038.servermarket.internal.enums.PayType;
import com.blank038.servermarket.api.handler.filter.FilterHandler;
import com.blank038.servermarket.internal.gui.impl.MarketGui;
import com.blank038.servermarket.internal.service.notify.INotifyService;
import com.blank038.servermarket.internal.service.notify.NotifyCenter;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
Expand Down Expand Up @@ -96,4 +98,20 @@ public static void sendTaxes(PayType payType, String subData, double tax) {
ServerMarket.getInstance().getLogger().log(Level.WARNING, "Fail to send the tax payment to " + taxAccount);
}
}

public static void registerService(String source, Class<? extends INotifyService> classZ) {
NotifyCenter.register(source, classZ);
}

public static INotifyService createService(String source, ConfigurationSection config) {
if (!NotifyCenter.isRegister(source)) {
return null;
}
try {
INotifyService service = NotifyCenter.findNotifyClass(source).newInstance();
return NotifyCenter.create(source, service, config);
} catch (Exception e) {
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ public interface IPlatformApi {

ITaskWrapper runTask(JavaPlugin plugin, Runnable runnable);

ITaskWrapper runTaskTimerAsynchronously(JavaPlugin plugin, Runnable runnable, long delay, long period);
ITaskWrapper runTaskAsynchronously(JavaPlugin plugin, Runnable runnable);

ITaskWrapper runTaskTimerAsynchronously(JavaPlugin plugin, Runnable runnable, long delaySecond, long periodSecond);
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ public void initialize() {
"CREATE TABLE IF NOT EXISTS `servermarket_sales` ( `sale_uuid` VARCHAR(36) NOT NULL, `market` VARCHAR(20) NOT NULL, `owner_name` VARCHAR(20) NOT NULL, `owner_uuid` VARCHAR(36) NOT NULL, `pay_type` VARCHAR(20) NOT NULL, `eco_type` VARCHAR(50), `price` int, `data` TEXT, `post_time` TIMESTAMP NOT NULL, PRIMARY KEY (`sale_uuid`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;",
"CREATE TABLE IF NOT EXISTS `servermarket_logs` ( `id` INT AUTO_INCREMENT, `trigger_time` TIMESTAMP, `trigger_uuid` VARCHAR(36) NOT NULL, `market` VARCHAR(50), `log_type` VARCHAR(10) NOT NULL, `data` TEXT, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;",
"CREATE TABLE IF NOT EXISTS `servermarket_offline_transactions` ( `id` INT AUTO_INCREMENT, `owner_uuid` VARCHAR(36) NOT NULL, `market` VARCHAR(50) NOT NULL, `amount` INT, `pay_type` VARCHAR(20) NOT NULL, `eco_type` VARCHAR(50), PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;"

};
storageHandler = new MySqlStorageHandler(
ServerMarket.getInstance(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ private void saveLogs() {

@Override
public void initialize() {
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(ServerMarket.getInstance(), this::saveLogs, 60L, 60L);
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(ServerMarket.getInstance(), this::saveLogs, 3, 3);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.blank038.servermarket.internal.cache.other;

/**
* @author Blank038
*/
public class NotifyCache {
public int index;
public long time;
public String message;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.blank038.servermarket.internal.command.virtual;

import com.blank038.servermarket.api.ServerMarketApi;
import com.blank038.servermarket.internal.cache.other.NotifyCache;
import com.blank038.servermarket.internal.plugin.ServerMarket;
import com.blank038.servermarket.api.event.PlayerSaleEvent;
import com.blank038.servermarket.api.entity.MarketData;
Expand All @@ -11,6 +12,7 @@
import com.blank038.servermarket.api.handler.filter.impl.KeyFilterImpl;
import com.blank038.servermarket.internal.gui.impl.MarketGui;
import com.blank038.servermarket.internal.i18n.I18n;
import com.blank038.servermarket.internal.service.notify.NotifyCenter;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
Expand Down Expand Up @@ -106,7 +108,7 @@ private void performSellCommand(Player player, String[] args) {
return;
}
// 判断余额是否足够交上架税
double tax = this.marketData.getPermsValueForPlayer(this.marketData.getShoutTaxSection(), player, false);
double tax = price * this.marketData.getPermsValueForPlayer(this.marketData.getShoutTaxSection(), player, false);
if (BaseEconomy.getEconomyBridge(this.marketData.getPaymentType()).balance(player, this.marketData.getEconomyType()) < tax) {
player.sendMessage(I18n.getStrAndHeader("shout-tax")
.replace("%economy%", this.marketData.getEconomyName()));
Expand Down Expand Up @@ -138,11 +140,14 @@ private void performSellCommand(Player player, String[] args) {
if (this.marketData.isSaleBroadcast()) {
String displayName = cloneItem.hasItemMeta() && cloneItem.getItemMeta().hasDisplayName() ?
cloneItem.getItemMeta().getDisplayName() : cloneItem.getType().name();
Bukkit.getServer().broadcastMessage(I18n.getStrAndHeader("broadcast")
NotifyCache notify = new NotifyCache();
notify.message = I18n.getStrAndHeader("broadcast")
.replace("%item%", displayName)
.replace("%market_name%", this.marketData.getDisplayName())
.replace("%amount%", String.valueOf(cloneItem.getAmount()))
.replace("%player%", player.getName()));
.replace("%player%", player.getName());
notify.time = System.currentTimeMillis();
NotifyCenter.pushNotify(notify);
}
} else {
player.getInventory().addItem(cloneItem);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public abstract class AbstractGui {
synchronized (COOLDOWN) {
COOLDOWN.entrySet().removeIf((entry) -> System.currentTimeMillis() > entry.getValue());
}
}, 1200L, 1200L);
}, 60, 60);
}

public boolean isCooldown(UUID uuid) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,14 @@ public ITaskWrapper runTask(JavaPlugin plugin, Runnable runnable) {
}

@Override
public ITaskWrapper runTaskTimerAsynchronously(JavaPlugin plugin, Runnable runnable, long delay, long period) {
BukkitTask bukkitTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, delay, period);
public ITaskWrapper runTaskAsynchronously(JavaPlugin plugin, Runnable runnable) {
BukkitTask bukkitTask = Bukkit.getScheduler().runTaskAsynchronously(plugin, runnable);
return new BukkitTaskWrapper(bukkitTask);
}

@Override
public ITaskWrapper runTaskTimerAsynchronously(JavaPlugin plugin, Runnable runnable, long delaySecond, long periodSecond) {
BukkitTask bukkitTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, delaySecond * 20, periodSecond * 20);
return new BukkitTaskWrapper(bukkitTask);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
import com.blank038.servermarket.internal.metrics.Metrics;
import com.blank038.servermarket.internal.platform.PlatformHandler;
import com.blank038.servermarket.internal.task.OfflineTransactionTask;
import com.google.common.collect.Lists;
import de.tr7zw.nbtapi.utils.MinecraftVersion;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.configuration.ConfigurationSection;

/**
* Global market plugin for Bukkit.
Expand Down Expand Up @@ -54,8 +56,8 @@ public void onEnable() {
// register sort handler
AbstractSortHandler.registerDefaults();
// start tasks
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(this, storageHandler::removeTimeOutItem, 200L, 200L);
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(this, storageHandler::saveAll, 1200L, 1200L);
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(this, storageHandler::removeTimeOutItem, 60, 60);
ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(this, storageHandler::saveAll, 60, 60);
// inject metrics
new Metrics(this, 20031);
}
Expand All @@ -78,25 +80,28 @@ public void loadConfig(boolean start) {
this.reloadConfig();
// Initialize I18n
new I18n(this.getConfig().getString("language", "zh_CN"));
// restart the task for offline transaction
OfflineTransactionTask.restart();
// Run legacy converter
LegacyBackup.check();
if (this.isEnabled()) {
// Save the default files
Lists.newArrayList("gui/store.yml").forEach((v) -> this.saveResource(v, v));
if (start && this.isEnabled()) {
// Initialize IStorageHandler
AbstractStorageHandler.check();
storageHandler.reload();
// Initialize economy
BaseEconomy.initEconomies();
// Initialize DataContainer
DataContainer.loadData();
// Save the default files
for (String fileName : new String[]{"gui/store.yml"}) {
this.saveResource(fileName, fileName);
}
this.getConsoleLogger().log(false, I18n.getProperties().getProperty("load-completed")
.replace("%s", String.valueOf(DataContainer.MARKET_DATA.size())));
this.getConsoleLogger().log(false, " ");
// register service
ConfigurationSection section = this.getConfig().getConfigurationSection("notify-option");
String serviceType = section.getString("use", "self");
ServerMarketApi.createService(serviceType, section.getConfigurationSection("type." + serviceType));
}
// restart the task for offline transaction
OfflineTransactionTask.restart();

this.getConsoleLogger().log(false, I18n.getProperties().getProperty("load-completed")
.replace("%s", String.valueOf(DataContainer.MARKET_DATA.size())));
this.getConsoleLogger().log(false, " ");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.blank038.servermarket.internal.service.notify;

import com.blank038.servermarket.internal.cache.other.NotifyCache;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;

/**
* @author Blank038
*/
public interface INotifyService {

void register(ConfigurationSection config);

void push(NotifyCache notifyCache);

default void broadcast(String message) {
Bukkit.getOnlinePlayers().forEach((player) -> player.sendMessage(message));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.blank038.servermarket.internal.service.notify;

import com.blank038.servermarket.internal.cache.other.NotifyCache;
import com.blank038.servermarket.internal.service.notify.impl.mysql.MySQLNotifyServiceImpl;
import com.blank038.servermarket.internal.service.notify.impl.self.SelfNotifyServiceImpl;
import org.bukkit.configuration.ConfigurationSection;

import java.util.HashMap;
import java.util.Map;

/**
* @author Blank038
*/
public class NotifyCenter {
private static final Map<String, INotifyService> NOTIFY_SERVICES = new HashMap<>();
private static final Map<String, Class<? extends INotifyService>> NOTIFY_CLASSES = new HashMap<>();

static {
NotifyCenter.register("self", SelfNotifyServiceImpl.class);
NotifyCenter.register("mysql", MySQLNotifyServiceImpl.class);
}

public static boolean isRegister(String source) {
return NOTIFY_CLASSES.containsKey(source);
}

public static boolean isCreated(String source) {
return NOTIFY_SERVICES.containsKey(source);
}

public static void register(String source, Class<? extends INotifyService> classZ) {
NOTIFY_CLASSES.putIfAbsent(source, classZ);
}

public static INotifyService create(String source, INotifyService service, ConfigurationSection config) {
if (NOTIFY_SERVICES.containsKey(source)) {
return null;
}
service.register(config);
NOTIFY_SERVICES.put(source, service);
return service;
}

public static Class<? extends INotifyService> findNotifyClass(String source) {
return NOTIFY_CLASSES.getOrDefault(source, null);
}

public static INotifyService getService(String service) {
return NOTIFY_SERVICES.getOrDefault(service, null);
}

public static Map<String, INotifyService> getServices() {
return NOTIFY_SERVICES;
}

public static void pushNotify(NotifyCache cache) {
NotifyCenter.getServices().forEach((k, v) -> v.push(cache));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.blank038.servermarket.internal.service.notify.impl;

import com.blank038.servermarket.internal.service.notify.INotifyService;

/**
* @author Blank038
*/
public abstract class AbstractNotifyService implements INotifyService {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.blank038.servermarket.internal.service.notify.impl;

import com.blank038.servermarket.api.ServerMarketApi;
import com.blank038.servermarket.api.platform.wrapper.ITaskWrapper;
import com.blank038.servermarket.internal.plugin.ServerMarket;

import java.util.ArrayList;
import java.util.List;

/**
* @author Blank038
*/
public abstract class IncreaseNotifyService extends AbstractNotifyService {
private final List<Integer> pushedIndexes = new ArrayList<>();
private ITaskWrapper wrapper;

public boolean hasIndex(int index) {
return this.pushedIndexes.contains(index);
}

public void addIndex(int index) {
this.pushedIndexes.add(index);
}

public void update() {
}

public void runTask(int seconds) {
if (wrapper != null) {
wrapper.cancel();
}
wrapper = ServerMarketApi.getPlatformApi().runTaskTimerAsynchronously(
ServerMarket.getInstance(),
() -> this.update(),
seconds,
seconds
);
}
}
Loading

0 comments on commit b6d21e4

Please sign in to comment.