1
0
mirror of https://github.com/RipMeApp/ripme.git synced 2025-08-26 15:24:51 +02:00

Network fix

This commit is contained in:
Isaaku
2019-07-24 11:29:26 -05:00
parent 143e32adbf
commit c2e42f260e
2 changed files with 117 additions and 119 deletions

View File

@@ -31,7 +31,7 @@ public class UpdateUtils {
static { static {
try { try {
mainFileName = new File(UpdateUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath(); mainFileName = new File(UpdateUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
} catch (URISyntaxException e) { } catch (URISyntaxException | IllegalArgumentException e) {
mainFileName = "ripme.jar"; mainFileName = "ripme.jar";
logger.error("Unable to get path of jar"); logger.error("Unable to get path of jar");
e.printStackTrace(); e.printStackTrace();
@@ -73,16 +73,12 @@ public class UpdateUtils {
Document doc = null; Document doc = null;
try { try {
logger.debug("Retrieving " + UpdateUtils.updateJsonURL); logger.debug("Retrieving " + UpdateUtils.updateJsonURL);
doc = Jsoup.connect(UpdateUtils.updateJsonURL) doc = Jsoup.connect(UpdateUtils.updateJsonURL).timeout(10 * 1000).ignoreContentType(true).get();
.timeout(10 * 1000)
.ignoreContentType(true)
.get();
} catch (IOException e) { } catch (IOException e) {
logger.error("Error while fetching update: ", e); logger.error("Error while fetching update: ", e);
JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null,
"<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>", "<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>",
"RipMe Updater", "RipMe Updater", JOptionPane.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
return; return;
} finally { } finally {
logger.info("Current version: " + getThisJarVersion()); logger.info("Current version: " + getThisJarVersion());
@@ -105,8 +101,8 @@ public class UpdateUtils {
logger.error("Error while updating: ", e); logger.error("Error while updating: ", e);
} }
} else { } else {
logger.debug("This version (" + UpdateUtils.getThisJarVersion() + logger.debug("This version (" + UpdateUtils.getThisJarVersion()
") is the same or newer than the website's version (" + latestVersion + ")"); + ") is the same or newer than the website's version (" + latestVersion + ")");
logger.info("v" + UpdateUtils.getThisJarVersion() + " is the latest version"); logger.info("v" + UpdateUtils.getThisJarVersion() + " is the latest version");
logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion()); logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion());
} }
@@ -118,16 +114,12 @@ public class UpdateUtils {
Document doc = null; Document doc = null;
try { try {
logger.debug("Retrieving " + UpdateUtils.updateJsonURL); logger.debug("Retrieving " + UpdateUtils.updateJsonURL);
doc = Jsoup.connect(UpdateUtils.updateJsonURL) doc = Jsoup.connect(UpdateUtils.updateJsonURL).timeout(10 * 1000).ignoreContentType(true).get();
.timeout(10 * 1000)
.ignoreContentType(true)
.get();
} catch (IOException e) { } catch (IOException e) {
logger.error("Error while fetching update: ", e); logger.error("Error while fetching update: ", e);
JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null,
"<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>", "<html><font color=\"red\">Error while fetching update: " + e.getMessage() + "</font></html>",
"RipMe Updater", "RipMe Updater", JOptionPane.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
return; return;
} finally { } finally {
configUpdateLabel.setText("Current version: " + getThisJarVersion()); configUpdateLabel.setText("Current version: " + getThisJarVersion());
@@ -159,17 +151,16 @@ public class UpdateUtils {
try { try {
UpdateUtils.downloadJarAndLaunch(getUpdateJarURL(latestVersion), true); UpdateUtils.downloadJarAndLaunch(getUpdateJarURL(latestVersion), true);
} catch (IOException e) { } catch (IOException e) {
JOptionPane.showMessageDialog(null, JOptionPane.showMessageDialog(null, "Error while updating: " + e.getMessage(), "RipMe Updater",
"Error while updating: " + e.getMessage(),
"RipMe Updater",
JOptionPane.ERROR_MESSAGE); JOptionPane.ERROR_MESSAGE);
configUpdateLabel.setText(""); configUpdateLabel.setText("");
logger.error("Error while updating: ", e); logger.error("Error while updating: ", e);
} }
} else { } else {
logger.debug("This version (" + UpdateUtils.getThisJarVersion() + logger.debug("This version (" + UpdateUtils.getThisJarVersion()
") is the same or newer than the website's version (" + latestVersion + ")"); + ") is the same or newer than the website's version (" + latestVersion + ")");
configUpdateLabel.setText("<html><font color=\"green\">v" + UpdateUtils.getThisJarVersion() + " is the latest version</font></html>"); configUpdateLabel.setText("<html><font color=\"green\">v" + UpdateUtils.getThisJarVersion()
+ " is the latest version</font></html>");
logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion()); logger.debug("Running latest version: " + UpdateUtils.getThisJarVersion());
} }
} }
@@ -191,8 +182,7 @@ public class UpdateUtils {
if (newVersions[i] > oldVersions[i]) { if (newVersions[i] > oldVersions[i]) {
logger.debug("oldVersion " + getThisJarVersion() + " < latestVersion" + latestVersion); logger.debug("oldVersion " + getThisJarVersion() + " < latestVersion" + latestVersion);
return true; return true;
} } else if (newVersions[i] < oldVersions[i]) {
else if (newVersions[i] < oldVersions[i]) {
logger.debug("oldVersion " + getThisJarVersion() + " > latestVersion " + latestVersion); logger.debug("oldVersion " + getThisJarVersion() + " > latestVersion " + latestVersion);
return false; return false;
} }
@@ -232,7 +222,8 @@ public class UpdateUtils {
sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4)); sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
sb.append("0123456789ABCDEF".charAt((b & 0x0F))); sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
} }
// As patch.py writes the hash in lowercase this must return the has in lowercase // As patch.py writes the hash in lowercase this must return the has in
// lowercase
return sb.toString().toLowerCase(); return sb.toString().toLowerCase();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
logger.error("Got error getting file hash " + e.getMessage()); logger.error("Got error getting file hash " + e.getMessage());
@@ -244,13 +235,10 @@ public class UpdateUtils {
return null; return null;
} }
private static void downloadJarAndLaunch(String updateJarURL, Boolean shouldLaunch) private static void downloadJarAndLaunch(String updateJarURL, Boolean shouldLaunch) throws IOException {
throws IOException {
Response response; Response response;
response = Jsoup.connect(updateJarURL) response = Jsoup.connect(updateJarURL).ignoreContentType(true)
.ignoreContentType(true) .timeout(Utils.getConfigInteger("download.timeout", 60 * 1000)).maxBodySize(1024 * 1024 * 100)
.timeout(Utils.getConfigInteger("download.timeout", 60 * 1000))
.maxBodySize(1024 * 1024 * 100)
.execute(); .execute();
try (FileOutputStream out = new FileOutputStream(updateFileName)) { try (FileOutputStream out = new FileOutputStream(updateFileName)) {
@@ -276,9 +264,7 @@ public class UpdateUtils {
// Windows // Windows
final String batchFile = "update_ripme.bat"; final String batchFile = "update_ripme.bat";
final String batchPath = new File(batchFile).getAbsolutePath(); final String batchPath = new File(batchFile).getAbsolutePath();
String script = "@echo off\r\n" String script = "@echo off\r\n" + "timeout 1\r\n" + "copy " + updateFileName + " " + mainFileName + "\r\n"
+ "timeout 1\r\n"
+ "copy " + updateFileName + " " + mainFileName + "\r\n"
+ "del " + updateFileName + "\r\n"; + "del " + updateFileName + "\r\n";
if (shouldLaunch) { if (shouldLaunch) {
script += mainFileName + "\r\n"; script += mainFileName + "\r\n";
@@ -298,7 +284,8 @@ public class UpdateUtils {
logger.info("Executing: " + batchFile); logger.info("Executing: " + batchFile);
Runtime.getRuntime().exec(batchExec); Runtime.getRuntime().exec(batchExec);
} catch (IOException e) { } catch (IOException e) {
//TODO implement proper stack trace handling this is really just intented as a placeholder until you implement proper error handling // TODO implement proper stack trace handling this is really just intented as a
// placeholder until you implement proper error handling
e.printStackTrace(); e.printStackTrace();
} }
})); }));
@@ -306,7 +293,8 @@ public class UpdateUtils {
System.exit(0); System.exit(0);
} else { } else {
// Mac / Linux // Mac / Linux
// Modifying file and launching it: *nix distributions don't have any issues with modifying/deleting files // Modifying file and launching it: *nix distributions don't have any issues
// with modifying/deleting files
// while they are being run // while they are being run
File mainFile = new File(mainFileName); File mainFile = new File(mainFileName);
String mainFilePath = mainFile.getAbsolutePath(); String mainFilePath = mainFile.getAbsolutePath();

View File

@@ -1,18 +1,10 @@
package com.rarchives.ripme.utils; package com.rarchives.ripme.utils;
import com.rarchives.ripme.ripper.AbstractRipper; import java.io.File;
import org.apache.commons.configuration.ConfigurationException; import java.io.FileNotFoundException;
import org.apache.commons.configuration.PropertiesConfiguration; import java.io.IOException;
import org.apache.log4j.LogManager; import java.io.InputStream;
import org.apache.log4j.Logger; import java.io.UnsupportedEncodingException;
import org.apache.log4j.PropertyConfigurator;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
@@ -30,7 +22,18 @@ import java.util.ResourceBundle;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import static java.lang.Math.toIntExact; import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import com.rarchives.ripme.ripper.AbstractRipper;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/** /**
* Common utility functions used in various places throughout the project. * Common utility functions used in various places throughout the project.
@@ -88,9 +91,9 @@ public class Utils {
* @return Root directory to save rips to. * @return Root directory to save rips to.
*/ */
public static File getWorkingDirectory() { public static File getWorkingDirectory() {
String currentDir = "."; String currentDir = "";
try { try {
currentDir = new File(".").getCanonicalPath() + File.separator + RIP_DIRECTORY + File.separator; currentDir = getJarDirectory().getCanonicalPath() + File.separator + RIP_DIRECTORY + File.separator;
} catch (IOException e) { } catch (IOException e) {
LOGGER.error("Error while finding working dir: ", e); LOGGER.error("Error while finding working dir: ", e);
} }
@@ -214,8 +217,12 @@ public class Utils {
* Gets the directory of where the config file is stored on a Mac machine. * Gets the directory of where the config file is stored on a Mac machine.
*/ */
private static String getMacOSConfigDir() { private static String getMacOSConfigDir() {
return System.getProperty("user.home") return System.getProperty("user.home") + File.separator + "Library" + File.separator + "Application Support"
+ File.separator + "Library" + File.separator + "Application Support" + File.separator + "ripme"; + File.separator + "ripme";
}
private static File getJarDirectory() {
return new File(System.getProperty("java.class.path")).getParentFile();
} }
/** /**
@@ -223,7 +230,7 @@ public class Utils {
*/ */
private static boolean portableMode() { private static boolean portableMode() {
try { try {
File file = new File(new File(".").getCanonicalPath() + File.separator + CONFIG_FILE); File file = new File(getJarDirectory().getCanonicalPath() + File.separator + CONFIG_FILE);
if (file.exists() && !file.isDirectory()) { if (file.exists() && !file.isDirectory()) {
return true; return true;
} }
@@ -240,18 +247,21 @@ public class Utils {
public static String getConfigDir() { public static String getConfigDir() {
if (portableMode()) { if (portableMode()) {
try { try {
return new File(".").getCanonicalPath(); return getJarDirectory().getCanonicalPath();
} catch (Exception e) { } catch (Exception e) {
return "."; return ".";
} }
} }
if (isWindows()) return getWindowsConfigDir(); if (isWindows())
if (isMacOS()) return getMacOSConfigDir(); return getWindowsConfigDir();
if (isUnix()) return getUnixConfigDir(); if (isMacOS())
return getMacOSConfigDir();
if (isUnix())
return getUnixConfigDir();
try { try {
return new File(".").getCanonicalPath(); return getJarDirectory().getCanonicalPath();
} catch (Exception e) { } catch (Exception e) {
return "."; return ".";
} }
@@ -302,8 +312,8 @@ public class Utils {
} }
/** /**
* Strips away URL parameters, which usually appear at the end of URLs. * Strips away URL parameters, which usually appear at the end of URLs. E.g. the
* E.g. the ?query on PHP * ?query on PHP
* *
* @param url The URL to filter/strip * @param url The URL to filter/strip
* @param parameter The parameter to strip * @param parameter The parameter to strip
@@ -344,9 +354,8 @@ public class Utils {
} }
/** /**
* Get a list of all Classes within a package. * Get a list of all Classes within a package. Works with file system projects
* Works with file system projects and jar files! * and jar files! Borrowed from StackOverflow, but I don't have a link :[
* Borrowed from StackOverflow, but I don't have a link :[
* *
* @param pkgname The name of the package * @param pkgname The name of the package
* @return List of classes within the package * @return List of classes within the package
@@ -365,7 +374,10 @@ public class Utils {
try { try {
directory = new File(resource.toURI()); directory = new File(resource.toURI());
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); throw new RuntimeException(
pkgname + " (" + resource
+ ") does not appear to be a valid URL / URI. Strange, since we got it from the system...",
e);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
directory = null; directory = null;
} }
@@ -386,17 +398,14 @@ public class Utils {
} else { } else {
// Load from JAR // Load from JAR
try { try {
String jarPath = fullPath String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
.replaceFirst("[.]jar[!].*", ".jar")
.replaceFirst("file:", "");
jarPath = URLDecoder.decode(jarPath, "UTF-8"); jarPath = URLDecoder.decode(jarPath, "UTF-8");
JarFile jarFile = new JarFile(jarPath); JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries(); Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
JarEntry nextElement = entries.nextElement(); JarEntry nextElement = entries.nextElement();
String entryName = nextElement.getName(); String entryName = nextElement.getName();
if (entryName.startsWith(relPath) if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())
&& entryName.length() > (relPath.length() + "/".length())
&& !nextElement.isDirectory()) { && !nextElement.isDirectory()) {
String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
try { try {
@@ -438,9 +447,7 @@ public class Utils {
if (path.length() < SHORTENED_PATH_LENGTH * 2) { if (path.length() < SHORTENED_PATH_LENGTH * 2) {
return path; return path;
} }
return path.substring(0, SHORTENED_PATH_LENGTH) return path.substring(0, SHORTENED_PATH_LENGTH) + "..." + path.substring(path.length() - SHORTENED_PATH_LENGTH);
+ "..."
+ path.substring(path.length() - SHORTENED_PATH_LENGTH);
} }
/** /**
@@ -455,9 +462,7 @@ public class Utils {
} }
public static String filesystemSafe(String text) { public static String filesystemSafe(String text) {
text = text.replaceAll("[^a-zA-Z0-9.-]", "_") text = text.replaceAll("[^a-zA-Z0-9.-]", "_").replaceAll("__", "_").replaceAll("_+$", "");
.replaceAll("__", "_")
.replaceAll("_+$", "");
if (text.length() > 100) { if (text.length() > 100) {
text = text.substring(0, 99); text = text.substring(0, 99);
} }
@@ -516,7 +521,8 @@ public class Utils {
} }
/** /**
* Gets and returns a list of all the album rippers present in the "com.rarchives.ripme.ripper.rippers" package. * Gets and returns a list of all the album rippers present in the
* "com.rarchives.ripme.ripper.rippers" package.
* *
* @return List<String> of all album rippers present. * @return List<String> of all album rippers present.
*/ */
@@ -529,7 +535,8 @@ public class Utils {
} }
/** /**
* Gets and returns a list of all video rippers present in the "com.rarchives.rime.rippers.video" package * Gets and returns a list of all video rippers present in the
* "com.rarchives.rime.rippers.video" package
* *
* @return List<String> of all the video rippers. * @return List<String> of all the video rippers.
*/ */
@@ -568,7 +575,6 @@ public class Utils {
public static void configureLogger() { public static void configureLogger() {
LogManager.shutdown(); LogManager.shutdown();
String logFile = getConfigBoolean("log.save", false) ? "log4j.file.properties" : "log4j.properties"; String logFile = getConfigBoolean("log.save", false) ? "log4j.file.properties" : "log4j.properties";
try (InputStream stream = Utils.class.getClassLoader().getResourceAsStream(logFile)) { try (InputStream stream = Utils.class.getClassLoader().getResourceAsStream(logFile)) {
if (stream == null) { if (stream == null) {
PropertyConfigurator.configure("src/main/resources/" + logFile); PropertyConfigurator.configure("src/main/resources/" + logFile);
@@ -627,7 +633,8 @@ public class Utils {
try { try {
for (String part : parts) { for (String part : parts) {
if ((pos = part.indexOf('=')) >= 0) { if ((pos = part.indexOf('=')) >= 0) {
res.put(URLDecoder.decode(part.substring(0, pos), "UTF-8"), URLDecoder.decode(part.substring(pos + 1), "UTF-8")); res.put(URLDecoder.decode(part.substring(0, pos), "UTF-8"),
URLDecoder.decode(part.substring(pos + 1), "UTF-8"));
} else { } else {
res.put(URLDecoder.decode(part, "UTF-8"), ""); res.put(URLDecoder.decode(part, "UTF-8"), "");
} }
@@ -695,17 +702,19 @@ public class Utils {
} }
/** /**
* Gets the ResourceBundle AKA language package. * Gets the ResourceBundle AKA language package. Used for choosing the language
* Used for choosing the language of the UI. * of the UI.
* *
* @return Returns the default resource bundle using the language specified in the config file. * @return Returns the default resource bundle using the language specified in
* the config file.
*/ */
public static ResourceBundle getResourceBundle(String langSelect) { public static ResourceBundle getResourceBundle(String langSelect) {
if (langSelect == null) { if (langSelect == null) {
if (!getConfigString("lang", "").equals("")) { if (!getConfigString("lang", "").equals("")) {
String[] langCode = getConfigString("lang", "").split("_"); String[] langCode = getConfigString("lang", "").split("_");
LOGGER.info("Setting locale to " + getConfigString("lang", "")); LOGGER.info("Setting locale to " + getConfigString("lang", ""));
return ResourceBundle.getBundle("LabelsBundle", new Locale(langCode[0], langCode[1]), new UTF8Control()); return ResourceBundle.getBundle("LabelsBundle", new Locale(langCode[0], langCode[1]),
new UTF8Control());
} }
} else { } else {
String[] langCode = langSelect.split("_"); String[] langCode = langSelect.split("_");
@@ -724,17 +733,17 @@ public class Utils {
/** /**
* Formats and reuturns the status text for rippers using the byte progress bar * Formats and reuturns the status text for rippers using the byte progress bar
* *
* @param completionPercentage An int between 0 and 100 which repersents how close the download is to complete * @param completionPercentage An int between 0 and 100 which repersents how
* close the download is to complete
* @param bytesCompleted How many bytes have been downloaded * @param bytesCompleted How many bytes have been downloaded
* @param bytesTotal The total size of the file that is being downloaded * @param bytesTotal The total size of the file that is being
* @return Returns the formatted status text for rippers using the byte progress bar * downloaded
* @return Returns the formatted status text for rippers using the byte progress
* bar
*/ */
public static String getByteStatusText(int completionPercentage, int bytesCompleted, int bytesTotal) { public static String getByteStatusText(int completionPercentage, int bytesCompleted, int bytesTotal) {
return String.valueOf(completionPercentage) + return String.valueOf(completionPercentage) + "% - " + Utils.bytesToHumanReadable(bytesCompleted) + " / "
"% - " + + Utils.bytesToHumanReadable(bytesTotal);
Utils.bytesToHumanReadable(bytesCompleted) +
" / " +
Utils.bytesToHumanReadable(bytesTotal);
} }
public static String getEXTFromMagic(ByteBuffer magic) { public static String getEXTFromMagic(ByteBuffer magic) {
@@ -797,7 +806,8 @@ public class Utils {
throw new FileNotFoundException("File path is too long for this OS"); throw new FileNotFoundException("File path is too long for this OS");
} }
String[] saveAsSplit = fileName.split("\\."); String[] saveAsSplit = fileName.split("\\.");
// Get the file extension so when we shorten the file name we don't cut off the file extension // Get the file extension so when we shorten the file name we don't cut off the
// file extension
String fileExt = saveAsSplit[saveAsSplit.length - 1]; String fileExt = saveAsSplit[saveAsSplit.length - 1];
// The max limit for paths on Windows is 260 chars // The max limit for paths on Windows is 260 chars
LOGGER.info(fullPath.substring(0, 260 - pathLength - fileExt.length() + 1) + "." + fileExt); LOGGER.info(fullPath.substring(0, 260 - pathLength - fileExt.length() + 1) + "." + fileExt);