qweeeee12311

Я хочу плагин (FDMaintenance) технических работ для моего сервера. Работать он должен по типу Maintenance. Нужно чтобы его можно было поставить на сервер velocity (у меня Velocity 3.3.0-SNAPSHOT). Плагин должен работать так: не пускать обычных игрового, пускать тех кто есть в вайт листе плагина. Выводить кастомное qui (описание сервера ping-message, player-count-message, player-list-hover-message, custom-maintenance-icon, kick-online-players). Должна быть функция таймера (до конца тех работ, включается по желанию) например включаем тех работы (/fdmt on) и просто тех работы, а если (/fdmt ontimer (количество секунд)) то в описание сервера должно быть другое с учетом таймера который переводит из секунд и часы минуты и секунды в формате плэйсхолдера (например: %H_fd% %M_fd% %S_fd%) когда кончается таймер то отображается просто как бы написал (/fdmt on). Сделай чтобы изменять qui можно было в спецальном файле yml и добавлять в вайтлист тоже файлом yml и перезагружать плагин (reload). САМОЕ ГЛАВНОЕ чтобы плагин работал уместно с плагинами Limbo (LimboAPI LimboAuth и тп) а то обычный плагин Maintenance просто не пускает даже админов при включенных тех работах и limbo.

Kodari AI
KodariJun 18 at 3:02 pm 11

I’ll create a Velocity maintenance plugin called FDMaintenance.

FDMaintenance
A Velocity proxy maintenance plugin that blocks non-whitelisted players during technical works. Features configurable server ping display (description, player count, hover text, custom icon), YML-based whitelist management, timer mode with %H_fd% %M_fd% %S_fd% placeholders, automatic timer expiry to normal maintenance, online player kick, and full Limbo plugin compatibility by only hooking LoginEvent and ProxyPingEvent.

Creating all 11 project files:

qweeeee12311

🔴 Критическая ошибка Плагин fdmaintenance 1.0.0 вызывает ошибку при каждом пинге сервера:

text java.lang.NoSuchMethodError: 'com.velocitypowered.api.proxy.server.ServerPing$Builder com.velocitypowered.api.proxy.server.ServerPing$Builder.samplePlayers(java.util.Collection)' Причина: Плагин fdmaintenance использует устаревший метод API, который был изменён или удалён в вашей версии Velocity. Метод samplePlayers(Collection) больше не существует — его заменили на samplePlayers(Collection<ServerPing.PlayerInfo>) или аналогичный.

🛠️ Решения Обновите fdmaintenance до последней версии, совместимой с Velocity 3.3.0. Кстати у меня чтобы вводить qui (когда тех рабыоты выключеры и ничего нет) AdvancedServerList

Kodari AI
KodariJun 18 at 3:07 pm 4

Проблема: в Velocity 3.3.0 ServerPing.SamplePlayer переименован в ServerPing.PlayerInfo и метод samplePlayers ожидает Collection<PlayerInfo>. Исправляю.

Готово. В Velocity 3.3.0 класс называется ServerPing.PlayerInfo вместо ServerPing.SamplePlayer. Метод samplePlayers работает с тем же сигнатурным типом Collection, но имя класса изменилось:

  • ServerPing.SamplePlayer → ServerPing.PlayerInfo

  • Конструктор остался тем же: (String name, UUID id)

qweeeee12311

сделай чтобы у ping-message было две строки

Kodari AI
KodariJun 18 at 3:27 pm 1

Просто обновляю config.yml — код уже поддерживает \n в parseComponent

Готово. Теперь:

  • Обычные техработы — в описании сервера 2 строки: &cServer is currently under maintenance / &7Please come back later.

  • Режим таймера — 2 строки: &eServer maintenance / &6Ends in &e%H_fd%h &6%M_fd%m &6%S_fd%s

Если хочешь другие строки — просто отредактируй ping-message и timer-ping-message в config.yml и сделай /fdmt reload.

qweeeee12311

а как выключить тех работы?

Kodari AI
KodariJun 18 at 3:36 pm 1

/fdmt off — выключает техработы, выводит сообщение и снимает кик всех игроков.

qweeeee12311

сделай чтобы кода вводишь время ontimer то можно было вводить не только секунды, но и по типу: 5h, 30m , 1h30m, 3h50m, 30s, 45s, 5m30s

Kodari AI
KodariJun 18 at 3:52 pm 1

Готово. Теперь ontimer принимает форматы:

  • 5h — 5 часов

  • 30m — 30 минут

  • 45s — 45 секунд

  • 1h30m — 1 час 30 минут

  • 3h50m — 3 часа 50 минут

  • 5m30s — 5 минут 30 секунд

  • 3600 — обычные секунды (как раньше)

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
11 849
src/main/java/com/fd/maintenance/command/MaintenanceCommand.java
package com.fd.maintenance.command;

import com.fd.maintenance.FDMaintenance;
import com.fd.maintenance.config.WhitelistManager;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.command.SimpleCommand;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;

public class MaintenanceCommand implements SimpleCommand {

    private final FDMaintenance plugin;
    private final Component prefix;

    public MaintenanceCommand(FDMaintenance plugin) {
        this.plugin = plugin;
        this.prefix = color("&8[&cFDMT&8] &7");
    }

    @Override
    public void execute(Invocation invocation) {
        CommandSource source = invocation.source();
        String[] args = invocation.arguments();

        if (!source.hasPermission("fdmaintenance.admin")) {
            source.sendMessage(prefix.append(color("&cYou don't have permission.")));
            return;
        }

        if (args.length == 0) {
            sendHelp(source);
            return;
        }

        switch (args[0].toLowerCase()) {
            case "on" -> handleOn(source);
            case "off" -> handleOff(source);
            case "ontimer" -> handleOnTimer(source, args);
            case "reload" -> handleReload(source);
            case "add" -> handleAdd(source, args);
            case "remove" -> handleRemove(source, args);
            case "list" -> handleList(source);
            case "status" -> handleStatus(source);
            case "check" -> handleCheck(source, args);
            default -> sendHelp(source);
        }
    }

    private void sendHelp(CommandSource source) {
        source.sendMessage(prefix.append(color("&6=== FDMaintenance Commands ===")));
        source.sendMessage(color(" &e/fdmt on &7- Enable maintenance mode"));
        source.sendMessage(color(" &e/fdmt off &7- Disable maintenance mode"));
        source.sendMessage(color(" &e/fdmt ontimer <time> &7- Enable timed maintenance (e.g. 1h30m, 30m, 45s, 3600)"));
        source.sendMessage(color(" &e/fdmt reload &7- Reload config and whitelist"));
        source.sendMessage(color(" &e/fdmt add <player> &7- Add player to whitelist"));
        source.sendMessage(color(" &e/fdmt remove <player> &7- Remove player from whitelist"));
        source.sendMessage(color(" &e/fdmt list &7- List whitelisted players"));
        source.sendMessage(color(" &e/fdmt status &7- Show current maintenance status"));
        source.sendMessage(color(" &e/fdmt check <player> &7- Check if player is whitelisted"));
    }

    private void handleOn(CommandSource source) {
        if (plugin.isMaintenanceActive()) {
            source.sendMessage(prefix.append(color("&cMaintenance is already enabled.")));
            return;
        }
        plugin.setMaintenanceActive(true);
        autoWhitelistSource(source);
        kickNonWhitelisted();
        source.sendMessage(prefix.append(color("&aMaintenance mode enabled.")));
        plugin.getLogger().info("Maintenance mode enabled by {}", source);
    }

    private void handleOff(CommandSource source) {
        if (!plugin.isMaintenanceActive()) {
            source.sendMessage(prefix.append(color("&cMaintenance is not enabled.")));
            return;
        }
        plugin.setMaintenanceActive(false);
        source.sendMessage(prefix.append(color("&aMaintenance mode disabled.")));
        plugin.getLogger().info("Maintenance mode disabled by {}", source);
    }

    private void handleOnTimer(CommandSource source, String[] args) {
        if (args.length < 2) {
            source.sendMessage(prefix.append(color("&cUsage: /fdmt ontimer <time>")));
            source.sendMessage(color(" &7Examples: &e5h, 30m, 1h30m, 3h50m, 45s, 5m30s, 3600"));
            return;
        }
        int seconds = parseTimeToSeconds(args[1]);
        if (seconds <= 0) {
            source.sendMessage(prefix.append(color("&cInvalid time format: " + args[1])));
            source.sendMessage(color(" &7Use: &e5h, 30m, 1h30m, 3h50m, 45s, 5m30s&7, or just seconds &e3600"));
            return;
        }
        plugin.setMaintenanceActive(true);
        autoWhitelistSource(source);
        kickNonWhitelisted();
        plugin.getMaintenanceTimer().start(seconds);
        source.sendMessage(prefix.append(color("&aTimed maintenance enabled for &e" + formatTimeDisplay(seconds) + "&a.")));
        plugin.getLogger().info("Timed maintenance for {}s enabled by {}", seconds, source);
    }

