Skip to content

Commit

Permalink
Import custom maps from server. Add multiple maps at once.
Browse files Browse the repository at this point in the history
  • Loading branch information
cesar-rgon committed Aug 6, 2019
1 parent b6b0f79 commit 26fe49a
Show file tree
Hide file tree
Showing 7 changed files with 251 additions and 136 deletions.
6 changes: 6 additions & 0 deletions src/main/java/pojos/kf2factory/Kf2Common.java
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,14 @@ protected void removeCustomMapsFromKfEngineIni(List<Long> idWorkShopList, String

private String generateMapCycleLine(List<Map> mapList) {
StringBuffer sb = new StringBuffer("GameMapCycles=(Maps=(");
boolean showSeparator = true;
if (!mapList.isEmpty()) {
sb.append("\"----- OFFICIAL MAPS -----\",");
for (Map map: mapList) {
if (showSeparator && !map.getOfficial()) {
sb.append("\"----- CUSTOM MAPS -----\",");
showSeparator = false;
}
sb.append("\"").append(map.getCode()).append("\"");
if (mapList.indexOf(map) < (mapList.size() - 1)) {
sb.append(",");
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/pojos/listener/TimeListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public void run() {
try {
List<Path> kfmFilesPath = Files.walk(Paths.get(installationFolder + "/KFGame/Cache/" + map.getIdWorkShop()))
.filter(Files::isRegularFile)
.filter(f -> f.getFileName().toString().startsWith("KF-"))
.filter(f -> f.getFileName().toString().endsWith(".kfm"))
.filter(f -> f.getFileName().toString().toUpperCase().startsWith("KF-"))
.filter(f -> f.getFileName().toString().toUpperCase().endsWith(".KFM"))
.collect(Collectors.toList());

if (kfmFilesPath != null && !kfmFilesPath.isEmpty()) {
Expand Down
127 changes: 98 additions & 29 deletions src/main/java/stories/mapsedition/MapsEditionController.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@
import javafx.scene.layout.GridPane;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pojos.kf2factory.Kf2Common;
import pojos.kf2factory.Kf2Factory;
import pojos.listener.TimeListener;
import pojos.session.Session;
import start.MainApplication;
import utils.Utils;

import java.io.*;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -40,6 +44,8 @@

public class MapsEditionController implements Initializable {

private static final Logger logger = LogManager.getLogger(MapsEditionController.class);

private final MapsEditionFacade facade;
private String installationFolder;
private List<Map> mapList;
Expand Down Expand Up @@ -214,7 +220,7 @@ private void searchMapsKeyReleased() {
}

@FXML
private void addNewMapOnAction() {
private void addNewMapsOnAction() {
if (!facade.isCorrectInstallationFolder(installationFolder)) {
Utils.warningDialog("No maps can be added!", "The installation folder is not correct.\nSet it up in Install / Update section.");
return;
Expand All @@ -226,22 +232,38 @@ private void addNewMapOnAction() {
if (MapViewOptions.VIEW_OFFICIAL.equals(viewPaneCombo.getValue())) {
viewPaneCombo.setValue(MapViewOptions.VIEW_BOTH);
}
Optional<String> result = Utils.OneTextInputDialog("Add a new custom map", "Enter url / id WorkShop");
try {
if (result.isPresent() && StringUtils.isNotBlank(result.get())) {
Map customMap = facade.createNewCustomMapFromWorkshop(result.get(), installationFolder);
if (customMap != null) {
mapList.add(customMap);
Kf2Common kf2Common = Kf2Factory.getInstance();
kf2Common.addCustomMapToKfEngineIni(customMap.getIdWorkShop(), installationFolder);
GridPane gridpane = createMapGridPane(facade.getDto(customMap));
customMapsFlowPane.getChildren().add(gridpane);
} else {
Utils.errorDialog("Error adding new custom map", "The map could not be found", null);
Optional<String> result = Utils.OneTextInputDialog("Add new custom maps", "Enter url / id WorkShop\nIf more than one\nuse \",\" as separator");
if (result.isPresent() && StringUtils.isNotBlank(result.get())) {
StringBuffer success = new StringBuffer();
StringBuffer errors = new StringBuffer();

String[] array = result.get().replaceAll(" ", "").split(",");
Map customMap = null;
for (int i=0; i < array.length; i++) {
try {
customMap = facade.createNewCustomMapFromWorkshop(array[i], installationFolder);
if (customMap != null) {
mapList.add(customMap);
Kf2Common kf2Common = Kf2Factory.getInstance();
kf2Common.addCustomMapToKfEngineIni(customMap.getIdWorkShop(), installationFolder);
GridPane gridpane = createMapGridPane(facade.getDto(customMap));
customMapsFlowPane.getChildren().add(gridpane);
success.append("map name: ").append(customMap.getCode()).append(" - idWorkShop: ").append(customMap.getIdWorkShop()).append("\n");
} else {
errors.append("url/id WorkShop: ").append(array[i]).append("\n");
}
} catch (Exception e) {
errors.append("url/id WorkShop: ").append(array[i]).append("\n");
}
}
} catch (Exception e) {
Utils.errorDialog(e.getMessage(), "See stacktrace for more details", e);
if (StringUtils.isNotBlank(success)) {
Utils.infoDialog("These maps were successfully added to the launcher:", success.toString());
} else {
Utils.infoDialog("No maps were added", "Check the url/id WorkShop of the maps");
}
if (StringUtils.isNotBlank(errors)) {
Utils.errorDialog("Error adding next maps to the launcher:", errors.toString(), null);
}
}
}

Expand Down Expand Up @@ -314,24 +336,71 @@ private void removeMapsOnAction() {
}

@FXML
private void checkCacheMapsOnAction() {
Utils.infoDialog("This feature is not implemented yet. Will be enabled for next release.", "It will detect custom maps previously downloaded in the server\nand it will add them to the launcher automatically.");
return;
/*
File cacheFolder = new File(installationFolder + "/KFGame/Cache/");
File[] listOfFiles = cacheFolder.listFiles();
private void importMapsFromServerOnAction() {
if (!facade.isCorrectInstallationFolder(installationFolder)) {
Utils.warningDialog("No maps can be imported!", "The installation folder is not correct.\nSet it up in Install / Update section.");
return;
}
if (Session.getInstance().isRunningProcess()) {
Utils.warningDialog("No maps can be imported!", "At least one instance of the server is running. Close them.");
return;
}

for (int i=0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
try {
Long idWorkShop = Long.parseLong(listOfFiles[i].getName());
Optional<ButtonType> result = Utils.questionDialog("Import maps from server to the launcher", "This operation can take a few minutes.\nAre you sure you want to continue?");
if (result.isPresent() && result.get().equals(ButtonType.OK)) {
logger.info("Starting the process to import maps from the server to the launcher");

File cacheFolder = new File(installationFolder + "/KFGame/Cache/");
File[] listOfFiles = cacheFolder.listFiles();
StringBuffer success = new StringBuffer();
StringBuffer errors = new StringBuffer();
for (int i=0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
Map customMap = null;
Long idWorkShop = null;
try {
idWorkShop = Long.parseLong(listOfFiles[i].getName());
List<Path> kfmFilesPath = Files.walk(Paths.get(installationFolder + "/KFGame/Cache/" + idWorkShop))
.filter(Files::isRegularFile)
.filter(f -> f.getFileName().toString().toUpperCase().startsWith("KF-"))
.filter(f -> f.getFileName().toString().toUpperCase().endsWith(".KFM"))
.collect(Collectors.toList());

} catch (Exception e) {
// TODO: Manage this error
if (kfmFilesPath != null && !kfmFilesPath.isEmpty()) {
String filenameWithExtension = kfmFilesPath.get(0).getFileName().toString();
String[] array = filenameWithExtension.split(".kfm");
String mapName = array[0];
Optional<Map> customMapInDataBase = facade.findMapByCode(mapName);
if (!customMapInDataBase.isPresent()) {
customMap = facade.createNewCustomMapFromWorkshop(idWorkShop, mapName, installationFolder);
if (customMap != null) {
mapList.add(customMap);
Kf2Common kf2Common = Kf2Factory.getInstance();
kf2Common.addCustomMapToKfEngineIni(customMap.getIdWorkShop(), installationFolder);
GridPane gridpane = createMapGridPane(facade.getDto(customMap));
customMapsFlowPane.getChildren().add(gridpane);
success.append("map name: ").append(customMap.getCode()).append(" - idWorkShop: ").append(idWorkShop).append("\n");
} else {
logger.error("Error importing the customMap with idWorkShop: " + idWorkShop);
errors.append("idWorkShop: ").append(idWorkShop).append("\n");
}
}
}
} catch (Exception e) {
logger.error("Error importing the customMap: " + customMap.getCode() + " with idWorkShop: " + idWorkShop, e);
errors.append("map name: ").append(customMap.getCode()).append(" - idWorkShop: ").append(idWorkShop).append("\n");
}
}
}
logger.info("The process to import maps from the server to the launcher has finished.");
if (StringUtils.isNotBlank(success)) {
Utils.infoDialog("These maps were successfully imported from server to the launcher:", success.toString());
} else {
Utils.infoDialog("No maps were imported", "The server does not contain new maps to be imported\nor the maps could not be imported successfully\nSee launcher.log file for more details.");
}
if (StringUtils.isNotBlank(errors)) {
Utils.errorDialog("Error importing next maps from server to the launcher:", errors.toString() + "\nSee launcher.log file for more details.", null);
}
}
*/
}
}
3 changes: 3 additions & 0 deletions src/main/java/stories/mapsedition/MapsEditionFacade.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@

import java.sql.SQLException;
import java.util.List;
import java.util.Optional;

public interface MapsEditionFacade {
List<Map> listAllMaps() throws SQLException;
List<MapDto> getDtos(List<Map> mapList);
MapDto getDto(Map map);
String findPropertyValue(String key) throws Exception;
Map createNewCustomMapFromWorkshop(String urlIdWorkshop, String installationFolder) throws Exception;
Map createNewCustomMapFromWorkshop(Long idWorkShop, String mapName, String installationFolder) throws Exception;
MapDto deleteSelectedMap(String mapName) throws SQLException;
boolean isCorrectInstallationFolder(String installationFolder);
Optional<Map> findMapByCode(String mapName) throws SQLException;
}
36 changes: 33 additions & 3 deletions src/main/java/stories/mapsedition/MapsEditionFacadeImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ public String findPropertyValue(String key) throws Exception {
return propertyService.getPropertyValue("properties/config.properties", key);
}

private Map createNewCustomMap(String mapName, Long idWorkShop, String urlPhoto) throws Exception {
private Map createNewCustomMap(String mapName, Long idWorkShop, String urlPhoto, boolean downloaded) throws Exception {
if ((StringUtils.isBlank(mapName) || idWorkShop == null)) {
return null;
}
String baseUrlWorkshop = propertyService.getPropertyValue("properties/config.properties", Constants.CONFIG_MAP_BASE_URL_WORKSHOP);
String urlInfo = baseUrlWorkshop + idWorkShop;
Map customMap = new Map(mapName, false, urlInfo, idWorkShop, urlPhoto, false);
Map customMap = new Map(mapName, false, urlInfo, idWorkShop, urlPhoto, downloaded);
return MapDao.getInstance().insert(customMap);
}

Expand Down Expand Up @@ -96,7 +96,32 @@ public Map createNewCustomMapFromWorkshop(String urlIdWorkshop, String installat
File localfile = Utils.downloadImageFromUrlToFile(strUrlMapImage, absoluteTargetFolder, mapName);
String relativeTargetFolder = customMapLocalFolder + "/" + localfile.getName();

return createNewCustomMap(mapName, idWorkShop, relativeTargetFolder);
return createNewCustomMap(mapName, idWorkShop, relativeTargetFolder, false);
}

@Override
public Map createNewCustomMapFromWorkshop(Long idWorkShop, String mapName, String installationFolder) throws Exception {
String baseUrlWorkshop = propertyService.getPropertyValue("properties/config.properties", Constants.CONFIG_MAP_BASE_URL_WORKSHOP);
URL urlWorkShop = new URL(baseUrlWorkshop + idWorkShop);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlWorkShop.openStream()));
String strUrlMapImage = null;
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("image_src")) {
String[] array = line.split("\"");
strUrlMapImage = array[3];
}
if (StringUtils.isNotEmpty(strUrlMapImage)) {
break;
}
}
reader.close();
String customMapLocalFolder = propertyService.getPropertyValue("properties/config.properties", Constants.CONFIG_MAP_CUSTOM_LOCAL_FOLDER);
String absoluteTargetFolder = installationFolder + customMapLocalFolder;
File localfile = Utils.downloadImageFromUrlToFile(strUrlMapImage, absoluteTargetFolder, mapName);
String relativeTargetFolder = customMapLocalFolder + "/" + localfile.getName();

return createNewCustomMap(mapName, idWorkShop, relativeTargetFolder, true);
}

@Override
Expand All @@ -122,4 +147,9 @@ public boolean isCorrectInstallationFolder(String installationFolder) {
}
return false;
}

@Override
public Optional<Map> findMapByCode(String mapName) throws SQLException {
return MapDao.getInstance().findByCode(mapName);
}
}
2 changes: 2 additions & 0 deletions src/main/java/utils/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ public static Optional<String> OneTextInputDialog(String header, String content)
PropertyService propertyService = new PropertyServiceImpl();
String applicationTitle = propertyService.getPropertyValue("properties/config.properties", Constants.CONFIG_APPLICATION_TITLE);
dialog.setTitle(applicationTitle);
dialog.getDialogPane().setMinWidth(600);
dialog.setResizable(true);
} catch (Exception ex) {
dialog.setTitle("");
}
Expand Down
Loading

0 comments on commit 26fe49a

Please sign in to comment.