better logging

This commit is contained in:
Jeddunk 2020-10-14 13:43:29 +02:00
parent b7ec6a62a3
commit 7c5329fd54
9 changed files with 201 additions and 88 deletions

View File

@ -38,7 +38,7 @@ Download the latest release and extract it into any folder (e.g. `%USERPROFILE%\
* Select a language and tick the options if needed. * Select a language and tick the options if needed.
* Click on *"Save"*. * Click on *"Save"*.
### Java 11 ### Java 11/Java 14
*WIP* *WIP*
@ -58,3 +58,10 @@ The following dependencies are licensed under the Apache License 2.0:
The following dependencies are licensed under the MIT License: The following dependencies are licensed under the MIT License:
* jsoup * jsoup
* Unirest-Java * Unirest-Java
* slf4j
* Copy Rename Maven Plugin
The following dependencies are licensed under the GPL2 License:
* fuzzywuzzy
Logback is dual-licensed under the EPL v1.0 and the LGPL 2.1.

View File

@ -75,5 +75,9 @@
<orderEntry type="library" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" />
<orderEntry type="library" name="Maven: org.codehaus.plexus:plexus-utils:1.5.8" level="project" /> <orderEntry type="library" name="Maven: org.codehaus.plexus:plexus-utils:1.5.8" level="project" />
<orderEntry type="library" name="Maven: org.sonatype.plexus:plexus-build-api:0.0.7" level="project" /> <orderEntry type="library" name="Maven: org.sonatype.plexus:plexus-build-api:0.0.7" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.jansi:jansi:1.18" level="project" />
</component> </component>
</module> </module>

13
pom.xml
View File

@ -21,7 +21,7 @@
<groupId>xyz.jeddunk</groupId> <groupId>xyz.jeddunk</groupId>
<artifactId>auto-cream-api</artifactId> <artifactId>auto-cream-api</artifactId>
<version>1.1.0</version> <version>1.2.0</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -208,6 +208,15 @@
<artifactId>copy-rename-maven-plugin</artifactId> <artifactId>copy-rename-maven-plugin</artifactId>
<version>1.0.1</version> <version>1.0.1</version>
</dependency> </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -34,12 +34,15 @@ import javafx.scene.control.*;
import javafx.stage.*; import javafx.stage.*;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.commons.configuration2.ex.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.jeddunk.autocreamapi.pojo.App; import xyz.jeddunk.autocreamapi.pojo.App;
import xyz.jeddunk.autocreamapi.util.CreamApiConfig; import xyz.jeddunk.autocreamapi.util.CreamApiConfig;
import xyz.jeddunk.autocreamapi.util.CreamApiDllHandler; import xyz.jeddunk.autocreamapi.util.CreamApiDllHandler;
import xyz.jeddunk.autocreamapi.util.SteamAppsListCache; import xyz.jeddunk.autocreamapi.util.SteamAppsListCache;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
@ -52,31 +55,29 @@ import java.util.stream.Stream;
public class Controller implements Initializable { public class Controller implements Initializable {
final Logger logger = LoggerFactory.getLogger(Controller.class);
private static final String GLYPH_FAILURE = "TIMES";
private static final String GLYPH_SUCCESS = "CHECK";
private static final Color COLOR_FAILURE = Color.web("#E53935");
private static final Color COLOR_SUCCESS = Color.web("#43A047");
private static final String REGEX = "(?<steamApiDll>steam_api(?:64)?.dll)$"; private static final String REGEX = "(?<steamApiDll>steam_api(?:64)?.dll)$";
public Label creamApiDllApplied;
public Label creamApiConfigExists;
public FontAwesomeIconView creamApiDllAppliedIcon;
public FontAwesomeIconView creamApiConfigExistsIcon;
private CreamApiDllHandler handler = null; private CreamApiDllHandler handler = null;
private final CreamApiConfig config = CreamApiConfig.getInstance();
private final SteamAppsListCache cache = new SteamAppsListCache();
private boolean is64Bit; private boolean is64Bit;
private boolean isSameFile; private boolean isSameFile;
{
try {
handler = CreamApiDllHandler.getInstance();
} catch (IOException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("CreamAPI DLLs missing!");
alert.setHeaderText("CreamAPI DLL files can't be found!");
alert.setContentText("Please download CreamAPI and extract the non-log " +
"version in the same folder as Auto-CreamAPI!\nThe program will now close.");
alert.showAndWait();
System.exit(10);
}
}
private final CreamApiConfig config = CreamApiConfig.getInstance(); @FXML
private final SteamAppsListCache cache = new SteamAppsListCache(); public Label creamApiDllApplied;
@FXML
public Label creamApiConfigExists;
@FXML
public FontAwesomeIconView creamApiDllAppliedIcon;
@FXML
public FontAwesomeIconView creamApiConfigExistsIcon;
@FXML @FXML
public Label state_label; public Label state_label;
@FXML @FXML
@ -96,7 +97,7 @@ public class Controller implements Initializable {
@FXML @FXML
public CheckBox unlock_all_checkbox; public CheckBox unlock_all_checkbox;
@FXML @FXML
public CheckBox use_steamdb_dlc; public CheckBox steamdb_dlc_checkbox;
@FXML @FXML
public Button reset_button; public Button reset_button;
@FXML @FXML
@ -106,16 +107,32 @@ public class Controller implements Initializable {
@FXML @FXML
public Button path_button; public Button path_button;
@FXML @FXML
public Button retrieveDlcList_button; public Button getDlcList_button;
private String steamApiPathString; private String steamApiPathString;
{
try {
handler = CreamApiDllHandler.getInstance();
} catch (FileNotFoundException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("CreamAPI DLLs missing!");
alert.setHeaderText("CreamAPI DLL files can't be found!");
alert.setContentText("Please download CreamAPI and extract the non-log " +
"version in the same folder as Auto-CreamAPI!\nThe program will now close.");
alert.showAndWait();
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
}
}
public Controller() { public Controller() {
} }
@FXML @FXML
@Override @Override
public void initialize(URL location, ResourceBundle resources) { public void initialize(URL location, ResourceBundle resources) {
use_steamdb_dlc.setSelected(true); steamdb_dlc_checkbox.setSelected(true);
appId_textfield.textProperty().addListener(appIdChangesGameName()); appId_textfield.textProperty().addListener(appIdChangesGameName());
game_name_textfield.setOnKeyReleased(event -> { game_name_textfield.setOnKeyReleased(event -> {
KeyCode code = event.getCode(); KeyCode code = event.getCode();
@ -131,6 +148,7 @@ public class Controller implements Initializable {
generate_tooltips(); generate_tooltips();
fix_dlc_textarea_prompt_text(); fix_dlc_textarea_prompt_text();
reset(true); reset(true);
state_label.setText("Ready.");
} }
private void read() { private void read() {
@ -145,8 +163,8 @@ public class Controller implements Initializable {
} }
private void emptyFields() { private void emptyFields() {
creamApiDllAppliedIcon.setGlyphName("TIMES"); /*setIndicator(creamApiDllApplied, creamApiDllAppliedIcon, COLOR_FAILURE, GLYPH_FAILURE);
creamApiConfigExistsIcon.setGlyphName("TIMES"); setIndicator(creamApiConfigExists, creamApiConfigExistsIcon, COLOR_FAILURE, GLYPH_FAILURE);*/
appId_textfield.setText(""); appId_textfield.setText("");
dlc_textarea.setText(""); dlc_textarea.setText("");
game_name_textfield.setText(""); game_name_textfield.setText("");
@ -164,6 +182,12 @@ public class Controller implements Initializable {
Tooltip extra_protection_tooltip = new Tooltip("\"extra protection\""); Tooltip extra_protection_tooltip = new Tooltip("\"extra protection\"");
extra_protection_checkbox.setTooltip(extra_protection_tooltip); extra_protection_checkbox.setTooltip(extra_protection_tooltip);
Tooltip.install(extra_protection_checkbox, extra_protection_tooltip); Tooltip.install(extra_protection_checkbox, extra_protection_tooltip);
Tooltip steamdb_dlc_tooltip = new Tooltip("Additionally get DLC data from SteamDB.\n" +
"Especially useful for DLC that is not listed on the Steam Store.\n" +
"This sometimes doesn't work because SteamDB may block access for scrapers.");
steamdb_dlc_checkbox.setTooltip(steamdb_dlc_tooltip);
Tooltip.install(steamdb_dlc_checkbox, steamdb_dlc_tooltip);
} }
private ChangeListener<String> appIdChangesGameName() { private ChangeListener<String> appIdChangesGameName() {
@ -196,10 +220,10 @@ public class Controller implements Initializable {
state_label.setText("Successfully reset all fields!"); state_label.setText("Successfully reset all fields!");
} }
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
System.err.println("Error reading cream_api.ini! " + logger.warn("Error reading cream_api.ini! " +
"This can be ignored if setting up CreamAPI for the first time."); "This can be ignored if setting up CreamAPI for the first time.");
} catch (NullPointerException e) { } catch (NullPointerException e) {
System.err.println("Can't fill out fields, no configuration file set!"); logger.warn("Can't fill out fields, no configuration file set!");
if (!silent) { if (!silent) {
state_label.setText("Could not reset fields, no configuration file set!"); state_label.setText("Could not reset fields, no configuration file set!");
} }
@ -208,8 +232,6 @@ public class Controller implements Initializable {
} }
private void updateIndicators() { private void updateIndicators() {
Color colorSuccess = Color.web("#43A047");
Color colorFailure = Color.web("#E53935");
try { try {
is64Bit = false; is64Bit = false;
if (!steamApiPathString.isEmpty()) { if (!steamApiPathString.isEmpty()) {
@ -221,36 +243,30 @@ public class Controller implements Initializable {
String md5 = DigestUtils.md5Hex(is); String md5 = DigestUtils.md5Hex(is);
isSameFile = Objects.equals(md5, handler.getDllMd5(is64Bit)); isSameFile = Objects.equals(md5, handler.getDllMd5(is64Bit));
if (isSameFile) { if (isSameFile) {
creamApiDllApplied.setTextFill(colorSuccess); setIndicator(creamApiDllApplied, creamApiDllAppliedIcon, COLOR_SUCCESS, GLYPH_SUCCESS);
creamApiDllAppliedIcon.setFill(colorSuccess);
creamApiDllAppliedIcon.setGlyphName("CHECK");
} else { } else {
creamApiDllApplied.setTextFill(colorFailure); setIndicator(creamApiDllApplied, creamApiDllAppliedIcon, COLOR_FAILURE, GLYPH_FAILURE);
creamApiDllAppliedIcon.setFill(colorFailure);
creamApiDllAppliedIcon.setGlyphName("TIMES");
} }
Path configPath = Paths.get(config.getPath()); Path configPath = Paths.get(config.getPath());
if (Files.exists(configPath) && Files.size(configPath) > 0L) { if (Files.exists(configPath) && Files.size(configPath) > 0L) {
creamApiConfigExists.setTextFill(colorSuccess); setIndicator(creamApiConfigExists, creamApiConfigExistsIcon, COLOR_SUCCESS, GLYPH_SUCCESS);
creamApiConfigExistsIcon.setFill(colorSuccess);
creamApiConfigExistsIcon.setGlyphName("CHECK");
} else { } else {
creamApiConfigExists.setTextFill(colorFailure); setIndicator(creamApiConfigExists, creamApiConfigExistsIcon, COLOR_FAILURE, GLYPH_FAILURE);
creamApiConfigExistsIcon.setFill(colorFailure);
creamApiConfigExistsIcon.setGlyphName("TIMES");
} }
} }
} catch (Exception e) { } catch (Exception e) {
System.err.println("Error! Resetting visual indicators!"); logger.warn("Resetting visual indicators!");
creamApiDllApplied.setTextFill(colorFailure); setIndicator(creamApiDllApplied, creamApiDllAppliedIcon, COLOR_FAILURE, GLYPH_FAILURE);
creamApiDllAppliedIcon.setFill(colorFailure); setIndicator(creamApiConfigExists, creamApiConfigExistsIcon, COLOR_FAILURE, GLYPH_FAILURE);
creamApiDllAppliedIcon.setGlyphName("TIMES");
creamApiConfigExists.setTextFill(colorFailure);
creamApiConfigExistsIcon.setFill(colorFailure);
creamApiConfigExistsIcon.setGlyphName("TIMES");
} }
} }
private void setIndicator(Label label, FontAwesomeIconView icon, Color color, String glyphName) {
label.setTextFill(color);
icon.setFill(color);
icon.setGlyphName(glyphName);
}
public void save() { public void save() {
Service<Void> s = new Service<Void>() { Service<Void> s = new Service<Void>() {
@Override @Override
@ -271,7 +287,7 @@ public class Controller implements Initializable {
e.printStackTrace(); e.printStackTrace();
cancel(); cancel();
} catch (NullPointerException e) { } catch (NullPointerException e) {
System.err.println("No configuration file set!"); logger.warn("No configuration file set!");
cancel(); cancel();
} }
updateIndicators(); updateIndicators();
@ -298,12 +314,14 @@ public class Controller implements Initializable {
public void getAppId() { public void getAppId() {
final List<App> games = cache.findListOfGames(game_name_textfield.getText()); final List<App> games = cache.findListOfGames(game_name_textfield.getText());
if (games.isEmpty()) { if (games.isEmpty()) {
logger.info("No game name was given, setting AppID to \"-1\"!");
appId_textfield.setText("-1"); appId_textfield.setText("-1");
} else if (games.size() == 1) { } else if (games.size() == 1) {
App game = games.get(0); App game = games.get(0);
game_name_textfield.setText(game.getName()); game_name_textfield.setText(game.getName());
appId_textfield.setText(String.valueOf(game.getAppId())); appId_textfield.setText(String.valueOf(game.getAppId()));
} else { } else {
logger.info("Multiple results found, opening search result window!");
try { try {
URL resource = ClassLoader.getSystemResource("searchResultWindow.fxml"); URL resource = ClassLoader.getSystemResource("searchResultWindow.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(resource); FXMLLoader fxmlLoader = new FXMLLoader(resource);
@ -327,7 +345,7 @@ public class Controller implements Initializable {
public void unlockAll_disableDlcTextArea() { public void unlockAll_disableDlcTextArea() {
dlc_textarea.setDisable(unlock_all_checkbox.isSelected()); dlc_textarea.setDisable(unlock_all_checkbox.isSelected());
retrieveDlcList_button.setDisable(unlock_all_checkbox.isSelected()); getDlcList_button.setDisable(unlock_all_checkbox.isSelected());
} }
/** /**
@ -342,7 +360,7 @@ public class Controller implements Initializable {
@Override @Override
protected Void call() { protected Void call() {
Map<Integer, String> collect = Map<Integer, String> collect =
cache.getDlcMap(appId_textfield.getText(), use_steamdb_dlc.isSelected()); cache.getDlcMap(appId_textfield.getText(), steamdb_dlc_checkbox.isSelected());
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
collect.forEach((k, v) -> sb.append(k).append("=").append(v).append("\n")); collect.forEach((k, v) -> sb.append(k).append("=").append(v).append("\n"));
dlc_textarea.setText(sb.toString()); dlc_textarea.setText(sb.toString());
@ -373,16 +391,16 @@ public class Controller implements Initializable {
new FileChooser.ExtensionFilter("Steam API DLL", new FileChooser.ExtensionFilter("Steam API DLL",
"steam_api.dll", "steam_api64.dll"); "steam_api.dll", "steam_api64.dll");
chooser.getExtensionFilters().add(filter); chooser.getExtensionFilters().add(filter);
final File file = chooser.showOpenDialog(path_button.getScene().getWindow()); File file = chooser.showOpenDialog(path_button.getScene().getWindow());
try { try {
config.setConfig(file.getParent() + "\\cream_api.ini"); config.setConfig(file.getParent() + "\\cream_api.ini");
path_textfield.setText(file.getParent());
steamApiPathString = file.getAbsolutePath();
} catch (ConfigurationException | IOException e) { } catch (ConfigurationException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (NullPointerException e) { } catch (NullPointerException e) {
System.err.println("Could not set config file location! Did you cancel the file chooser?"); logger.warn("Could not set config file location! Did you cancel the file chooser?");
} }
path_textfield.setText(file.getParent());
steamApiPathString = file.getAbsolutePath();
emptyFields(); emptyFields();
reset(true); reset(true);
state_label.setText("Ready."); state_label.setText("Ready.");
@ -406,7 +424,8 @@ public class Controller implements Initializable {
Path dir = path.getParent(); Path dir = path.getParent();
Path secondDll = Paths.get(dir.toString() + secondDllString); Path secondDll = Paths.get(dir.toString() + secondDllString);
if (Files.exists(secondDll)) { if (Files.exists(secondDll)) {
System.out.println("Alternative DLL found!"); //System.out.println("Alternative DLL found!");
logger.info("Second DLL found: (" + secondDll.toString() + ")!");
InputStream is = Files.newInputStream(secondDll); InputStream is = Files.newInputStream(secondDll);
String md5 = DigestUtils.md5Hex(is); String md5 = DigestUtils.md5Hex(is);
boolean isSameFile1 = Objects.equals(md5, handler.getDllMd5(!is64Bit)); boolean isSameFile1 = Objects.equals(md5, handler.getDllMd5(!is64Bit));
@ -441,7 +460,7 @@ public class Controller implements Initializable {
save_button.setDisable(b); save_button.setDisable(b);
getAppId_button.setDisable(b); getAppId_button.setDisable(b);
path_button.setDisable(b); path_button.setDisable(b);
retrieveDlcList_button.setDisable(b); getDlcList_button.setDisable(b);
} }
public void resetFromButton() { public void resetFromButton() {

View File

@ -20,14 +20,20 @@ import javafx.scene.control.cell.TreeItemPropertyValueFactory;
import javafx.scene.input.MouseButton; import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent; import javafx.scene.input.MouseEvent;
import javafx.stage.Stage; import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.jeddunk.autocreamapi.pojo.App; import xyz.jeddunk.autocreamapi.pojo.App;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import static java.text.MessageFormat.format;
public class SearchResultWindowController implements Initializable { public class SearchResultWindowController implements Initializable {
final Logger logger = LoggerFactory.getLogger(SearchResultWindowController.class);
@FXML @FXML
public Button okButton; public Button okButton;
@FXML @FXML
@ -62,6 +68,7 @@ public class SearchResultWindowController implements Initializable {
public void confirm() { public void confirm() {
App app = gameTable.getSelectionModel().getSelectedItem().getValue(); App app = gameTable.getSelectionModel().getSelectedItem().getValue();
logger.info(format("Game selected: {0} ({1})!", app.getName(), app.getAppId()));
parent.game_name_textfield.setText(app.getName()); parent.game_name_textfield.setText(app.getName());
parent.appId_textfield.setText(String.valueOf(app.getAppId())); parent.appId_textfield.setText(String.valueOf(app.getAppId()));
Stage current = (Stage) okButton.getScene().getWindow(); Stage current = (Stage) okButton.getScene().getWindow();
@ -69,8 +76,9 @@ public class SearchResultWindowController implements Initializable {
} }
public void cancel() { public void cancel() {
parent.game_name_textfield.setText(""); logger.info("Closing window without setting game!");
parent.appId_textfield.setText("-1"); /*parent.game_name_textfield.setText("");
parent.appId_textfield.setText("-1");*/
Stage current = (Stage) cancelButton.getScene().getWindow(); Stage current = (Stage) cancelButton.getScene().getWindow();
current.close(); current.close();
} }
@ -89,11 +97,12 @@ public class SearchResultWindowController implements Initializable {
} }
lastTime = currentTime; lastTime = currentTime;
if (isDblClicked) { if (isDblClicked) {
App app = gameTable.getSelectionModel().getSelectedItem().getValue(); /*App app = gameTable.getSelectionModel().getSelectedItem().getValue();
parent.game_name_textfield.setText(app.getName()); parent.game_name_textfield.setText(app.getName());
parent.appId_textfield.setText(String.valueOf(app.getAppId())); parent.appId_textfield.setText(String.valueOf(app.getAppId()));
Stage current = (Stage) gameTable.getScene().getWindow(); Stage current = (Stage) gameTable.getScene().getWindow();
current.close(); current.close();*/
confirm();
} }
} }
} }

View File

@ -19,12 +19,18 @@ import org.apache.commons.configuration2.*;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.commons.configuration2.ex.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.text.MessageFormat;
import java.util.*; import java.util.*;
import static java.text.MessageFormat.format;
public class CreamApiConfig { public class CreamApiConfig {
final Logger logger = LoggerFactory.getLogger(CreamApiConfig.class);
private static CreamApiConfig configInstance; private static CreamApiConfig configInstance;
private static final Configurations CONFIGS = new Configurations(); private static final Configurations CONFIGS = new Configurations();
@ -48,7 +54,7 @@ public class CreamApiConfig {
config = CONFIGS.ini(path); config = CONFIGS.ini(path);
config.setCommentLeadingCharsUsedInInput(";"); config.setCommentLeadingCharsUsedInInput(";");
} catch (ConfigurationException e) { } catch (ConfigurationException e) {
System.err.println("No config file found in default location!"); logger.warn("No config file found in default location!");
//e.printStackTrace(); //e.printStackTrace();
} }
@ -88,10 +94,10 @@ public class CreamApiConfig {
try { try {
read(); read();
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
System.err.println("Error reading cream_api.ini! " + logger.warn("Error reading cream_api.ini! " +
"This can be ignored if setting up CreamAPI for the first time."); "This can be ignored if setting up CreamAPI for the first time.");
} catch (NullPointerException e) { } catch (NullPointerException e) {
System.err.println("Can't fill out fields, no configuration file set!"); logger.warn("Can't fill out fields, no configuration file set!");
} }
} }
@ -151,7 +157,7 @@ public class CreamApiConfig {
Arrays.stream(str.split("\\R+")).forEach(line -> { Arrays.stream(str.split("\\R+")).forEach(line -> {
final String[] split = line.split("\\s*=\\s*", 2); final String[] split = line.split("\\s*=\\s*", 2);
if (split.length == 2) dlc.put(Integer.parseInt(split[0]), split[1]); if (split.length == 2) dlc.put(Integer.parseInt(split[0]), split[1]);
else System.err.println(MessageFormat.format("Error while splitting line: \"{0}\"", line)); else logger.error(format("Error while splitting line: \"{0}\"", line));
}); });
} }
@ -204,9 +210,9 @@ public class CreamApiConfig {
public void setConfig(String path) throws ConfigurationException, IOException { public void setConfig(String path) throws ConfigurationException, IOException {
File file = new File(path); File file = new File(path);
if (file.createNewFile()) { if (file.createNewFile()) {
System.out.println("New config file created!"); logger.info("New config file created!");
} else { } else {
System.out.println("Using existing config file!"); logger.info("Using existing config file!");
} }
this.config = CONFIGS.ini(path); this.config = CONFIGS.ini(path);
this.config.setCommentLeadingCharsUsedInInput(";"); this.config.setCommentLeadingCharsUsedInInput(";");

View File

@ -27,6 +27,8 @@ import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.jeddunk.autocreamapi.pojo.App; import xyz.jeddunk.autocreamapi.pojo.App;
import xyz.jeddunk.autocreamapi.pojo.SteamAppsList; import xyz.jeddunk.autocreamapi.pojo.SteamAppsList;
import xyz.jeddunk.autocreamapi.util.env.MainEnv; import xyz.jeddunk.autocreamapi.util.env.MainEnv;
@ -40,6 +42,8 @@ import java.util.stream.Collectors;
public class SteamAppsListCache { public class SteamAppsListCache {
final Logger logger = LoggerFactory.getLogger(SteamAppsListCache.class);
private SteamAppsList list = new SteamAppsList(); private SteamAppsList list = new SteamAppsList();
private final File cacheFile = new File("steamapps.json"); private final File cacheFile = new File("steamapps.json");
private MainEnv env; private MainEnv env;
@ -51,6 +55,7 @@ public class SteamAppsListCache {
env = (MainEnv) envDefault.newInstance(); env = (MainEnv) envDefault.newInstance();
// System.out.println(env.getKey()); // System.out.println(env.getKey());
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
logger.debug("Default environment missing, using main environemnt...");
env = new MainEnv(); env = new MainEnv();
} catch (IllegalAccessException | InstantiationException e) { } catch (IllegalAccessException | InstantiationException e) {
// Only thrown by newInstance() // Only thrown by newInstance()
@ -60,16 +65,16 @@ public class SteamAppsListCache {
try { try {
getListFromFile(); getListFromFile();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
System.err.println("File does not exist, trying to create steamapps.json for the first time..."); logger.info("File does not exist, trying to create steamapps.json for the first time...");
//fileFound = false; //fileFound = false;
sync(); sync();
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
System.err.println("File seems to be corrupt, trying to recreate steamapps.json..."); logger.warn("File seems to be corrupt, trying to recreate steamapps.json...");
//fileFound = false; //fileFound = false;
sync(); sync();
} }
if (Instant.now().isAfter(list.getTimestamp().plus(Duration.ofDays(3)))) { if (Instant.now().isAfter(list.getTimestamp().plus(Duration.ofDays(3)))) {
System.err.println("List in file is not recent!"); logger.info("List in file is not recent!");
sync(); sync();
} }
} }
@ -109,7 +114,7 @@ public class SteamAppsListCache {
} }
private void getListFromApi() { private void getListFromApi() {
System.out.println("Trying to get SteamAppList from API..."); logger.info("Trying to get SteamAppList from API...");
List<App> apps = getApps(); List<App> apps = getApps();
list.setTimestamp(Instant.now()); list.setTimestamp(Instant.now());
list.setSteamAppsList(apps); list.setSteamAppsList(apps);
@ -125,24 +130,24 @@ public class SteamAppsListCache {
} }
private void saveListToFile() throws IOException { private void saveListToFile() throws IOException {
System.out.println("Trying to save SteamAppList to file \"" + cacheFile.getAbsolutePath() + "\"..."); logger.info("Trying to save SteamAppList to file \"" + cacheFile.getAbsolutePath() + "\"...");
Gson gson = new Gson(); Gson gson = new Gson();
String jsonString = gson.toJson(list); String jsonString = gson.toJson(list);
BufferedWriter fOut = new BufferedWriter(new FileWriter(cacheFile)); BufferedWriter fOut = new BufferedWriter(new FileWriter(cacheFile));
fOut.write(jsonString); fOut.write(jsonString);
fOut.close(); fOut.close();
System.out.println("Successfully saved SteamAppList to file \"" + cacheFile.getAbsolutePath() + "\"..."); logger.info("Successfully saved SteamAppList to file \"" + cacheFile.getAbsolutePath() + "\"...");
} }
private void getListFromFile() throws FileNotFoundException, JsonSyntaxException { private void getListFromFile() throws FileNotFoundException, JsonSyntaxException {
System.out.println("Trying to get SteamAppList from file \"" + cacheFile.getAbsolutePath() + "\"..."); logger.info("Trying to get SteamAppList from file \"" + cacheFile.getAbsolutePath() + "\"...");
BufferedReader fIn = new BufferedReader(new FileReader(cacheFile)); BufferedReader fIn = new BufferedReader(new FileReader(cacheFile));
String json = fIn.lines().collect(Collectors.joining()); String json = fIn.lines().collect(Collectors.joining());
final Type type = new TypeToken<SteamAppsList>() { final Type type = new TypeToken<SteamAppsList>() {
}.getType(); }.getType();
Gson gson = new Gson(); Gson gson = new Gson();
list = gson.fromJson(json, type); list = gson.fromJson(json, type);
System.out.println("Successfully got SteamAppList from file \"" + cacheFile.getAbsolutePath() + "\"..."); logger.info("Successfully got SteamAppList from file \"" + cacheFile.getAbsolutePath() + "\"...");
} }
public Map<Integer, String> getDlcMap(String appId, boolean use_steamdb) { public Map<Integer, String> getDlcMap(String appId, boolean use_steamdb) {
@ -164,13 +169,15 @@ public class SteamAppsListCache {
steamStoreDLCs.put(Integer.parseInt(dlc_id), dlc_name); steamStoreDLCs.put(Integer.parseInt(dlc_id), dlc_name);
} }
} catch (HttpStatusException e) { } catch (HttpStatusException e) {
logger.error(e.getUrl());
if (e.getStatusCode() == 404) { if (e.getStatusCode() == 404) {
System.err.println("App ID empty or not found! (HTTP Status Code: 404)"); logger.error("App ID empty or not found! (HTTP Status Code: 404)");
} else { } else {
System.err.printf("Error occurred while trying to get list of DLCs " + /*System.err.printf("Error occurred while trying to get list of DLCs " +
"(HTTP Status Code: %d)%n", e.getStatusCode()); "(HTTP Status Code: %d)%n", e.getStatusCode());*/
logger.error("Error occurred while trying to get list of DLCs " +
"(HTTP Status Code: " + e.getStatusCode() + ")");
} }
System.err.println(e.getUrl());
} catch (NullPointerException | IOException e) { } catch (NullPointerException | IOException e) {
// ignore // ignore
} }
@ -194,13 +201,15 @@ public class SteamAppsListCache {
steamDbDLCs.put(Integer.parseInt(dlc_id), dlc_name); steamDbDLCs.put(Integer.parseInt(dlc_id), dlc_name);
} }
} catch (HttpStatusException e) { } catch (HttpStatusException e) {
logger.error(e.getUrl());
if (e.getStatusCode() == 404) { if (e.getStatusCode() == 404) {
System.err.println("App ID empty or not found! (HTTP Status Code: 404)"); logger.error("App ID empty or not found! (HTTP Status Code: 404)");
} else { } else {
System.err.printf("Error occurred while trying to get list of DLCs " + /*System.err.printf("Error occurred while trying to get list of DLCs " +
"(HTTP Status Code: %d)%n", e.getStatusCode()); "(HTTP Status Code: %d)%n", e.getStatusCode());*/
logger.error("Error occurred while trying to get list of DLCs " +
"(HTTP Status Code: " + e.getStatusCode() + ")");
} }
System.err.println(e.getUrl());
} catch (NullPointerException | IOException e) { } catch (NullPointerException | IOException e) {
// ignore // ignore
} }

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Auto-CreamAPI
~ Copyright (C) 2020 Jeddunk
~
~ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
~ License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
~ version.
~
~ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
~ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
~
~ You should have received a copy of the GNU General Public License along with this program. If not, see
~ <https://www.gnu.org/licenses/>.
-->
<configuration>
<property name="PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %msg%n"/>
<!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
the key "bySecond" into the logger context. This value will be
available to all subsequent configuration elements. -->
<timestamp key="bySecond" datePattern="yyyy'_'MM'_'dd'-'HH'_'mm'_'ss"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!--withJansi>true</withJansi-->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<!-- use the previously created timestamp to create a uniquely
named log file -->
<file>autocreamapi_${bySecond}.log</file>
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<logger name="com.base22" level="TRACE"/>
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>

View File

@ -67,7 +67,7 @@
<JFXTextArea fx:id="dlc_textarea" maxHeight="1.7976931348623157E308" prefHeight="999999.0" <JFXTextArea fx:id="dlc_textarea" maxHeight="1.7976931348623157E308" prefHeight="999999.0"
promptText="List of DLC..." GridPane.columnSpan="2147483647" GridPane.rowIndex="2" promptText="List of DLC..." GridPane.columnSpan="2147483647" GridPane.rowIndex="2"
GridPane.rowSpan="2147483647"/> GridPane.rowSpan="2147483647"/>
<JFXCheckBox fx:id="use_steamdb_dlc" text="Additionally use SteamDB for DLCs" <JFXCheckBox fx:id="steamdb_dlc_checkbox" text="Additionally use SteamDB for DLCs"
GridPane.rowIndex="1"/> GridPane.rowIndex="1"/>
</GridPane> </GridPane>
</TitledPane> </TitledPane>
@ -87,7 +87,7 @@
<JFXComboBox fx:id="language_combobox" editable="true" promptText="Language" GridPane.columnSpan="2147483647" GridPane.rowIndex="2" /> <JFXComboBox fx:id="language_combobox" editable="true" promptText="Language" GridPane.columnSpan="2147483647" GridPane.rowIndex="2" />
<JFXCheckBox fx:id="offline_checkbox" text="Force offline mode" GridPane.columnSpan="2147483647" GridPane.rowIndex="3" /> <JFXCheckBox fx:id="offline_checkbox" text="Force offline mode" GridPane.columnSpan="2147483647" GridPane.rowIndex="3" />
<JFXCheckBox fx:id="extra_protection_checkbox" text="Try to bypass game-specific protection" GridPane.columnSpan="2147483647" GridPane.rowIndex="4" /> <JFXCheckBox fx:id="extra_protection_checkbox" text="Try to bypass game-specific protection" GridPane.columnSpan="2147483647" GridPane.rowIndex="4" />
<JFXButton fx:id="retrieveDlcList_button" maxHeight="1.7976931348623157E308" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onAction="#getDlcList" ripplerFill="BLACK" text="Get DLCs for AppID" GridPane.rowIndex="6" /> <JFXButton fx:id="getDlcList_button" maxHeight="1.7976931348623157E308" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onAction="#getDlcList" ripplerFill="BLACK" text="Get DLCs for AppID" GridPane.rowIndex="6" />
<JFXButton fx:id="save_button" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" onAction="#save" ripplerFill="BLACK" text="Save" GridPane.columnIndex="1" GridPane.rowIndex="6" /> <JFXButton fx:id="save_button" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" onAction="#save" ripplerFill="BLACK" text="Save" GridPane.columnIndex="1" GridPane.rowIndex="6" />
<JFXButton fx:id="reset_button" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" onAction="#resetFromButton" ripplerFill="BLACK" text="Reset" GridPane.columnIndex="2" GridPane.rowIndex="6" /> <JFXButton fx:id="reset_button" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" onAction="#resetFromButton" ripplerFill="BLACK" text="Reset" GridPane.columnIndex="2" GridPane.rowIndex="6" />
<BorderPane.margin> <BorderPane.margin>