    private void handleReload(CommandSource source) {
        plugin.getConfigManager().load();
        plugin.getWhitelistManager().load();
        source.sendMessage(prefix.append(color("&aConfiguration and whitelist reloaded.")));
        plugin.getLogger().info("Configuration reloaded by {}", source);
    }

    private void handleAdd(CommandSource source, String[] args) {
        if (args.length < 2) {
            source.sendMessage(prefix.append(color("&cUsage: /fdmt add <player>")));
            return;
        }
        String entry = args[1];
        WhitelistManager wm = plugin.getWhitelistManager();
        if (wm.add(entry)) {
            source.sendMessage(prefix.append(color("&aAdded &e" + entry + " &ato the whitelist.")));
        } else {
            source.sendMessage(prefix.append(color("&e" + entry + " &cis already in the whitelist.")));
        }
    }

    private void handleRemove(CommandSource source, String[] args) {
        if (args.length < 2) {
            source.sendMessage(prefix.append(color("&cUsage: /fdmt remove <player>")));
            return;
        }
        String entry = args[1];
        WhitelistManager wm = plugin.getWhitelistManager();
        if (wm.remove(entry)) {
            source.sendMessage(prefix.append(color("&aRemoved &e" + entry + " &afrom the whitelist.")));
        } else {
            source.sendMessage(prefix.append(color("&e" + entry + " &cis not in the whitelist.")));
        }
    }

    private void handleList(CommandSource source) {
        WhitelistManager wm = plugin.getWhitelistManager();
        Set<String> whitelisted = wm.getWhitelisted();
        if (whitelisted.isEmpty()) {
            source.sendMessage(prefix.append(color("&cThe whitelist is empty.")));
            return;
        }
        source.sendMessage(prefix.append(color("&6Whitelisted players (&e" + whitelisted.size() + "&6):")));
        for (String entry : whitelisted) {
            source.sendMessage(color(" &7- &e" + entry));
        }
    }

    private void handleStatus(CommandSource source) {
        if (!plugin.isMaintenanceActive()) {
            source.sendMessage(prefix.append(color("&cMaintenance is currently &4DISABLED&c.")));
            return;
        }
        if (plugin.isTimerActive() && plugin.getMaintenanceTimer().isRunning()) {
            int h = plugin.getMaintenanceTimer().getHours();
            int m = plugin.getMaintenanceTimer().getMinutes();
            int s = plugin.getMaintenanceTimer().getSeconds();
            source.sendMessage(prefix.append(color("&6Maintenance is &aENABLED &6(timed mode)")));
            source.sendMessage(color(" &7Time remaining: &e" + h + "h " + m + "m " + s + "s"));
        } else {
            source.sendMessage(prefix.append(color("&6Maintenance is &aENABLED &6(normal mode)")));
        }
    }

    private void handleCheck(CommandSource source, String[] args) {
        if (args.length < 2) {
            source.sendMessage(prefix.append(color("&cUsage: /fdmt check <player>")));
            return;
        }
        String target = args[1];
        WhitelistManager wm = plugin.getWhitelistManager();
        boolean found = wm.getWhitelisted().stream()
                .anyMatch(e -> e.equalsIgnoreCase(target));
        if (found) {
            source.sendMessage(prefix.append(color("&e" + target + " &ais whitelisted.")));
        } else {
            source.sendMessage(prefix.append(color("&e" + target + " &cis not whitelisted.")));
        }
    }

    private void autoWhitelistSource(CommandSource source) {
        if (source instanceof Player) {
            Player player = (Player) source;
            String uuidStr = player.getUniqueId().toString();
            WhitelistManager wm = plugin.getWhitelistManager();
            if (!wm.getWhitelisted().contains(uuidStr) &&
                !wm.getWhitelisted().contains(player.getUsername().toLowerCase())) {
                wm.add(uuidStr);
                source.sendMessage(prefix.append(color("&7Auto-added to whitelist.")));
            }
        }