Anpassung Logger

This commit is contained in:
Ocame
2024-12-08 22:32:26 +01:00
parent c7a9a84dac
commit a38cf1995f
8 changed files with 100 additions and 16 deletions

View File

@ -5,7 +5,7 @@ plugins {
application.mainClass = "de.ocame.ffdiscordbot.Main" application.mainClass = "de.ocame.ffdiscordbot.Main"
group 'de.ocame' group 'de.ocame'
version '1.2-SNAPSHOT' version '1.3-SNAPSHOT'
repositories { repositories {

View File

@ -12,9 +12,10 @@ public class ConfigLoader {
try (FileInputStream input = new FileInputStream("ffBot.conf")) { try (FileInputStream input = new FileInputStream("ffBot.conf")) {
properties.load(input); properties.load(input);
} catch (IOException e) { } catch (IOException e) {
System.err.println("Konfigurationsdatei konnte nicht geladen werden: " + e.getMessage()); LoggerUtil.log("info", "ConfigLoader", "Konfigurationsdatei konnte nicht geladen werden: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
LoggerUtil.log("info", "ConfigLoader", "Konfigurationsdatei wurde geladen");
} }
public String getToken() { public String getToken() {

View File

@ -47,10 +47,12 @@ public class FanFiktionReader {
public void checkAlerts() { public void checkAlerts() {
try { try {
LoggerUtil.log("info", "Reader", "Beginn Check Alerts");
Document alertPage = fetchHTMLWithAuthentication(URL + "/?a=i"); Document alertPage = fetchHTMLWithAuthentication(URL + "/?a=i");
if (alertPage == null) if (alertPage == null) {
LoggerUtil.log("info", "Reader", "Keine Seite gefunden");
return; return;
}
// Story Check // Story Check
Element authorBox = alertPage.getElementById("ffcbox-alerts_author-box"); Element authorBox = alertPage.getElementById("ffcbox-alerts_author-box");
@ -59,6 +61,8 @@ public class FanFiktionReader {
for (Element row : rows) { for (Element row : rows) {
checkNewStoryFromAlert(row); checkNewStoryFromAlert(row);
} }
if(rows.isEmpty())
LoggerUtil.log("info", "Reader", "Keine neuen Storys");
} }
// Kapitel Check // Kapitel Check
@ -89,6 +93,9 @@ public class FanFiktionReader {
} }
} }
if(rows.isEmpty())
LoggerUtil.log("info", "Reader", "Keine neuen Kapitel");
} }
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
@ -96,6 +103,7 @@ public class FanFiktionReader {
} }
Random random = new Random(); Random random = new Random();
this.time = random.nextLong(24 * 60, 34 * 60); this.time = random.nextLong(24 * 60, 34 * 60);
LoggerUtil.log("info", "Reader", "Ende Check Alerts");
} }
/** /**
@ -104,6 +112,7 @@ public class FanFiktionReader {
* @param row * @param row
*/ */
public void checkNewStoryFromAlert(Element row) { public void checkNewStoryFromAlert(Element row) {
LoggerUtil.log("info", "Reader", "Check neue Storys");
Elements cols = row.select("td"); Elements cols = row.select("td");
if (cols.size() >= 2) { // Ensure there are at least two columns if (cols.size() >= 2) { // Ensure there are at least two columns
/*name, link, ffid, date, autor*/ /*name, link, ffid, date, autor*/
@ -142,8 +151,12 @@ public class FanFiktionReader {
* @param chapterDate * @param chapterDate
*/ */
public void checkNewChapter(String url, long chapterDate) { public void checkNewChapter(String url, long chapterDate) {
try { checkNewChapter(url, chapterDate, false);
}
public void checkNewChapter(String url, long chapterDate, boolean force) {
try {
LoggerUtil.log("info", "Reader", "Check neue Kapitel");
Document storyPage = fetchHTMLWithAuthentication(url); Document storyPage = fetchHTMLWithAuthentication(url);
if (storyPage == null) if (storyPage == null)
return; return;
@ -172,14 +185,15 @@ public class FanFiktionReader {
// todo: fehler behandlung // todo: fehler behandlung
} }
if (!SQLiteStorage.checkChapter(ffid, Long.parseLong(chapterNumer))) { if (!SQLiteStorage.checkChapter(ffid, Long.parseLong(chapterNumer)) || force) {
/* todo: neue Chapter gefunden Ausgabe */ /* todo: neue Chapter gefunden Ausgabe */
if (SQLiteStorage.isStoryInvalid(ffid)) { if (SQLiteStorage.isStoryInvalid(ffid)) {
readandSaveStory(storyPage); readandSaveStory(storyPage);
} }
DataStory ds = SQLiteStorage.getStory(ffid); DataStory ds = SQLiteStorage.getStory(ffid);
DataChapter newChapter = new DataChapter(chapterName, URL + onChange, ffid, chapterDate, Long.parseLong(chapterNumer)); DataChapter newChapter = new DataChapter(chapterName, URL + onChange, ffid, chapterDate, Long.parseLong(chapterNumer));
SQLiteStorage.insertChapter(newChapter); if(!SQLiteStorage.checkChapter(ffid, Long.parseLong(chapterNumer)))
SQLiteStorage.insertChapter(newChapter);
//clearChapter(); //clearChapter();
new ChapterNotifier(jda, newChapter, ds).sendOutput(); new ChapterNotifier(jda, newChapter, ds).sendOutput();
} }
@ -275,7 +289,7 @@ public class FanFiktionReader {
* Führt den Login aus * Führt den Login aus
*/ */
public void login() { public void login() {
System.out.print("Login muss ausgeführt werden"); LoggerUtil.log("info", "Reader", "Login muss ausgeführt werden");
try { try {
ConfigLoader configLoader = new ConfigLoader(); ConfigLoader configLoader = new ConfigLoader();
@ -288,6 +302,7 @@ public class FanFiktionReader {
if (nameBox.isEmpty()) { if (nameBox.isEmpty()) {
time += 2 * 60 * 60; // Zeit um 2h erhöhen time += 2 * 60 * 60; // Zeit um 2h erhöhen
new InfoNotifier(jda).setMessagetext("Login Fehlgeschlagen").sendOutput(); new InfoNotifier(jda).setMessagetext("Login Fehlgeschlagen").sendOutput();
LoggerUtil.log("info", "Reader", "Login Fehlgeschlagen");
} }
Elements aBox = logintPage.select("input[name='a']"); Elements aBox = logintPage.select("input[name='a']");
@ -311,9 +326,11 @@ public class FanFiktionReader {
if (!nameBox.isEmpty()) { if (!nameBox.isEmpty()) {
time += 2 * 60 * 60; // Zeit um 2h erhöhen time += 2 * 60 * 60; // Zeit um 2h erhöhen
new InfoNotifier(jda).setMessagetext("Login Fehlgeschlagen").sendOutput(); new InfoNotifier(jda).setMessagetext("Login Fehlgeschlagen").sendOutput();
LoggerUtil.log("info", "Reader", "Login Fehlgeschlagen");
} }
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
LoggerUtil.log("error", "Reader", "Login nicht erfolgreich " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
@ -353,7 +370,7 @@ public class FanFiktionReader {
try { try {
Document sendToFav = fetcher.fetchHtml(URL + "/?a=q&a1=v&t=addstory&lbi=popup-addtofav-body&ar=1&action=i", postData); Document sendToFav = fetcher.fetchHtml(URL + "/?a=q&a1=v&t=addstory&lbi=popup-addtofav-body&ar=1&action=i", postData);
if(sendToFav.getElementsByClass("successbox").isEmpty()) { if(sendToFav.getElementsByClass("successbox").isEmpty()) {
System.out.print("Story konnte nicht hinzugefügt werden"); LoggerUtil.log("info", "Reader", "Story konnte nicht hinzugefügt werden");
new InfoNotifier(jda).setMessagetext("Story " + ffid + "konnte nicht hinzugefügt werden. \n" + sendToFav.toString()).sendOutput(); new InfoNotifier(jda).setMessagetext("Story " + ffid + "konnte nicht hinzugefügt werden. \n" + sendToFav.toString()).sendOutput();
} }
} }

View File

@ -0,0 +1,39 @@
package de.ocame.ffdiscordbot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerUtil {
//private static final Logger logger = LoggerFactory.getLogger(LoggerUtil.class);
/**
* Erstellt einen Logeintrag basierend auf Typ, Modul und Nachricht.
*
* @param logType Der Typ des Logs: "trace", "debug", "info", "warn", "error".
* @param module Der Name des Moduls oder Kontextes.
* @param message Die Nachricht, die geloggt werden soll.
*/
public static void log(String logType, String module, String message) {
Logger logger = LoggerFactory.getLogger(module);
switch (logType.toLowerCase()) {
case "trace":
logger.trace(message);
break;
case "debug":
logger.debug(message);
break;
case "info":
logger.info(message);
break;
case "warn":
logger.warn(message);
break;
case "error":
logger.error(message);
break;
default:
logger.warn("Unbekannter Log-Typ: {}. Nachricht: {}", logType, message);
}
}
}

View File

@ -53,6 +53,9 @@ public class Main {
// Berechne das neue Intervall basierend auf ffr.getTime() // Berechne das neue Intervall basierend auf ffr.getTime()
delay[0] = ffr.getTime(); delay[0] = ffr.getTime();
LoggerUtil.log("info", "Main", "neue Zeit: " + Long.toString(delay[0]));
// Plane die Aufgabe erneut mit dem neuen Intervall // Plane die Aufgabe erneut mit dem neuen Intervall
scheduledFuture.get().cancel(false); scheduledFuture.get().cancel(false);
scheduledFuture.set(scheduler.schedule(this, delay[0], TimeUnit.SECONDS)); scheduledFuture.set(scheduler.schedule(this, delay[0], TimeUnit.SECONDS));

View File

@ -3,6 +3,8 @@ import java.awt.*;
import java.sql.*; import java.sql.*;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -293,13 +295,13 @@ public class SQLiteStorage {
String channelOption = rs.getString("value"); String channelOption = rs.getString("value");
if (!channelOption.isEmpty()) { if (!channelOption.isEmpty()) {
JSONArray jsonArray = new JSONArray(channelOption); JSONObject jsonObject = new JSONObject(channelOption);
List<Long> longList = new ArrayList<>(); List<Long> longList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) { for (String key : jsonObject.keySet()) {
try { try {
// Versuche, den Wert in ein Long zu konvertieren // Versuche, den Wert in ein Long zu konvertieren
long value = jsonArray.getLong(i); long value = jsonObject.getLong(key);
longList.add(value); // Füge den Wert der Liste hinzu, wenn es ein gültiger Long ist longList.add(value); // Füge den Wert der Liste hinzu, wenn es ein gültiger Long ist
} catch (Exception e) { } catch (Exception e) {
// Wenn der Wert kein gültiges Long ist, wird er übersprungen // Wenn der Wert kein gültiges Long ist, wird er übersprungen

View File

@ -25,7 +25,7 @@ class SocketServerRunnable implements Runnable {
public void run() { public void run() {
int port = 12345; int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) { try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Socket-Server läuft auf Port " + port); LoggerUtil.log("info", "SocketRunnable", "Socket-Server läuft auf Port " + port);
while (true) { while (true) {
try (Socket clientSocket = serverSocket.accept(); try (Socket clientSocket = serverSocket.accept();
@ -33,7 +33,8 @@ class SocketServerRunnable implements Runnable {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String jsonMessageFromClient = in.readLine(); String jsonMessageFromClient = in.readLine();
System.out.println("Nachricht vom Client erhalten: " + jsonMessageFromClient); LoggerUtil.log("info", "SocketRunnable", "Nachricht vom Client erhalten: " + jsonMessageFromClient);
JSONObject jsonData = new JSONObject(jsonMessageFromClient); JSONObject jsonData = new JSONObject(jsonMessageFromClient);
String action = jsonData.getString("action"); String action = jsonData.getString("action");
@ -45,17 +46,19 @@ class SocketServerRunnable implements Runnable {
case "check" -> checkAction(out); case "check" -> checkAction(out);
case "chapterTest" -> chapterTest(jsonData, out); case "chapterTest" -> chapterTest(jsonData, out);
case "addFavo" -> addFavo(jsonData); case "addFavo" -> addFavo(jsonData);
case "forceChapter" -> forceChapter(jsonData);
} }
} }
catch (IOException | NullPointerException e) { catch (IOException | NullPointerException e) {
System.out.println("Fehler bei der Kommunikation mit dem Client: " + e.getMessage()); LoggerUtil.log("error", "SocketRunnable", "Fehler bei der Kommunikation mit dem Client: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
catch (IOException e) { catch (IOException e) {
System.out.println("Server konnte nicht gestartet werden: " + e.getMessage()); LoggerUtil.log("error", "SocketRunnable", "Server konnte nicht gestartet werden: " + e.getMessage());
} }
} }
private Boolean channelCheckAction(JSONObject jsonData, PrintWriter out) { private Boolean channelCheckAction(JSONObject jsonData, PrintWriter out) {
@ -118,4 +121,11 @@ class SocketServerRunnable implements Runnable {
String ffId = jsonData.getString("ffId"); String ffId = jsonData.getString("ffId");
ffr.addStoryToFavorit(ffId); ffr.addStoryToFavorit(ffId);
} }
private void forceChapter(JSONObject jsonData) {
String link = jsonData.getString("link");
String timestamp = jsonData.getString("timestamp");
ffr.checkNewChapter(link, ffr.DateToTimestamp(timestamp), true);
}
} }

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %boldCyan(%-34.-34thread) %red(%10.10X{jda.shard}) %boldGreen(%-15.-15logger{0}) %highlight(%-6level) %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>