Advertisement
NoSloppy

again

Oct 13th, 2023 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.11 KB | None | 0 0
  1. package com.example.soundfontconverter;
  2.  
  3. import org.springframework.stereotype.Service;
  4.  
  5. import java.io.IOException;
  6. import java.nio.file.*;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.io.BufferedReader;
  11. import java.io.File;
  12. import java.io.FileReader;
  13. import java.util.stream.Stream;
  14. import java.util.Comparator;
  15. import java.util.stream.Collectors;
  16. import java.text.SimpleDateFormat;
  17. import java.util.Date;
  18.  
  19. @Service
  20. public class SoundFontNamingService {
  21.  
  22. enum BoardType {
  23. CFX,
  24. GH3,
  25. PROFFIE,
  26. VERSO,
  27. XENO3;
  28.  
  29. public static String getKey(BoardType source, BoardType target) {
  30. return source.name() + "_TO_" + target.name();
  31. }
  32. }
  33. private StringBuilder logStringBuilder = new StringBuilder();
  34. private boolean chained = false;
  35. private String realTarget = "PROFFIE";
  36. private static final String DEFAULTS_PATH = "./inis";
  37. private static final Map<String, String> CFX_TO_PROFFIE = new HashMap<>();
  38. private static final Map<String, String> CFX_TO_VERSO = new HashMap<>();
  39. private static final Map<String, String> GH3_TO_PROFFIE = new HashMap<>();
  40. private static final Map<String, String> PROFFIE_TO_CFX = new HashMap<>();
  41. private static final Map<String, String> PROFFIE_TO_GH3 = new HashMap<>();
  42. private static final Map<String, String> PROFFIE_TO_VERSO = new HashMap<>();
  43. private static final Map<String, String> PROFFIE_TO_XENO3 = new HashMap<>();
  44. private static final Map<String, String> VERSO_TO_CFX = new HashMap<>();
  45. private static final Map<String, String> VERSO_TO_PROFFIE = new HashMap<>();
  46. private static final Map<String, String> XENO3_TO_PROFFIE = new HashMap<>();
  47. //... additional board mappings can be added here
  48.  
  49. // Central mapping repository
  50. private static final Map<String, Map<String, String>> soundMappings = new HashMap<>();
  51. private static final Map<String, Integer> soundCounter = new HashMap<>();
  52.  
  53. static {
  54. initializeMappings();
  55. }
  56.  
  57. private static void loadMappingsFromCSV(String csvFilePath, Map<String, String> mapping) {
  58. try (BufferedReader reader = new BufferedReader(new FileReader(csvFilePath))) {
  59. String line;
  60. while ((line = reader.readLine()) != null) {
  61. String[] parts = line.split(",");
  62. if (parts.length >= 2) {
  63. mapping.put(parts[0], parts[1]);
  64. }
  65. }
  66. } catch (IOException e) {
  67. e.printStackTrace();
  68. }
  69. }
  70.  
  71. private static void safeLoadMappingsFromCSV(String csvFilePath, Map<String, String> mapping) {
  72. File f = new File(csvFilePath);
  73. if(f.exists() && !f.isDirectory()) {
  74. loadMappingsFromCSV(csvFilePath, mapping);
  75. }
  76. }
  77.  
  78. private static void initializeMappings() {
  79. safeLoadMappingsFromCSV("./CSV/CFX_TO_PROFFIE.csv", CFX_TO_PROFFIE);
  80. // safeLoadMappingsFromCSV("./CSV/CFX_TO_VERSO.csv", CFX_TO_VERSO);
  81. // safeLoadMappingsFromCSV("./CSV/GH3_TO_PROFFIE.csv", GH3_TO_PROFFIE);
  82. safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_CFX.csv", PROFFIE_TO_CFX);
  83. // safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_GH3.csv", PROFFIE_TO_CFX);
  84. safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_VERSO.csv", PROFFIE_TO_VERSO);
  85. safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_XENO3.csv", PROFFIE_TO_XENO3);
  86. // safeLoadMappingsFromCSV("./CSV/VERSO_TO_PROFFIE.csv", VERSO_TO_PROFFIE);
  87. safeLoadMappingsFromCSV("./CSV/XENO3_TO_PROFFIE.csv", XENO3_TO_PROFFIE);
  88. // ... and so on for other mappings ...
  89.  
  90. soundMappings.put(BoardType.getKey(BoardType.CFX, BoardType.PROFFIE), CFX_TO_PROFFIE);
  91. // soundMappings.put(BoardType.getKey(BoardType.CFX, BoardType.VERSO), CFX_TO_VERSO);
  92. soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.CFX), PROFFIE_TO_CFX);
  93. soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.GH3), PROFFIE_TO_CFX);
  94. soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.VERSO), PROFFIE_TO_VERSO);
  95. soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.XENO3), PROFFIE_TO_XENO3);
  96. soundMappings.put(BoardType.getKey(BoardType.GH3, BoardType.PROFFIE), CFX_TO_PROFFIE);
  97. // soundMappings.put(BoardType.getKey(BoardType.VERSO, BoardType.CFX), VERSO_TO_CFX);
  98. soundMappings.put(BoardType.getKey(BoardType.VERSO, BoardType.PROFFIE), VERSO_TO_PROFFIE);
  99. soundMappings.put(BoardType.getKey(BoardType.XENO3, BoardType.PROFFIE), XENO3_TO_PROFFIE);
  100.  
  101. // Reverse Mapping fist so actual mappings will override
  102.  
  103. // CFX to Proffie mapping
  104. for (Map.Entry<String, String> entry : PROFFIE_TO_CFX.entrySet()) {
  105. CFX_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
  106. }
  107. // for (Map.Entry<String, String> entry : VERSO_TO_CFX.entrySet()) {
  108. // CFX_TO_VERSO.putIfAbsent(entry.getValue(), entry.getKey());
  109. // }
  110. // Verso to Proffie mapping
  111. for (Map.Entry<String, String> entry : PROFFIE_TO_VERSO.entrySet()) {
  112. VERSO_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
  113. }
  114. // Xeno3 to Proffie mapping
  115. for (Map.Entry<String, String> entry : PROFFIE_TO_XENO3.entrySet()) {
  116. XENO3_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
  117. }
  118. }
  119.  
  120. private static void ensureDirectoryExists(Path dirPath) {
  121. try {
  122. if (!Files.exists(dirPath)) {
  123. Files.createDirectories(dirPath);
  124. System.out.println("Creating directory: " + dirPath);
  125. }
  126. } catch (IOException ex) {
  127. ex.printStackTrace();
  128. }
  129. }
  130.  
  131. private static void copyFile(Path sourcePath, Path targetPath) {
  132. try {
  133. Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
  134. } catch (IOException ex) {
  135. System.err.println("Error copying file from " + sourcePath + " to " + targetPath);
  136. ex.printStackTrace();
  137. }
  138. }
  139.  
  140.  
  141. // This version takes the optimizeForProffie parameter. It's the main logic
  142. private void convertSounds(BoardType sourceBoard, List<String> fileNames, BoardType targetBoard, String targetDir, boolean optimizeForProffie) throws IOException {
  143. soundCounter.clear();
  144. String key = BoardType.getKey(sourceBoard, targetBoard);
  145. System.out.println("----------------------------------------------------------------\n.");
  146. if (targetBoard == BoardType.PROFFIE && realTarget == "PROFFIE") {
  147. System.out.println("Converting from " + sourceBoard + " to " + targetBoard + "\n.");
  148. } else if (targetBoard != BoardType.PROFFIE) {
  149. realTarget = targetBoard.toString();
  150. } else {
  151. System.out.println("Converting from " + sourceBoard + " to " + realTarget + "\n.");
  152. }
  153.  
  154. // Directory structure code here:
  155. String sourceDirName = new File(sourceDir).getName();
  156. // Include a special case for GH3 output directory naming
  157. String finalTargetDir = targetDir + "/Converted_to_" + targetBoard + "/" +
  158. (targetBoard == BoardType.GH3 ? "sound1 - " : "") +
  159. sourceDirName;
  160.  
  161. // Prepare Log file
  162. if (chained == false) {
  163. ensureDirectoryExists(Paths.get(finalTargetDir));
  164. SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
  165. String currentDate = sdf.format(new Date());
  166. logStringBuilder.append("Converted with SoundFont Naming Converter 3.0\n");
  167. logStringBuilder.append("Brian Conner a.k.a NoSloppy\n\n");
  168. logStringBuilder.append(currentDate).append("\n");
  169.  
  170. if (targetBoard == BoardType.PROFFIE && realTarget == "PROFFIE") {
  171. logStringBuilder.append("Converted: ").append(sourceBoard).append(" to ").append(targetBoard).append("\n");
  172. logStringBuilder.append("Optimized for Fat32 performance: ").append(optimizeForProffie ? "Yes" : "No").append("\n\n");
  173. } else if (targetBoard != BoardType.PROFFIE) {
  174. realTarget = targetBoard.toString();
  175. } else {
  176. logStringBuilder.append("Converted: ").append(sourceBoard).append(" to ").append(realTarget).append("\n");
  177. logStringBuilder.append("\n");
  178. }
  179. }
  180.  
  181. // If it's Proffie to Proffie, skip the mapping
  182. Map<String, String> mapping;
  183. if (sourceBoard == BoardType.PROFFIE && targetBoard == BoardType.PROFFIE) {
  184. mapping = null; // No mapping required for Proffie to Proffie
  185. } else {
  186. if (!soundMappings.containsKey(key)) {
  187. System.out.println("Conversion from " + sourceBoard + " to " + targetBoard + " is not supported.");
  188. return;
  189. }
  190. mapping = soundMappings.get(key);
  191. }
  192.  
  193. ensureDirectoryExists(Paths.get(finalTargetDir));
  194.  
  195. // Check if source has directories named something like "Bonus Files" or "extra"
  196. boolean hasExtrasDirectories = false;
  197. try {
  198. hasExtrasDirectories = Files.walk(Paths.get(sourceDir), 1) // Only check immediate children
  199. .filter(Files::isDirectory).anyMatch(path -> {
  200. String dirName = path.getFileName().toString().toLowerCase();
  201. return dirName.contains("bonus") || dirName.contains("extra");
  202. });
  203. } catch (IOException ex) {
  204. ex.printStackTrace();
  205. }
  206.  
  207. // If "extras" directory is needed, create it now
  208. if (hasExtrasDirectories) {
  209. ensureDirectoryExists(Paths.get(finalTargetDir + "/extras"));
  210. }
  211.  
  212. // Main sound conversion
  213. Map<String, Integer> fileNameCounter = new HashMap<>();
  214. boolean fontSoundProcessed = false;
  215.  
  216. // We now loop through the fileNames list, and the filters are handled within the loop
  217. for (String fileName : fileNames) {
  218. if (!fileName.startsWith(".")) {
  219. // Assuming file names are in format "parentDir/file.wav"
  220. String[] parts = fileName.split("/");
  221. String parentDirName = parts.length > 1 ? parts[0].toLowerCase() : "";
  222. if (parentDirName.contains("bonus") || parentDirName.contains("extra")) {
  223. copyFile(Paths.get(sourceDir, fileName), Paths.get(finalTargetDir, "extras", fileName));
  224. String logEntryExtras = "Moved extra/bonus file to " + finalTargetDir + "/extras/" + fileName;
  225. System.out.println(logEntryExtras);
  226. logStringBuilder.append(logEntryExtras).append("\n");
  227. continue; // Skip to next iteration if it's an "extra" or "bonus" file
  228. }
  229. }
  230.  
  231. // Move non-wav files directly to the target folder
  232. if (!fileName.endsWith(".wav")) {
  233. // Update your database or renaming logic here
  234. String logEntryNonWav = "Moved non-wav file: " + fileName;
  235. System.out.println(logEntryNonWav);
  236. logStringBuilder.append(logEntryNonWav).append("\n");
  237. continue; // Continue to the next iteration as this is not a wav file
  238. }
  239.  
  240. // Move "track" wav files to "tracks" folder
  241. if (fileName.contains("track")) {
  242. ensureDirectoryExists(Paths.get(finalTargetDir + "/tracks"));
  243. // Assuming copyFile can handle file names, otherwise replace with appropriate logic
  244. copyFile(Paths.get(sourceDir, fileName), Paths.get(finalTargetDir, "tracks", fileName));
  245. String logEntryTrack = "Moved track file: " + fileName;
  246. System.out.println(logEntryTrack);
  247. logStringBuilder.append(logEntryTrack).append("\n");
  248. continue; // changed from return to continue to go to the next iteration
  249. }
  250.  
  251. // For other wav files, use the mapping
  252. String baseName = fileName.replaceAll(" (\\(\\d+\\))?\\.wav$|\\d+\\.wav$", ".wav");
  253. // If we're doing Proffie to Proffie, keep the baseName as is
  254. String convertedBaseName = (mapping == null) ? baseName : mapping.getOrDefault(baseName, baseName);
  255.  
  256. String outputPath;
  257. if (convertedBaseName != null) {
  258. int count = soundCounter.getOrDefault(convertedBaseName, 0) + 1;
  259. soundCounter.put(convertedBaseName, count);
  260.  
  261. String prefix = (convertedBaseName.contains(".")) ? convertedBaseName.substring(0, convertedBaseName.lastIndexOf('.')) : convertedBaseName;
  262. String formattedCount = String.valueOf(count);
  263.  
  264. if (targetBoard == BoardType.CFX) {
  265. String newPrefix;
  266. int currentCounter;
  267.  
  268. String switchKey = convertedBaseName.toLowerCase().replaceAll("\\.wav$", "");
  269. String commonKey;
  270. switch (switchKey) {
  271. // First, handle the special numbering and weird naming cases
  272. case "poweroff":
  273. commonKey = "pwroff";
  274. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  275. if (currentCounter == 1) {
  276. newPrefix = "poweroff";
  277. } else if (currentCounter == 2) {
  278. newPrefix = "pwroff2";
  279. } else {
  280. newPrefix = "poweroff" + (currentCounter - 1);
  281. }
  282. outputPath = finalTargetDir + "/" + newPrefix + ".wav";
  283. fileNameCounter.put(commonKey, currentCounter + 1);
  284. break;
  285.  
  286. // case "clash":
  287. // commonKey = "clash";
  288. // currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  289. // if (currentCounter == 1) {
  290. // newPrefix = "clash" + currentCounter;
  291. // } else if (currentCounter == 2) {
  292. // newPrefix = "fclash" + (currentCounter -1);
  293. // } else {
  294. // newPrefix = "clash" + (currentCounter - 1);
  295. // }
  296. // outputPath = finalTargetDir + "/" + newPrefix + ".wav";
  297. // fileNameCounter.put(commonKey, currentCounter + 1);
  298. // break;
  299.  
  300. case "font":
  301. commonKey = "font";
  302. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  303. if (currentCounter == 1) {
  304. outputPath = finalTargetDir + "/font" + ".wav";
  305. } else {
  306. int nextBootCounter = fileNameCounter.getOrDefault("boot", 1);
  307. outputPath = finalTargetDir + "/boot" + (nextBootCounter == 1 ? "" : nextBootCounter) + ".wav";
  308. fileNameCounter.put("boot", nextBootCounter + 1);
  309. }
  310. fileNameCounter.put(commonKey, currentCounter + 1);
  311. break;
  312.  
  313. // These get no number on the first file, then sequence the rest staring from 2
  314. case "boot":
  315. commonKey = "boot";
  316. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  317. outputPath = finalTargetDir + "/boot" + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  318. fileNameCounter.put(commonKey, currentCounter + 1);
  319. break;
  320.  
  321. case "color":
  322. commonKey = "color";
  323. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  324. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  325. fileNameCounter.put(commonKey, currentCounter + 1);
  326. break;
  327. case "blaster":
  328. commonKey = "blaster";
  329. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  330. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  331. fileNameCounter.put(commonKey, currentCounter + 1);
  332. break;
  333. case "poweron":
  334. commonKey = "poweron";
  335. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  336. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  337. fileNameCounter.put(commonKey, currentCounter + 1);
  338. break;
  339. case "lockup":
  340. commonKey = "lockup";
  341. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  342. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  343. fileNameCounter.put(commonKey, currentCounter + 1);
  344. break;
  345. case "drag":
  346. commonKey = "drag";
  347. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  348. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  349. fileNameCounter.put(commonKey, currentCounter + 1);
  350. break;
  351. case "force":
  352. commonKey = "force";
  353. currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  354. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
  355. fileNameCounter.put(commonKey, currentCounter + 1);
  356. break;
  357.  
  358. default:
  359. currentCounter = fileNameCounter.getOrDefault(switchKey, 1);
  360. outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + currentCounter + ".wav";
  361.  
  362. fileNameCounter.put(switchKey, currentCounter + 1);
  363. break;
  364. }
  365.  
  366. } else if (targetBoard == BoardType.PROFFIE) {
  367. if (prefix.length() > 6 && count == 1 && soundCounter.containsKey(baseName)) {
  368. formattedCount = String.valueOf(count);
  369. } else {
  370. formattedCount = (prefix.length() > 6) ? String.valueOf(count) : String.format("%02d", count);
  371. }
  372. if (optimizeForProffie) {
  373. outputPath = count == 1 ? finalTargetDir + "/" + prefix + ".wav" : finalTargetDir + "/" + prefix + "/" + prefix + formattedCount + ".wav";
  374.  
  375. if (count == 2) {
  376. Path originalPath = Paths.get(finalTargetDir, prefix + ".wav");
  377. Path newPath = Paths.get(finalTargetDir, prefix, prefix + (prefix.length() > 6 ? "1" : "01") + ".wav");
  378. ensureDirectoryExists(Paths.get(finalTargetDir + "/" + prefix));
  379. Files.move(originalPath, newPath, StandardCopyOption.REPLACE_EXISTING);
  380. String logEntryProffie = "Numbered and moved first file to subdirectory:\n"
  381. + " " + originalPath.subpath(2, originalPath.getNameCount())
  382. + " -> "
  383. + newPath.subpath(2, newPath.getNameCount());
  384. System.out.println(logEntryProffie);
  385. logStringBuilder.append(logEntryProffie).append("\n");
  386. }
  387. } else {
  388. outputPath = finalTargetDir + "/" + (count > 1 ? prefix + formattedCount : prefix) + ".wav";
  389.  
  390. if (count == 2) {
  391. Path originalPath = Paths.get(finalTargetDir, prefix + ".wav");
  392. Path newPath = Paths.get(finalTargetDir, prefix + (prefix.length() > 6 ? "1" : "01") + ".wav");
  393. Files.move(originalPath, newPath, StandardCopyOption.REPLACE_EXISTING);
  394. String logEntryProffie = "Numbered the first file:\n "
  395. + " " + originalPath.subpath(2, originalPath.getNameCount())
  396. + " -> "
  397. + newPath.subpath(2, newPath.getNameCount());
  398. System.out.println(logEntryProffie);
  399. logStringBuilder.append(logEntryProffie).append("\n");
  400. }
  401. }
  402. } else if (targetBoard == BoardType.VERSO && convertedBaseName.equals("font.wav")) {
  403. String commonKey = "font";
  404. int currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
  405. fileNameCounter.put(commonKey, currentCounter + 1);
  406.  
  407. if (currentCounter == 1) {
  408. outputPath = finalTargetDir + "/font.wav";
  409. copyFile(Paths.get(sourceDir, fileName), Paths.get(outputPath));
  410. String logEntryVerso = "Converted: " + path.getFileName().toString() + " -> " + outputPath.replace("temporaryDirectory/", "");
  411. System.out.println(logEntryVerso);
  412. logStringBuilder.append(logEntryVerso).append("\n");
  413. } else {
  414. String logEntryVersoSkipped = "Skipped additional 'font' file: " + fileName;
  415. System.out.println(logEntryVersoSkipped);
  416. logStringBuilder.append(logEntryVersoSkipped).append("\n");
  417. }
  418. return;
  419.  
  420. } else if (targetBoard == BoardType.XENO3) {
  421. outputPath = Paths.get(finalTargetDir, prefix + " (" + count + ").wav").toString();
  422.  
  423. } else if (count > 1 || (targetBoard != BoardType.PROFFIE && count == 1)) {
  424. outputPath = Paths.get(finalTargetDir, prefix + formattedCount + ".wav").toString();
  425. } else {
  426. outputPath = Paths.get(finalTargetDir, prefix + ".wav").toString();
  427. }
  428.  
  429. copyFile(Paths.get(sourceDir, fileName), Paths.get(outputPath));
  430. String logEntry = "Converted: " + path.getFileName().toString() + " -> " + outputPath.replace("temporaryDirectory/", "");
  431. System.out.println(logEntry);
  432. logStringBuilder.append(logEntry).append("\n");
  433.  
  434. } else { // convertedBaseName = null
  435. System.out.println("Skipped wav file without mapping: " + fileName);
  436. }
  437.  
  438. };
  439. if (chained == true) {
  440. logStringBuilder.append("\n*********----- MTFBWY -----*********\n");
  441. } else {
  442. logStringBuilder.append("\n\n");
  443. }
  444. try {
  445. System.out.println("--- Writing _Conversion_Log.txt ---");
  446. Files.writeString(Paths.get(finalTargetDir, "_Conversion_Log.txt"), logStringBuilder.toString());
  447. } catch (IOException e) {
  448. System.err.println("Failed to write log: " + e.getMessage());
  449. }
  450.  
  451.  
  452. // After processing all files, check for default INIs for Proffie
  453. if (targetBoard == BoardType.PROFFIE) {
  454. String[] defaultFiles = {"config.ini", "smoothsw.ini"};
  455. for (String defaultFile : defaultFiles) {
  456. File targetDefaultFile = new File(finalTargetDir, defaultFile);
  457. if (!targetDefaultFile.exists()) {
  458. File inisFile = new File(DEFAULTS_PATH + "/" + defaultFile);
  459. if (inisFile.exists()) {
  460. try {
  461. Files.copy(inisFile.toPath(), targetDefaultFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
  462. System.out.println("Copied default file: " + defaultFile);
  463. } catch (IOException e) {
  464. // e.printStackTrace();
  465. System.err.println("Error while copying file: " + defaultFile);
  466.  
  467. }
  468. }
  469. }
  470. }
  471. }
  472. }
  473.  
  474. public class MutableInt {
  475. public int value;
  476. public MutableInt(int value) {
  477. this.value = value;
  478. }
  479. }
  480.  
  481. public void cleanupTemporaryDirectory() {
  482. System.out.println("Removing any existing temporaryDirectory and generated zip file");
  483. try {
  484. Path tempDir = Paths.get("temporaryDirectory");
  485. if (Files.exists(tempDir)) {
  486. Files.walk(tempDir)
  487. .sorted(Comparator.reverseOrder()) // Important to delete child before parent
  488. .forEach(path -> {
  489. try {
  490. Files.deleteIfExists(path);
  491. } catch (IOException e) {
  492. // Handle the exception, e.g., logging it.
  493. e.printStackTrace();
  494. }
  495. });
  496. }
  497.  
  498. // Deleting the generated zip file.
  499. Files.deleteIfExists(Paths.get("temporaryDirectory.zip"));
  500.  
  501. } catch (IOException e) {
  502. // Handle the exception, e.g., logging it.
  503. e.printStackTrace();
  504. }
  505. }
  506.  
  507. public void convertSoundFont(List<Path> savedFiles, String sourceBoard, String targetBoard, boolean optimize) throws IOException {
  508. BoardType srcBoard = BoardType.valueOf(sourceBoard.toUpperCase());
  509. BoardType tgtBoard = BoardType.valueOf(targetBoard.toUpperCase());
  510.  
  511. String sourceDir = savedFiles.get(0).getParent().toString();
  512. convertSounds(srcBoard, sourceDir, tgtBoard, "temporaryDirectory", optimize);
  513. }
  514.  
  515. public void chainConvertSoundFont(List<Path> savedFiles, String sourceBoard, String targetBoard, boolean optimize) throws IOException {
  516. // Clear the StringBuilder for subsequent log entries
  517. logStringBuilder.setLength(0);
  518. if ("PROFFIE".equals(sourceBoard) || "PROFFIE".equals(targetBoard)) {
  519. // Just convert normally.
  520. convertSoundFont(savedFiles, sourceBoard, targetBoard, optimize);
  521. } else {
  522. // Do the chained conversion;
  523. // cCnvert to PROFFIE first and save it in /temporaryDirectory/Converted_to_PROFFIE.
  524. // Using realTarget for logging only
  525. realTarget = targetBoard;
  526. convertSoundFont(savedFiles, sourceBoard, "PROFFIE", false);
  527. chained = !chained;
  528.  
  529. // Now use the converted PROFFIE files as source for the actual target.
  530. // Clear the StringBuilder for subsequent log entries
  531. //logStringBuilder.setLength(0);
  532. Path tempProffieDir = Paths.get("temporaryDirectory", "Converted_to_PROFFIE");
  533. List<Path> proffieFiles = Files.walk(tempProffieDir)
  534. .filter(Files::isRegularFile)
  535. .collect(Collectors.toList());
  536. convertSoundFont(proffieFiles, "PROFFIE", targetBoard, false);
  537. chained = !chained;
  538.  
  539. // Optional: Cleanup the temporary directory used for the PROFFIE conversion.
  540. }
  541. }
  542.  
  543. public void removeOriginalDirectory(String originalDirName) {
  544. Path originalDir = Paths.get("temporaryDirectory", originalDirName);
  545. try {
  546. System.out.println("Initiating removal of directory: " + originalDir.toString());
  547. Files.walk(originalDir)
  548. .sorted(Comparator.reverseOrder()) // Important to delete child before parent
  549. .forEach(path -> {
  550. try {
  551. Files.deleteIfExists(path);
  552. } catch (IOException e) {
  553. e.printStackTrace();
  554. }
  555. });
  556. } catch (IOException e) {
  557. e.printStackTrace();
  558. }
  559. System.out.println("Completed removal of directory: " + originalDir.toString());
  560. }
  561.  
  562. public Path zipConvertedFiles(String targetDir) throws IOException {
  563. Path zipPath = Paths.get(targetDir + ".zip");
  564.  
  565. // Logging the structure
  566. Path sourcePath = Paths.get(targetDir);
  567. System.out.println("Logging directory structure before zipping:");
  568. Files.walk(sourcePath).forEach(p -> {
  569. // System.out.println(p.toString());
  570. });
  571. System.out.println("Starting to create ZIP file...");
  572.  
  573. try (FileSystem zipFs = FileSystems.newFileSystem(zipPath, Map.of("create", "true"))) {
  574. // Exclude the top-level source directory itself when walking
  575. Files.walk(sourcePath).filter(p -> !p.equals(sourcePath)).forEach(path -> {
  576. try {
  577. if (Files.isRegularFile(path) && Files.size(path) > 0) { // Ensure it's a file and has content
  578. String sourceDirName = sourcePath.getFileName().toString();
  579. Path destPath = zipFs.getPath("/" + sourceDirName + "/" + sourcePath.relativize(path).toString());
  580.  
  581. // Ensure the parent directory structure exists in the ZIP
  582. if (destPath.getParent() != null) {
  583. Files.createDirectories(destPath.getParent());
  584. }
  585.  
  586. Files.copy(path, destPath, StandardCopyOption.REPLACE_EXISTING);
  587. }
  588. } catch (NoSuchFileException e) {
  589. System.err.println("Directory structure in ZIP does not match expected structure: " + e.getMessage());
  590. } catch (Exception e) {
  591. e.printStackTrace();
  592. System.err.println("Error processing file: " + path.toString() +
  593. ". Destination path in ZIP: " + zipFs.getPath("/" + sourcePath.relativize(path).toString()));
  594. }
  595. });
  596.  
  597. } catch (Exception e) {
  598. e.printStackTrace();
  599. throw new IOException("Error encountered during zip operation: " + e.getMessage());
  600. }
  601. System.out.println("Conversion complete. Zip file saved and ready for download from " + targetDir + ".zip");
  602. return zipPath;
  603. }
  604. }
  605.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement