NeoForge rewrite based on Simple Backups by MelanX
This commit is contained in:
parent
4ee7e3c070
commit
9796c6c583
29 changed files with 1170 additions and 559 deletions
|
@ -1,142 +0,0 @@
|
|||
package com.github.jinks.extbackup;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
|
||||
public enum BackupHandler {
|
||||
INSTANCE;
|
||||
|
||||
public long nextBackup = -1L;
|
||||
public int doingBackup = 0;
|
||||
public boolean hadPlayersOnline = false;
|
||||
private boolean youHaveBeenWarned = false;
|
||||
public void init() {
|
||||
doingBackup = 0;
|
||||
nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
|
||||
File script = ConfigHandler.COMMON.getScript();
|
||||
|
||||
if (!script.exists()) {
|
||||
script.getParentFile().mkdirs();
|
||||
try {
|
||||
Files.write(script.toPath(), "#!/bin/bash\n# Put your backup script here!\n\nexit 0".getBytes(StandardCharsets.UTF_8));
|
||||
script.setExecutable(true);
|
||||
ExtBackup.logger.info("No backup script was found, a script has been created at " + script.getAbsolutePath() + ", please modify it to your liking.");
|
||||
} catch (IOException e) {
|
||||
ExtBackup.logger.error("Backup script does not exist and cannot be created!");
|
||||
ExtBackup.logger.error("Disabling ExtBackup!");
|
||||
ConfigHandler.COMMON.enabled.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
ExtBackup.logger.info("Active script: " + script.getAbsolutePath());
|
||||
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
|
||||
}
|
||||
|
||||
public boolean run(MinecraftServer server) {
|
||||
if (doingBackup != 0 || !ConfigHandler.COMMON.enabled.get()) {
|
||||
return false;
|
||||
}
|
||||
if (doingBackup != 0) {
|
||||
ExtBackup.logger.warn("Tried to start backup while one is already running!");
|
||||
return false;
|
||||
}
|
||||
|
||||
File script = ConfigHandler.COMMON.getScript();
|
||||
if (!script.exists() || !script.canExecute()) {
|
||||
ExtBackup.logger.error("Cannot access or execute backup script. Bailing out!");
|
||||
return false;
|
||||
}
|
||||
|
||||
doingBackup = 1;
|
||||
|
||||
try {
|
||||
if (server.getPlayerList() != null) {
|
||||
server.getPlayerList().saveAll();
|
||||
}
|
||||
|
||||
for (ServerLevel level : server.getAllLevels()) {
|
||||
if (level != null) {
|
||||
//world.save(null, true, false);
|
||||
level.noSave = true;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
ExtBackup.logger.error("Saving the world failed!");
|
||||
enableSaving(server);
|
||||
ex.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
|
||||
new Thread(() -> {
|
||||
try {
|
||||
doBackup(server, script);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
doingBackup = 2;
|
||||
}).start();
|
||||
|
||||
nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
|
||||
return true;
|
||||
}
|
||||
|
||||
private int doBackup(MinecraftServer server, File script) {
|
||||
if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Starting backup.");}
|
||||
ExtBackupUtil.broadcast(server, "Starting Backup!");
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
|
||||
int returnValue = -1;
|
||||
//Map<String, String> env = pb.environment();
|
||||
pb.redirectErrorStream(true);
|
||||
try {
|
||||
Process backup = pb.start();
|
||||
returnValue = backup.waitFor();
|
||||
} catch (Exception ex) {
|
||||
enableSaving(server);
|
||||
ExtBackup.logger.error("Something went wrong with the Backup script!");
|
||||
ExtBackup.logger.error("Check your Backups.");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
enableSaving(server);
|
||||
youHaveBeenWarned = false;
|
||||
if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Backup done.");}
|
||||
ExtBackupUtil.broadcast(server, "Backup done!");
|
||||
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
private void enableSaving(MinecraftServer server) {
|
||||
for (ServerLevel level : server.getAllLevels()) {
|
||||
if (level != null) {
|
||||
level.noSave = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void tick(MinecraftServer server, long now) {
|
||||
if (nextBackup > 0L && nextBackup <= now) {
|
||||
//ExtBackup.logger.info("Backup time!");
|
||||
if (!ConfigHandler.COMMON.only_if_players_online.get() || hadPlayersOnline || !server.getPlayerList().getPlayers().isEmpty()) {
|
||||
hadPlayersOnline = false;
|
||||
run(server);
|
||||
}
|
||||
}
|
||||
if (doingBackup > 1) {
|
||||
doingBackup = 0;
|
||||
} else if (doingBackup > 0) {
|
||||
if (now - nextBackup > 1200000 && !youHaveBeenWarned) {
|
||||
ExtBackup.logger.warn("There has been a running backup for more than 20 minutes.");
|
||||
ExtBackup.logger.warn("Something seems to be wrong.");
|
||||
youHaveBeenWarned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
package com.github.jinks.extbackup;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import net.minecraftforge.common.ForgeConfigSpec;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
|
||||
public final class ConfigHandler {
|
||||
|
||||
public static class Common {
|
||||
public final ForgeConfigSpec.BooleanValue enabled;
|
||||
private final ForgeConfigSpec.IntValue backup_timer;
|
||||
public final ForgeConfigSpec.BooleanValue silent;
|
||||
public final ForgeConfigSpec.BooleanValue only_if_players_online;
|
||||
public final ForgeConfigSpec.BooleanValue force_on_shutdown;
|
||||
public final ForgeConfigSpec.ConfigValue<String> script;
|
||||
|
||||
public Common(ForgeConfigSpec.Builder builder) {
|
||||
enabled = builder
|
||||
.comment("backups are enabled")
|
||||
.define("enabled", true);
|
||||
|
||||
backup_timer = builder
|
||||
.comment("interval in minutes to run the backup script")
|
||||
.defineInRange("backup_timer", 10, 1 , 3600);
|
||||
|
||||
silent = builder
|
||||
.comment("be silent, do not post backups in chat")
|
||||
.define("silent", false);
|
||||
|
||||
only_if_players_online = builder
|
||||
.comment("run only if players are online")
|
||||
.define("only_if_players_online", true);
|
||||
|
||||
force_on_shutdown = builder
|
||||
.comment("run backup on server shutdown")
|
||||
.define("force_on_shutdown", true);
|
||||
|
||||
script = builder
|
||||
.comment("script location - this script is run on each interval")
|
||||
.define("script", "local/extbackup/runbackup.sh");
|
||||
}
|
||||
|
||||
public long time() {
|
||||
return (long) (ConfigHandler.COMMON.backup_timer.get() * 60000L);
|
||||
}
|
||||
|
||||
private static File cachedScript;
|
||||
public File getScript() {
|
||||
String scr = ConfigHandler.COMMON.script.get();
|
||||
if (scr == null) {
|
||||
ExtBackup.logger.warn("Script is NULL!");
|
||||
return null;
|
||||
}
|
||||
if (cachedScript == null) {
|
||||
cachedScript = scr.trim().isEmpty() ? new File(FMLPaths.GAMEDIR.get() + "local/extbackup/runbackup.sh") : new File(scr.trim());
|
||||
}
|
||||
return cachedScript;
|
||||
}
|
||||
}
|
||||
|
||||
public static final Common COMMON;
|
||||
public static final ForgeConfigSpec COMMON_SPEC;
|
||||
static {
|
||||
final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new);
|
||||
COMMON_SPEC = specPair.getRight();
|
||||
COMMON = specPair.getLeft();
|
||||
}
|
||||
|
||||
public static void onConfigLoad() {
|
||||
//BackupHandler.INSTANCE.nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
|
||||
//ExtBackup.logger.info("Config Changed, next backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(BackupHandler.INSTANCE.nextBackup)));
|
||||
}
|
||||
}
|
|
@ -1,78 +0,0 @@
|
|||
package com.github.jinks.extbackup;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||
import net.minecraftforge.fml.ModLoadingContext;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.event.server.ServerStartedEvent;
|
||||
import net.minecraftforge.event.server.ServerStoppingEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
@Mod(ExtBackup.MOD_ID)
|
||||
@Mod.EventBusSubscriber(modid = ExtBackup.MOD_ID)
|
||||
public class ExtBackup {
|
||||
|
||||
public static final String MOD_ID = "extbackup";
|
||||
|
||||
public static final Logger logger = LogManager.getLogger("ExtBackup");
|
||||
|
||||
public ExtBackup() {
|
||||
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ConfigHandler.COMMON_SPEC);
|
||||
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
|
||||
modBus.addListener(this::setup);
|
||||
//modBus.addListener((ModConfig.Loading e) -> ConfigHandler.onConfigLoad());
|
||||
//modBus.addListener((ModConfig.Reloading e) -> ConfigHandler.onConfigLoad());
|
||||
|
||||
// Register ourselves for server and other game events we are interested in
|
||||
IEventBus forgeBus = MinecraftForge.EVENT_BUS;
|
||||
forgeBus.register(this);
|
||||
forgeBus.addListener(this::serverAboutToStart);
|
||||
forgeBus.addListener(this::serverStopping);
|
||||
}
|
||||
|
||||
private void setup(final FMLCommonSetupEvent event) {
|
||||
ConfigHandler.onConfigLoad();
|
||||
}
|
||||
|
||||
public void serverAboutToStart(ServerStartedEvent event) {
|
||||
BackupHandler.INSTANCE.init();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void serverStopping(ServerStoppingEvent event) {
|
||||
if (ConfigHandler.COMMON.force_on_shutdown.get()) {
|
||||
MinecraftServer server = event.getServer();
|
||||
|
||||
if (server != null) {
|
||||
BackupHandler.INSTANCE.run(server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void serverTick(TickEvent.ServerTickEvent event) {
|
||||
if (event.phase != TickEvent.Phase.START) {
|
||||
//MinecraftServer server = LogicalSidedProvider.INSTANCE.get(LogicalSide.SERVER);
|
||||
MinecraftServer server = event.getServer();
|
||||
|
||||
if (server != null) {
|
||||
//logger.debug("Server Tick! " + event.phase);
|
||||
BackupHandler.INSTANCE.tick(server, System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {
|
||||
BackupHandler.INSTANCE.hadPlayersOnline = true;
|
||||
}
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
package com.github.jinks.extbackup;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.ChatType;
|
||||
|
||||
public class ExtBackupUtil {
|
||||
|
||||
public static void broadcast(MinecraftServer server, String message) {
|
||||
if (!ConfigHandler.COMMON.silent.get()) {
|
||||
//Component bcMessage = new TextComponent("[§1ExtBackup§r] " + message);
|
||||
Component bcMessage = Component.literal("[§1ExtBackup§r] " + message);
|
||||
//server.getPlayerList().broadcastMessage(bcMessage, ChatType.SYSTEM, Util.NIL_UUID);
|
||||
server.getPlayerList().broadcastSystemMessage(bcMessage, true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
63
src/main/java/de/melanx/simplebackups/BackupData.java
Normal file
63
src/main/java/de/melanx/simplebackups/BackupData.java
Normal file
|
@ -0,0 +1,63 @@
|
|||
package de.melanx.simplebackups;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public class BackupData extends SavedData {
|
||||
|
||||
private long lastSaved;
|
||||
private boolean paused;
|
||||
|
||||
private BackupData() {
|
||||
// use BackupData.get
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public CompoundTag save(@Nonnull CompoundTag nbt, @Nonnull HolderLookup.Provider provider) {
|
||||
nbt.putLong("lastSaved", this.lastSaved);
|
||||
nbt.putBoolean("paused", this.paused);
|
||||
return nbt;
|
||||
}
|
||||
|
||||
public static BackupData get(ServerLevel level) {
|
||||
return BackupData.get(level.getServer());
|
||||
}
|
||||
|
||||
public static BackupData get(MinecraftServer server) {
|
||||
return server.overworld().getDataStorage().computeIfAbsent(BackupData.factory(), "simplebackups");
|
||||
}
|
||||
|
||||
public BackupData load(@Nonnull CompoundTag nbt, @Nonnull HolderLookup.Provider provider) {
|
||||
this.lastSaved = nbt.getLong("lastSaved");
|
||||
this.paused = nbt.getBoolean("paused");
|
||||
return this;
|
||||
}
|
||||
|
||||
public void setPaused(boolean paused) {
|
||||
this.paused = paused;
|
||||
this.setDirty();
|
||||
}
|
||||
|
||||
public boolean isPaused() {
|
||||
return this.paused;
|
||||
}
|
||||
|
||||
public long getLastSaved() {
|
||||
return this.lastSaved;
|
||||
}
|
||||
|
||||
public void updateSaveTime(long time) {
|
||||
this.lastSaved = time;
|
||||
this.setDirty();
|
||||
}
|
||||
|
||||
private static SavedData.Factory<BackupData> factory() {
|
||||
return new SavedData.Factory<>(BackupData::new, (nbt, provider) -> new BackupData().load(nbt, provider));
|
||||
}
|
||||
}
|
137
src/main/java/de/melanx/simplebackups/BackupThread.java
Normal file
137
src/main/java/de/melanx/simplebackups/BackupThread.java
Normal file
|
@ -0,0 +1,137 @@
|
|||
package de.melanx.simplebackups;
|
||||
|
||||
import de.melanx.simplebackups.config.CommonConfig;
|
||||
import de.melanx.simplebackups.config.ServerConfig;
|
||||
import de.melanx.simplebackups.network.Pause;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.DefaultUncaughtExceptionHandler;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
//import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.neoforged.fml.i18n.I18nManager;
|
||||
import net.neoforged.neoforge.network.registration.NetworkRegistry;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.SignStyle;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.util.*;
|
||||
|
||||
public class BackupThread extends Thread {
|
||||
|
||||
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
|
||||
.appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).appendLiteral('-')
|
||||
.appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
|
||||
.appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('_')
|
||||
.appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral('-')
|
||||
.appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral('-')
|
||||
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
|
||||
.toFormatter();
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(BackupThread.class);
|
||||
private final MinecraftServer server;
|
||||
private final boolean quiet;
|
||||
private BackupThread(@Nonnull MinecraftServer server, boolean quiet, BackupData backupData) {
|
||||
this.server = server;
|
||||
this.quiet = quiet;
|
||||
this.setName("SimpleBackups");
|
||||
this.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
|
||||
}
|
||||
|
||||
public static boolean tryCreateBackup(MinecraftServer server) {
|
||||
BackupData backupData = BackupData.get(server);
|
||||
if (BackupThread.shouldRunBackup(server)) {
|
||||
BackupThread thread = new BackupThread(server, false, backupData);
|
||||
thread.start();
|
||||
long currentTime = System.currentTimeMillis();
|
||||
backupData.updateSaveTime(currentTime);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean shouldRunBackup(MinecraftServer server) {
|
||||
BackupData backupData = BackupData.get(server);
|
||||
if (!CommonConfig.isEnabled() || backupData.isPaused()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return System.currentTimeMillis() - CommonConfig.getTimer() > backupData.getLastSaved();
|
||||
}
|
||||
|
||||
public static void createBackup(MinecraftServer server, boolean quiet) {
|
||||
BackupThread thread = new BackupThread(server, quiet, null);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
long start = System.currentTimeMillis();
|
||||
this.broadcast("simplebackups.backup_started", Style.EMPTY.withColor(ChatFormatting.GOLD));
|
||||
long end = System.currentTimeMillis();
|
||||
String time = Timer.getTimer(end - start);
|
||||
this.broadcast("simplebackups.backup_finished", Style.EMPTY.withColor(ChatFormatting.GOLD), time);
|
||||
} catch (Exception e) {
|
||||
SimpleBackups.LOGGER.error("Error backing up", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void broadcast(String message, Style style, Object... parameters) {
|
||||
if (CommonConfig.sendMessages() && !this.quiet) {
|
||||
this.server.execute(() -> {
|
||||
this.server.getPlayerList().getPlayers().forEach(player -> {
|
||||
if (ServerConfig.messagesForEveryone() || player.hasPermissions(2)) {
|
||||
player.sendSystemMessage(BackupThread.component(player, message, parameters).withStyle(style));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("null")
|
||||
public static MutableComponent component(@Nullable ServerPlayer player, String key, Object... parameters) {
|
||||
if (player != null) {
|
||||
//noinspection UnstableApiUsage
|
||||
if (NetworkRegistry.hasChannel(player.connection.connection, null, Pause.ID)) {
|
||||
return Component.translatable(key, parameters);
|
||||
}
|
||||
}
|
||||
|
||||
return Component.literal(String.format(Optional.ofNullable(I18nManager.loadTranslations("en_us").get(key)).orElse(key), parameters));
|
||||
}
|
||||
|
||||
// vanilla copy with modifications
|
||||
private long makeWorldBackup() throws IOException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static class Timer {
|
||||
|
||||
private static final SimpleDateFormat SECONDS = new SimpleDateFormat("s.SSS");
|
||||
private static final SimpleDateFormat MINUTES = new SimpleDateFormat("mm:ss");
|
||||
private static final SimpleDateFormat HOURS = new SimpleDateFormat("HH:mm");
|
||||
|
||||
public static String getTimer(long milliseconds) {
|
||||
Date date = new Date(milliseconds);
|
||||
double seconds = milliseconds / 1000d;
|
||||
if (seconds < 60) {
|
||||
return SECONDS.format(date) + "s";
|
||||
} else if (seconds < 3600) {
|
||||
return MINUTES.format(date) + "min";
|
||||
} else {
|
||||
return HOURS.format(date) + "h";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
67
src/main/java/de/melanx/simplebackups/EventListener.java
Normal file
67
src/main/java/de/melanx/simplebackups/EventListener.java
Normal file
|
@ -0,0 +1,67 @@
|
|||
package de.melanx.simplebackups;
|
||||
|
||||
import de.melanx.simplebackups.commands.BackupCommand;
|
||||
import de.melanx.simplebackups.commands.PauseCommand;
|
||||
import de.melanx.simplebackups.config.CommonConfig;
|
||||
import de.melanx.simplebackups.config.ServerConfig;
|
||||
import de.melanx.simplebackups.network.Pause;
|
||||
import net.minecraft.commands.Commands;
|
||||
//import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
||||
import net.neoforged.neoforge.event.tick.LevelTickEvent;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.neoforged.neoforge.network.registration.NetworkRegistry;
|
||||
|
||||
public class EventListener {
|
||||
|
||||
private boolean doBackup;
|
||||
|
||||
@SubscribeEvent
|
||||
public void registerCommands(RegisterCommandsEvent event) {
|
||||
event.getDispatcher().register(Commands.literal(SimpleBackups.MODID)
|
||||
.requires(stack -> ServerConfig.commandsCheatsDisabled() || stack.hasPermission(2))
|
||||
.then(BackupCommand.register())
|
||||
.then(PauseCommand.register()));
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onServerTick(LevelTickEvent.Post event) {
|
||||
if (event.getLevel() instanceof ServerLevel level && !level.isClientSide
|
||||
&& level.getGameTime() % 20 == 0 && level == level.getServer().overworld()) {
|
||||
|
||||
if (!level.getServer().getPlayerList().getPlayers().isEmpty() || this.doBackup || CommonConfig.doNoPlayerBackups()) {
|
||||
this.doBackup = false;
|
||||
|
||||
boolean done = BackupThread.tryCreateBackup(level.getServer());
|
||||
if (done) {
|
||||
SimpleBackups.LOGGER.info("Backup done.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("null")
|
||||
@SubscribeEvent
|
||||
public void onPlayerConnect(PlayerEvent.PlayerLoggedInEvent event) {
|
||||
ServerPlayer player = (ServerPlayer) event.getEntity();
|
||||
//noinspection UnstableApiUsage
|
||||
if (CommonConfig.isEnabled() && event.getEntity().getServer() != null && NetworkRegistry.hasChannel(player.connection.connection, null, Pause.ID)) {
|
||||
PacketDistributor.sendToPlayer(player, new Pause(BackupData.get(event.getEntity().getServer()).isPaused()));
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("null")
|
||||
@SubscribeEvent
|
||||
public void onPlayerDisconnect(PlayerEvent.PlayerLoggedOutEvent event) {
|
||||
if (event.getEntity() instanceof ServerPlayer player) {
|
||||
//noinspection ConstantConditions
|
||||
if (player.getServer().getPlayerList().getPlayers().isEmpty()) {
|
||||
this.doBackup = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
48
src/main/java/de/melanx/simplebackups/SimpleBackups.java
Normal file
48
src/main/java/de/melanx/simplebackups/SimpleBackups.java
Normal file
|
@ -0,0 +1,48 @@
|
|||
package de.melanx.simplebackups;
|
||||
|
||||
import de.melanx.simplebackups.client.ClientEventHandler;
|
||||
import de.melanx.simplebackups.config.CommonConfig;
|
||||
import de.melanx.simplebackups.config.ServerConfig;
|
||||
import de.melanx.simplebackups.network.Pause;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.ModContainer;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.config.ModConfig;
|
||||
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
||||
import net.neoforged.neoforge.network.registration.PayloadRegistrar;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Mod(SimpleBackups.MODID)
|
||||
public class SimpleBackups {
|
||||
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(SimpleBackups.class);
|
||||
public static final String MODID = "simplebackups";
|
||||
|
||||
public SimpleBackups(IEventBus modEventBus, ModContainer modContainer, Dist dist) {
|
||||
modContainer.registerConfig(ModConfig.Type.COMMON, CommonConfig.CONFIG);
|
||||
modContainer.registerConfig(ModConfig.Type.SERVER, ServerConfig.CONFIG);
|
||||
NeoForge.EVENT_BUS.register(new EventListener());
|
||||
modEventBus.addListener(this::setup);
|
||||
modEventBus.addListener(this::onRegisterPayloadHandler);
|
||||
|
||||
if (dist.isClient()) {
|
||||
NeoForge.EVENT_BUS.register(new ClientEventHandler());
|
||||
}
|
||||
}
|
||||
|
||||
private void onRegisterPayloadHandler(RegisterPayloadHandlersEvent event) {
|
||||
PayloadRegistrar registrar = event.registrar(SimpleBackups.MODID)
|
||||
.versioned("1.0")
|
||||
.optional();
|
||||
|
||||
registrar.playToClient(Pause.TYPE, Pause.CODEC, Pause::handle);
|
||||
}
|
||||
|
||||
private void setup(FMLCommonSetupEvent event) {
|
||||
// NO-OP
|
||||
}
|
||||
}
|
48
src/main/java/de/melanx/simplebackups/StorageSize.java
Normal file
48
src/main/java/de/melanx/simplebackups/StorageSize.java
Normal file
|
@ -0,0 +1,48 @@
|
|||
package de.melanx.simplebackups;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum StorageSize {
|
||||
B(0),
|
||||
KB(1),
|
||||
MB(2),
|
||||
GB(3),
|
||||
TB(4);
|
||||
|
||||
private final long sizeInBytes;
|
||||
private final String postfix;
|
||||
|
||||
StorageSize(int factor) {
|
||||
this.sizeInBytes = (long) Math.pow(1024, factor);
|
||||
this.postfix = this.name().toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public static StorageSize getSizeFor(double bytes) {
|
||||
for (StorageSize value : StorageSize.values()) {
|
||||
if (bytes < value.sizeInBytes) {
|
||||
return value.getLower();
|
||||
} else if (value == TB) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return B;
|
||||
}
|
||||
|
||||
public static long getBytes(String s) {
|
||||
String[] splits = s.split(" ");
|
||||
int amount = Integer.parseInt(splits[0]);
|
||||
StorageSize size = StorageSize.valueOf(splits[1].toUpperCase(Locale.ROOT));
|
||||
return amount * size.sizeInBytes;
|
||||
}
|
||||
|
||||
public static String getFormattedSize(double bytes) {
|
||||
StorageSize size = StorageSize.getSizeFor(bytes);
|
||||
double small = bytes / size.sizeInBytes;
|
||||
return String.format("%.1f %s", small, size.postfix);
|
||||
}
|
||||
|
||||
public StorageSize getLower() {
|
||||
return this.ordinal() == 0 ? this : StorageSize.values()[this.ordinal() - 1];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package de.melanx.simplebackups.client;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.client.event.CustomizeGuiOverlayEvent;
|
||||
|
||||
public class ClientEventHandler {
|
||||
|
||||
private static final MutableComponent COMPONENT = Component.translatable("simplebackups.backups_paused").withStyle(ChatFormatting.RED);
|
||||
private static boolean isPaused = false;
|
||||
|
||||
public static void setPaused(boolean paused) {
|
||||
isPaused = paused;
|
||||
}
|
||||
|
||||
public static boolean isPaused() {
|
||||
return isPaused;
|
||||
}
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
@SubscribeEvent
|
||||
public void onRenderText(CustomizeGuiOverlayEvent.DebugText event) {
|
||||
if (!isPaused) {
|
||||
return;
|
||||
}
|
||||
|
||||
GuiGraphics guiGraphics = event.getGuiGraphics();
|
||||
guiGraphics.fill(3, 3, 20, 20, 0);
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.defaultBlendFunc();
|
||||
guiGraphics.drawString(Minecraft.getInstance().font, COMPONENT, 3, 3, 0);
|
||||
RenderSystem.disableBlend();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package de.melanx.simplebackups.commands;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import com.mojang.brigadier.arguments.BoolArgumentType;
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import de.melanx.simplebackups.BackupThread;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
public class BackupCommand implements Command<CommandSourceStack> {
|
||||
|
||||
public static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("backup")
|
||||
.then(Commands.literal("start")
|
||||
.executes(new BackupCommand())
|
||||
.then(Commands.argument("quiet", BoolArgumentType.bool())
|
||||
.executes(new BackupCommand())
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int run(CommandContext<CommandSourceStack> context) {
|
||||
boolean quiet = false;
|
||||
try {
|
||||
quiet = BoolArgumentType.getBool(context, "quiet");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
MinecraftServer server = context.getSource().getServer();
|
||||
BackupThread.createBackup(server, quiet);
|
||||
return 1;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package de.melanx.simplebackups.commands;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import com.mojang.brigadier.builder.ArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import de.melanx.simplebackups.BackupData;
|
||||
import de.melanx.simplebackups.network.Pause;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
|
||||
public class PauseCommand implements Command<CommandSourceStack> {
|
||||
|
||||
private final boolean paused;
|
||||
|
||||
private PauseCommand(boolean paused) {
|
||||
this.paused = paused;
|
||||
}
|
||||
|
||||
public static ArgumentBuilder<CommandSourceStack, ?> register() {
|
||||
return Commands.literal("backup")
|
||||
.then(Commands.literal("pause")
|
||||
.executes(new PauseCommand(true)))
|
||||
.then(Commands.literal("unpause")
|
||||
.executes(new PauseCommand(false)));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int run(CommandContext<CommandSourceStack> context) {
|
||||
BackupData data = BackupData.get(context.getSource().getServer());
|
||||
data.setPaused(this.paused);
|
||||
PacketDistributor.sendToAllPlayers(new Pause(this.paused));
|
||||
return this.paused ? 1 : 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package de.melanx.simplebackups.config;
|
||||
|
||||
import net.neoforged.neoforge.common.ModConfigSpec;
|
||||
|
||||
|
||||
public class CommonConfig {
|
||||
|
||||
public static final ModConfigSpec CONFIG;
|
||||
private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder();
|
||||
|
||||
static {
|
||||
init(BUILDER);
|
||||
CONFIG = BUILDER.build();
|
||||
}
|
||||
|
||||
private static ModConfigSpec.BooleanValue enabled;
|
||||
private static ModConfigSpec.IntValue timer;
|
||||
private static ModConfigSpec.BooleanValue sendMessages;
|
||||
private static ModConfigSpec.BooleanValue noPlayerBackups;
|
||||
|
||||
public static void init(ModConfigSpec.Builder builder) {
|
||||
enabled = builder.comment("If set false, no backups are being made.")
|
||||
.define("enabled", true);
|
||||
timer = builder.comment("The time between two backups in minutes", "5 = each 5 minutes", "60 = each hour", "1440 = each day")
|
||||
.defineInRange("timer", 120, 1, Short.MAX_VALUE);
|
||||
sendMessages = builder.comment("Should message be sent when backup is in the making?")
|
||||
.define("sendMessages", true);
|
||||
noPlayerBackups = builder.comment("Create backups, even if nobody is online")
|
||||
.define("noPlayerBackups", false);
|
||||
|
||||
builder.push("mod_compat");
|
||||
builder.pop();
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return enabled.get();
|
||||
}
|
||||
|
||||
// converts config value from milliseconds to minutes
|
||||
public static int getTimer() {
|
||||
return timer.get() * 60 * 1000;
|
||||
}
|
||||
|
||||
public static boolean doNoPlayerBackups() {
|
||||
return noPlayerBackups.get();
|
||||
}
|
||||
|
||||
public static boolean sendMessages() {
|
||||
return sendMessages.get();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package de.melanx.simplebackups.config;
|
||||
|
||||
import net.neoforged.neoforge.common.ModConfigSpec;
|
||||
|
||||
public class ServerConfig {
|
||||
|
||||
public static final ModConfigSpec CONFIG;
|
||||
private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder();
|
||||
|
||||
static {
|
||||
init(BUILDER);
|
||||
CONFIG = BUILDER.build();
|
||||
}
|
||||
|
||||
private static ModConfigSpec.BooleanValue commandsCheatsDisabled;
|
||||
private static ModConfigSpec.BooleanValue messagesForEveryone;
|
||||
|
||||
public static void init(ModConfigSpec.Builder builder) {
|
||||
commandsCheatsDisabled = builder.comment("Should commands work without cheats enabled? Mainly recommended for single player, otherwise all users on servers can trigger commands.")
|
||||
.define("commandsCheatsDisabled", false);
|
||||
messagesForEveryone = builder.comment("Should all users receive the backup message? Disable to only have users with permission level 2 and higher receive them.")
|
||||
.define("messagesForEveryone", true);
|
||||
}
|
||||
|
||||
public static boolean commandsCheatsDisabled() {
|
||||
return commandsCheatsDisabled.get();
|
||||
}
|
||||
|
||||
public static boolean messagesForEveryone() {
|
||||
return messagesForEveryone.get();
|
||||
}
|
||||
}
|
32
src/main/java/de/melanx/simplebackups/network/Pause.java
Normal file
32
src/main/java/de/melanx/simplebackups/network/Pause.java
Normal file
|
@ -0,0 +1,32 @@
|
|||
package de.melanx.simplebackups.network;
|
||||
|
||||
import de.melanx.simplebackups.SimpleBackups;
|
||||
import de.melanx.simplebackups.client.ClientEventHandler;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.network.handling.IPayloadContext;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public record Pause(boolean pause) implements CustomPacketPayload {
|
||||
|
||||
public static final ResourceLocation ID = ResourceLocation.fromNamespaceAndPath(SimpleBackups.MODID, "pause");
|
||||
public static final CustomPacketPayload.Type<Pause> TYPE = new Type<>(ID);
|
||||
|
||||
public static final StreamCodec<FriendlyByteBuf, Pause> CODEC = StreamCodec.composite(
|
||||
ByteBufCodecs.BOOL, Pause::pause, Pause::new
|
||||
);
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return Pause.TYPE;
|
||||
}
|
||||
|
||||
public void handle(IPayloadContext context) {
|
||||
ClientEventHandler.setPaused(this.pause);
|
||||
}
|
||||
}
|
4
src/main/resources/META-INF/accesstransformer.cfg
Normal file
4
src/main/resources/META-INF/accesstransformer.cfg
Normal file
|
@ -0,0 +1,4 @@
|
|||
public net.minecraft.server.MinecraftServer storageSource
|
||||
public net.minecraft.server.network.ServerCommonPacketListenerImpl connection
|
||||
public net.minecraft.world.level.storage.LevelStorageSource$LevelStorageAccess checkLock()V
|
||||
public net.minecraft.world.level.storage.LevelStorageSource$LevelStorageAccess levelId
|
|
@ -1,34 +0,0 @@
|
|||
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
|
||||
modLoader="javafml"
|
||||
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
|
||||
# Forge for 1.16.3 is version 34
|
||||
loaderVersion="[40,)"
|
||||
# A URL to refer people to when problems occur with this mod
|
||||
issueTrackerURL="https://github.com/jinks/extbackup/issues"
|
||||
license="GPL"
|
||||
|
||||
[[mods]]
|
||||
modId="extbackup"
|
||||
version="${file.jarVersion}"
|
||||
displayName="ExtBackup"
|
||||
displayURL="https://github.com/jinks/extbackup"
|
||||
#logoFile="assets/examplemod/textures/logo.png"
|
||||
credits="LatVianModder, alexbobp, vazkii"
|
||||
authors="jinks"
|
||||
description='''
|
||||
Minimal Minecraft backup mod, relying on external backup tools.
|
||||
'''
|
||||
|
||||
[[dependencies.extbackup]]
|
||||
modId="forge"
|
||||
mandatory=true
|
||||
versionRange="[47,)"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
||||
|
||||
[[dependencies.extbackup]]
|
||||
modId="minecraft"
|
||||
mandatory=true
|
||||
versionRange="[1.20.1]"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
30
src/main/resources/META-INF/neoforge.mods.toml
Normal file
30
src/main/resources/META-INF/neoforge.mods.toml
Normal file
|
@ -0,0 +1,30 @@
|
|||
modLoader="javafml"
|
||||
loaderVersion="${loader_version_range}"
|
||||
license="${license}"
|
||||
issueTrackerURL = "https://github.com/ChaoticTrials/SimpleBackups/issues"
|
||||
|
||||
[[mods]]
|
||||
modId = "${modid}"
|
||||
version = "${mod_version}"
|
||||
displayName = "Simple Backups"
|
||||
updateJSONURL = "https://assets.melanx.de/updates/simple-backups.json"
|
||||
displayURL = "https://modrinth.com/user/MelanX"
|
||||
authors = "MelanX"
|
||||
displayTest = "IGNORE_ALL_VERSION"
|
||||
description = '''
|
||||
A simple mod to create scheduled backups.
|
||||
'''
|
||||
|
||||
[[dependencies.${ modid }]]
|
||||
modId = "neoforge"
|
||||
type = "required"
|
||||
versionRange = "[${neo_version},)"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
||||
|
||||
[[dependencies.${modid}]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[${minecraft_version},)"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
8
src/main/resources/assets/simplebackups/lang/de_de.json
Normal file
8
src/main/resources/assets/simplebackups/lang/de_de.json
Normal file
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"simplebackups.backup_started": "Backup gestartet...",
|
||||
"simplebackups.backup_finished": "Backup fertiggestellt in %s",
|
||||
"simplebackups.backups_paused": "Backups pausiert",
|
||||
"simplebackups.commands.only_modified": "Es werden nicht nur veränderte Dateien gesichert, prüfe deine Konfigurationsdatei",
|
||||
"simplebackups.commands.is_merging": "Ein Zusammenführungsvorgang ist bereits im Gange",
|
||||
"simplebackups.commands.finished": "Zusammenführen der Backups erfolgreich abgeschlossen"
|
||||
}
|
8
src/main/resources/assets/simplebackups/lang/en_us.json
Normal file
8
src/main/resources/assets/simplebackups/lang/en_us.json
Normal file
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"simplebackups.backup_started": "Backup started...",
|
||||
"simplebackups.backup_finished": "Backup completed in %s",
|
||||
"simplebackups.backups_paused": "Backups paused",
|
||||
"simplebackups.commands.only_modified": "Not only modified files are being backed up, please check your configuration file",
|
||||
"simplebackups.commands.is_merging": "A merge operation is already in progress",
|
||||
"simplebackups.commands.finished": "Merging backups completed successfully"
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
{
|
||||
"pack": {
|
||||
"description": "ExtBackup resources",
|
||||
"pack_format": 8,
|
||||
"_comment": "A pack_format of 6 requires json lang files and some texture changes from 1.16.2. Note: we require v6 pack meta for all mods."
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue