Skip to content

Добавил команду /givepass для продления проходок #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .idea/misc.xml

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

такое грузить не оч хорошо, это должно контролится через gitignore, но следи все равно)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, мой косяк,проморгал

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion src/main/java/org/joutak/joutaktemplate/JouTakTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.bukkit.plugin.java.JavaPlugin;
import org.joutak.joutaktemplate.commands.GivePassCommand;
import org.joutak.joutaktemplate.data.PlayerJoinListener;


@Slf4j
Expand All @@ -13,12 +15,17 @@ public final class JouTakTemplate extends JavaPlugin {

@Override
public void onEnable() {

instance = this;
if (!getDataFolder().exists()) getDataFolder().mkdirs();
getCommand("givepass").setExecutor(new GivePassCommand(this));
getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
log.info("Плагин JouTakTemplate успешно включен.");
}

@Override
public void onDisable() {
// Plugin shutdown logic
log.info("Плагин JouTekTemplate отключён");
}

}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а как ты видишь, какая цель у этого класса? т.е , какую задачу он решает

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если на сервере какие-то тех. неполадки и нужно продлить пользователям проходки ибо они не виноваты в технических проблемах.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я имел в виду несколько иной подход: класс должен выполнять только действия, связанные с конкретной командой, например, продлением проходок. В текущей реализации он дополнительно занимается чтением и записью данных в файл.

В данном случае, класс небольшой, это не создаёт значительных проблем. Однако в более сложных проектах предпочтительно разделять функциональность, создавая отдельные утилитные классы для работы с файлами. Постоянное создание объектов для чтения и записи (Reader/Writer) вручную, вместо использования готовых экземпляров из одного класса, может привести к сложностям с отладкой ошибок, связанных с их настройками.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да,я понимаю, просто посчитал что в данном случае так как проект маленький, то можно реализовать reader/writer не вынося их в отдельный класс. Для масштабируемости конечно лучше вынести, если надо, то могу реализовать

Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package org.joutak.joutaktemplate.commands;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.joutak.joutaktemplate.data.PlayerPass;

import java.io.*;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

public class GivePassCommand implements CommandExecutor {
private final JavaPlugin javaPlugin;
private final File jsonFile;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public GivePassCommand(JavaPlugin javaPlugin){
this.javaPlugin = javaPlugin;
this.jsonFile = new File(javaPlugin.getDataFolder(), "passes.json");
}

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args){
if (args.length != 1){
sender.sendMessage(ChatColor.RED + "Использование команды /givepass <количество дней>");
return false;
}

int days;
try
{
days = Integer.parseInt(args[0]);
} catch (NumberFormatException e){
sender.sendMessage(ChatColor.RED + "Введите целое число ");
return false;
}

if(!jsonFile.exists()){
sender.sendMessage(ChatColor.RED+"Файл passes.json не найден");
return false;
}

try(Reader reader = new FileReader(jsonFile)) {
Type listType = new TypeToken<List<PlayerPass>>() {
}.getType();
List<PlayerPass> passes = gson.fromJson(reader, listType);

LocalDate now = LocalDate.now();

for (PlayerPass pass : passes) {
LocalDate passUntil = LocalDate.parse(pass.getPassValidUntil(), formatter);
LocalDate newValidUntil = passUntil.isAfter(now) ? passUntil.plusDays(days) : now.plusDays(days);

pass.setPassValidUntil(newValidUntil.format(formatter));
pass.setLastPaymentDate(now.format(formatter));
}

try (Writer writer = new FileWriter(jsonFile)) {
gson.toJson(passes, writer);
}

sender.sendMessage(ChatColor.GREEN + "Проходки продлены на " + days + " дня(ей)");
return true;
}
catch (IOException | DateTimeParseException e){
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "Ошибка при обработке файла.");
return false;
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, этого в задаче не было, но чисто на "подумать". Часто бывает, что либо в БД, либо с фронта( если он есть), приходит Json, с полями, названия которых отличаются от бековских.

Типа: в коде у нас lastPaymentDate, а приходит last_payment_date, есть представление, как такое разруливать?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

@MaksProg MaksProg Jun 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В Gson если я правильно понимаю можно использовать аннотацию @SerializedName в котором указывается имя переменной с которой к нам приходит Json.

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.joutak.joutaktemplate.data;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.io.*;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.bukkit.plugin.java.JavaPlugin;

public class PlayerJoinListener implements Listener {

private final File jsonFile;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public PlayerJoinListener(JavaPlugin plugin) {
this.jsonFile = new File(plugin.getDataFolder(), "passes.json");
}

@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
String nickname = event.getPlayer().getName();

List<PlayerPass> passes = new ArrayList<>();

if (jsonFile.exists()) {
try (Reader reader = new FileReader(jsonFile)) {
Type listType = new TypeToken<List<PlayerPass>>() {}.getType();
passes = gson.fromJson(reader, listType);
} catch (IOException e) {
e.printStackTrace();
}
}

boolean exists = passes.stream().anyMatch(p -> p.getNickname().equalsIgnoreCase(nickname));
if (!exists) {
LocalDate now = LocalDate.now();
PlayerPass newPass = new PlayerPass();
newPass.setNickname(nickname);
newPass.setLastPaymentDate(now.format(formatter));
newPass.setPassValidUntil(now.format(formatter));
passes.add(newPass);

// Сохранить обратно
try (Writer writer = new FileWriter(jsonFile)) {
gson.toJson(passes, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
11 changes: 11 additions & 0 deletions src/main/java/org/joutak/joutaktemplate/data/PlayerPass.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.joutak.joutaktemplate.data;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class PlayerPass {
private String nickname;
private String lastPaymentDate;
private String passValidUntil;
}
8 changes: 5 additions & 3 deletions src/main/resources/plugin.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
name: JouTakTemplate
version: '${project.version}'
version: 1.0-SNAPSHOT
main: org.joutak.joutaktemplate.JouTakTemplate
api-version: '1.20'
api-version: 1.20
commands:
joutest: {}
givepass:
description: Раздаёт проходки игрокам на N дней
usage: /givepass <days>