-
Notifications
You must be signed in to change notification settings - Fork 2
Добавил команду /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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. а как ты видишь, какая цель у этого класса? т.е , какую задачу он решает There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Если на сервере какие-то тех. неполадки и нужно продлить пользователям проходки ибо они не виноваты в технических проблемах. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я имел в виду несколько иной подход: класс должен выполнять только действия, связанные с конкретной командой, например, продлением проходок. В текущей реализации он дополнительно занимается чтением и записью данных в файл. В данном случае, класс небольшой, это не создаёт значительных проблем. Однако в более сложных проектах предпочтительно разделять функциональность, создавая отдельные утилитные классы для работы с файлами. Постоянное создание объектов для чтения и записи (Reader/Writer) вручную, вместо использования готовых экземпляров из одного класса, может привести к сложностям с отладкой ошибок, связанных с их настройками. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Кстати, этого в задаче не было, но чисто на "подумать". Часто бывает, что либо в БД, либо с фронта( если он есть), приходит Json, с полями, названия которых отличаются от бековских. Типа: в коде у нас lastPaymentDate, а приходит last_payment_date, есть представление, как такое разруливать? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
} | ||
} | ||
} | ||
} |
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; | ||
} |
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> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
такое грузить не оч хорошо, это должно контролится через gitignore, но следи все равно)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, мой косяк,проморгал