/
ledart
/
RRP_LedNik
Обзор
Документация
Войти
/
ledart
/
RRP_LedNik
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
client/model/ChatHistoryManager.java
155 строк
6 KB
Darya
добавила быстрые сообщения в лобби и в комнате. история сообщений сохраняется в лобби и в комнатах
18 дек 2025, 03:32
18 дек 2025, 03:32
b48cb9c
Код
Авторство
О чём код?
package client.model; import java.io.*; import java.nio.file.*; import java.util.ArrayList; import java.util.List; public class ChatHistoryManager { private static final String CHAT_DIR = "chat_history"; private static final String LOBBY_FILE = "lobby_chat.txt"; private static final int MAX_HISTORY_LINES = 100; public ChatHistoryManager() { createChatDirectory(); } private void createChatDirectory() { try { Files.createDirectories(Paths.get(CHAT_DIR)); System.out.println("[ChatHistory] Directory created: " + CHAT_DIR); } catch (IOException e) { System.err.println("[ChatHistory] Error creating directory: " + e.getMessage()); } } // Сохранить сообщение лобби public void saveLobbyMessage(String message) { saveMessage(LOBBY_FILE, message); } // Сохранить сообщение комнаты public void saveRoomMessage(String roomName, String message) { String safeRoomName = roomName.replaceAll("[^a-zA-Z0-9_]", "_"); String fileName = "room_" + safeRoomName + ".txt"; saveMessage(fileName, message); } private void saveMessage(String fileName, String message) { try { Path filePath = Paths.get(CHAT_DIR, fileName); // Добавляем временную метку к сообщению String timestamp = java.time.LocalTime.now().format(java.time.format.DateTimeFormatter.ofPattern("HH:mm")); String fullMessage = "[" + timestamp + "] " + message; // Открываем файл для добавления (создаём если нет) try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { writer.write(fullMessage); writer.newLine(); } // Обрезаем файл если он слишком большой trimFileIfNeeded(filePath); } catch (IOException e) { System.err.println("[ChatHistory] Error saving message: " + e.getMessage()); } } // Загрузить историю лобби public List<String> loadLobbyHistory() { return loadHistory(LOBBY_FILE); } // Загрузить историю комнаты public List<String> loadRoomHistory(String roomName) { String safeRoomName = roomName.replaceAll("[^a-zA-Z0-9_]", "_"); String fileName = "room_" + safeRoomName + ".txt"; return loadHistory(fileName); } private List<String> loadHistory(String fileName) { List<String> history = new ArrayList<>(); Path filePath = Paths.get(CHAT_DIR, fileName); if (!Files.exists(filePath)) { System.out.println("[ChatHistory] No history file found: " + fileName); return history; } try { List<String> allLines = Files.readAllLines(filePath); // Берем последние MAX_HISTORY_LINES сообщений int startIndex = Math.max(0, allLines.size() - MAX_HISTORY_LINES); for (int i = startIndex; i < allLines.size(); i++) { history.add(allLines.get(i)); } System.out.println("[ChatHistory] Loaded " + history.size() + " messages from " + fileName); } catch (IOException e) { System.err.println("[ChatHistory] Error loading history: " + e.getMessage()); } return history; } // Удалить историю комнаты public void deleteRoomHistory(String roomName) { String safeRoomName = roomName.replaceAll("[^a-zA-Z0-9_]", "_"); String fileName = "room_" + safeRoomName + ".txt"; Path filePath = Paths.get(CHAT_DIR, fileName); try { if (Files.exists(filePath)) { Files.delete(filePath); System.out.println("[ChatHistory] Deleted room history: " + roomName); } } catch (IOException e) { System.err.println("[ChatHistory] Error deleting room history: " + e.getMessage()); } } // Обрезать файл если он слишком большой private void trimFileIfNeeded(Path filePath) throws IOException { List<String> allLines = Files.readAllLines(filePath); if (allLines.size() > MAX_HISTORY_LINES * 2) { // Оставляем последние MAX_HISTORY_LINES строк int startIndex = allLines.size() - MAX_HISTORY_LINES; List<String> trimmedLines = new ArrayList<>(); for (int i = startIndex; i < allLines.size(); i++) { trimmedLines.add(allLines.get(i)); } Files.write(filePath, trimmedLines); System.out.println("[ChatHistory] Trimmed file: " + filePath.getFileName()); } } // Очистить всю историю чата public void clearAllHistory() { try { Path chatDir = Paths.get(CHAT_DIR); if (Files.exists(chatDir)) { Files.walk(chatDir) .filter(Files::isRegularFile) .forEach(file -> { try { Files.delete(file); } catch (IOException e) { System.err.println("[ChatHistory] Error deleting file: " + e.getMessage()); } }); System.out.println("[ChatHistory] Cleared all chat history"); } } catch (IOException e) { System.err.println("[ChatHistory] Error clearing history: " + e.getMessage()); } } }