Skip to content
This repository has been archived by the owner on Jan 21, 2022. It is now read-only.

Commit

Permalink
Release 1.11.6
Browse files Browse the repository at this point in the history
Fixed some bugs one of which being a memory leak caused by unclosed streams.
  • Loading branch information
PlanetTeamSpeakk authored May 6, 2018
1 parent 84b72a2 commit 7e7e577
Show file tree
Hide file tree
Showing 7 changed files with 205 additions and 57 deletions.
48 changes: 26 additions & 22 deletions src/main/java/com/ptsmods/impulse/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

import javax.annotation.Nullable;
import javax.security.auth.login.LoginException;
Expand Down Expand Up @@ -98,7 +102,6 @@
import com.ptsmods.impulse.utils.HookedPrintStream.PrintHook;
import com.ptsmods.impulse.utils.ImageManipulator;
import com.ptsmods.impulse.utils.Random;
import com.ptsmods.impulse.utils.UsageMonitorer;
import com.ptsmods.impulse.utils.compiler.CompilationException;
import com.ptsmods.impulse.utils.compiler.MemoryJavaCompiler;

Expand Down Expand Up @@ -149,7 +152,7 @@ public class Main {

public static final int major = 1;
public static final int minor = 11;
public static final int revision = 5;
public static final int revision = 6;
public static final String type = "stable";
public static final String version = String.format("%s.%s.%s-%s", major, minor, revision, type);
public static final Object nil = null;
Expand Down Expand Up @@ -234,7 +237,6 @@ public void onPrint(String string, boolean newLine) {
else theUnsafe = null;
}

@SuppressWarnings("deprecation")
public static final void main(String[] args) {
List<String> argsList = Lists.newArrayList(args);
devMode = argsList.contains("-devMode");
Expand All @@ -245,22 +247,13 @@ public static final void main(String[] args) {
int lines = 0;
for (File file : getFilesInDir(new File("src/main/java/com/ptsmods/impulse/")))
try {
lines += Files.readAllLines(file.toPath()).size();
for (String line : Files.readAllLines(file.toPath()))
if (!line.split("//")[0].trim().isEmpty() && !line.startsWith("import")) lines += 1;
} catch (IOException e) {
e.printStackTrace();
}
print(LogType.DEBUG, "Impulse is currently made up of", lines, "lines of code! Woah!");
}
runAsynchronously(() -> {
while (true) {
for (Thread thread : getThreads())
if (UsageMonitorer.getThreadCPUUsage(thread).floatValue() >= 25 && thread != mainThread) {
thread.stop();
print(LogType.WARN, "Thread '" + thread.getName() + "' with an ID of", thread.getId(), "was killed as its CPU usage,", UsageMonitorer.getThreadCPUUsage(thread).floatValue() + "%, was greater than or equal to 25%.");
}
sleep(1000); // the values get updated every second
}
});
try {
main0(args);
} catch (Throwable e) {
Expand Down Expand Up @@ -613,7 +606,7 @@ public static Member getMemberFromInput(Message input) {
}

public static String getUsernameAtArg(String string, Guild guild, int arg) {
return getUsernameFromArgs(removeArgs(string.split(" "), Arrays.stream(new int[arg]).boxed().toArray(Integer[]::new)), guild);
return getUsernameFromArgs(removeArgs(string.split(" "), intArrayToIntegerArray(new int[arg])), guild);
}

private static String getUsernameFromArgs(String[] args, Guild guild) {
Expand Down Expand Up @@ -2538,19 +2531,30 @@ public static List<File> getFilesInDir(File dir) {
}

public static Integer[] intArrayToIntegerArray(int... array) {
return Arrays.stream(array).boxed().toArray(Integer[]::new);
IntStream stream = Arrays.stream(array);
Stream stream0 = stream.boxed();
Integer[] modernArray = (Integer[]) stream0.<Integer>toArray(Integer[]::new);
stream.close();
stream0.close();
return modernArray;
}

public static Long[] longArrayToLongArray(long... array) {
return Arrays.stream(array).boxed().toArray(Long[]::new);
}

public static Float[] floatArrayToFloatArray(long... array) {
return Arrays.stream(array).boxed().toArray(Float[]::new);
LongStream stream = Arrays.stream(array);
Stream stream0 = stream.boxed();
Long[] modernArray = (Long[]) stream0.<Long>toArray(Long[]::new);
stream.close();
stream0.close();
return modernArray;
}

public static Double[] doubleArrayToDoubleArray(double... array) {
return Arrays.stream(array).boxed().toArray(Double[]::new);
DoubleStream stream = Arrays.stream(array);
Stream stream0 = stream.boxed();
Double[] modernArray = (Double[]) stream0.<Double>toArray(Double[]::new);
stream.close();
stream0.close();
return modernArray;
}

public static boolean isWholeNumber(double d) {
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/ptsmods/impulse/commands/Marriage.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -699,7 +698,7 @@ private static final Map<String, Object> getChild(CommandEvent event) throws Exc
if (!isMarried(event.getAuthor(), maritus, event.getGuild())) throw new Exception("not married");
String name = "";
if (!mentioned)
name = Main.join(Main.removeArgs(event.getArgs().split(" "), Arrays.stream(new int[maritus.getName().split(" ").length]).boxed().toArray(Integer[]::new)));
name = Main.join(Main.removeArgs(event.getArgs().split(" "), Main.intArrayToIntegerArray(new int[maritus.getName().split(" ").length])));
else name = Main.join(Main.removeArg(event.getArgs().split(" "), 0));
for (Entry<String, Map<String, Map<String, Object>>> guild : marriages.entrySet())
for (Entry<String, Map<String, Object>> role : guild.getValue().entrySet())
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/ptsmods/impulse/utils/Dashboard.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import com.ptsmods.impulse.commands.Economy;
import com.ptsmods.impulse.commands.Marriage;
import com.ptsmods.impulse.commands.Moderation;
import com.ptsmods.impulse.utils.upnp.UPnP;
import com.ptsmods.impulse.utils.upnp.UPnPProtocol;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
Expand Down Expand Up @@ -223,6 +225,7 @@ public void handle0(HttpExchange he) throws IOException {
server.setExecutor(executor);
server.start();
Main.print(LogType.INFO, "Successfully started the server on port", server.getAddress().getPort() + ", you can browse to it by going to http://localhost:" + server.getAddress().getPort() + ".");
UPnP.portForward(UPnPProtocol.BOTH, port, "Discord Bot API");
}

public static void writeString(HttpExchange he, String string, Object... args) throws IOException {
Expand Down
92 changes: 59 additions & 33 deletions src/main/java/com/ptsmods/impulse/utils/Downloader.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,27 @@ public class Downloader {

/**
*
* @param url The url of the file to be downloaded.
* @param fileLocation A string of the location where the file should be downloaded to, this must include a file suffix.
* @return Map<String, String> Contains keys fileLocation and success, fileLocation will contain the location where the file was downloaded to, success will be a boolean in a string which shows if the download was successful.
* @param url
* The url of the file to be downloaded.
* @param fileLocation
* A string of the location where the file should be downloaded to,
* this must include a file suffix.
* @return A {@link com.ptsmods.impulse.utils.Downloader.DownloadResult
* DownloadResult} that'll contain the downloaded file's location, the
* file size and if it succeeded.
* @throws IOException
*/
public static DownloadResult downloadFile(String url, String fileLocation) throws IOException {
String[] fileLocationParts = fileLocation.split("/");
String fileLocation2 = "";
for (int x = 0; x < fileLocationParts.length; x += 1)
if (x+1 != fileLocationParts.length) {
if (x + 1 != fileLocationParts.length) {
fileLocation2 += "/" + fileLocationParts[x];
new File(fileLocation2.substring(1)).mkdirs();
}
if (new File(fileLocation).exists()) fileLocation = fileLocation.split("\\.")[0] + "-1" + (fileLocation.split("\\.").length != 1 ? "." + fileLocation.split("\\.")[fileLocation.split("\\.").length-1] : "");
while (new File(fileLocation).exists()) fileLocation = addNextDigit(fileLocation);
if (new File(fileLocation).exists()) fileLocation = fileLocation.split("\\.")[0] + "-1" + (fileLocation.split("\\.").length != 1 ? "." + fileLocation.split("\\.")[fileLocation.split("\\.").length - 1] : "");
while (new File(fileLocation).exists())
fileLocation = addNextDigit(fileLocation);
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
Expand All @@ -47,9 +53,9 @@ public static DownloadResult downloadFile(String url, String fileLocation) throw
}

private static String addNextDigit(String string) {
Long digit = Long.parseLong(string.split("-")[string.split("-").length-1].split("\\.")[0]);
Long digit = Long.parseLong(string.split("-")[string.split("-").length - 1].split("\\.")[0]);
digit += 1;
return string.split("\\.")[0].split("-")[0] + "-" + digit.toString() + "." + string.split("\\.")[string.split("\\.").length-1];
return string.split("\\.")[0].split("-")[0] + "-" + digit.toString() + "." + string.split("\\.")[string.split("\\.").length - 1];
}

public static DownloadResult downloadYoutubeVideo(String url, String fileLocation) throws IOException {
Expand Down Expand Up @@ -77,12 +83,11 @@ public static String getVideoLinkFromYoutubeVid(String url) throws IOException {
downloadUrl = (String) audio.get("url");
break;
}
} else
for (Map video1 : videos)
if (((String) video1.get("extension")).toLowerCase().equals("mp4")) {
downloadUrl = (String) video1.get("url");
break;
}
} else for (Map video1 : videos)
if (((String) video1.get("extension")).toLowerCase().equals("mp4")) {
downloadUrl = (String) video1.get("url");
break;
}
downloadUrl = downloadUrl.replaceAll(" ", "+");
}
}
Expand Down Expand Up @@ -111,7 +116,8 @@ public static String getVideoLinkFromVimeoVid(String url) throws IOException {
}
quality = lowerQuality(quality);
}
if (!video.isEmpty()) return (String) video.get("url");
if (!video.isEmpty())
return (String) video.get("url");
else return "";
} else throw new IOException("The given URL was not a Vimeo URL.");
}
Expand All @@ -120,53 +126,73 @@ public static long getWebFileSize(String url) throws IOException {
try {
return new URL(url).openConnection().getContentLengthLong();
} catch (Throwable e) {
if (!(e instanceof IOException)) throw new IOException(e);
if (!(e instanceof IOException))
throw new IOException(e);
else throw e;
}
}

public static String formatFileSize(double bytes) {
String output = "0 bytes";
if (bytes/1024F/1024F/1024F >= 1F) output = bytes/1024F/1024F/1024F + " gigabytes";
else if (bytes/1024F/1024F >= 1F) output = bytes/1024F/1024F + " megabytes";
else output = bytes/1024L + " kilobytes";
if (bytes / 1024F / 1024F / 1024F >= 1F)
output = bytes / 1024F / 1024F / 1024F + " gigabytes";
else if (bytes / 1024F / 1024F >= 1F)
output = bytes / 1024F / 1024F + " megabytes";
else output = bytes / 1024L + " kilobytes";
return output;
}

public static double formatFileSizeDoubleMb(double bytes) {
return bytes/1024F/1024F;
return bytes / 1024F / 1024F;
}

public static String lowerQuality(String quality) {
String output = "240p";
switch (quality) {
case "1080p": {output = "720p"; break;}
case "720p": {output = "540p"; break;}
case "540p": {output = "480p"; break;}
case "480p": {output = "360p"; break;}
default: break;
case "1080p": {
output = "720p";
break;
}
case "720p": {
output = "540p";
break;
}
case "540p": {
output = "480p";
break;
}
case "480p": {
output = "360p";
break;
}
default:
break;
}
return output;
}

public static DownloadResult downloadFileOrVideo(String url, String fileLocation) throws IOException {
if (url.contains("youtu")) return downloadYoutubeVideo(url, fileLocation);
else if (url.contains("vimeo.com/")) return downloadVimeoVideo(url, fileLocation);
if (url.contains("youtu"))
return downloadYoutubeVideo(url, fileLocation);
else if (url.contains("vimeo.com/"))
return downloadVimeoVideo(url, fileLocation);
else return downloadFile(url, fileLocation);
}

public static String convertUrl(String url) throws IOException {
if (url.contains("youtu")) return getVideoLinkFromYoutubeVid(url);
else if (url.contains("vimeo")) return getVideoLinkFromVimeoVid(url);
if (url.contains("youtu"))
return getVideoLinkFromYoutubeVid(url);
else if (url.contains("vimeo"))
return getVideoLinkFromVimeoVid(url);
else return url;
}

public static class DownloadResult {

private final File file;
private final String fileLocation;
private final long fileSize;
private final boolean success;
private final File file;
private final String fileLocation;
private final long fileSize;
private final boolean success;

private DownloadResult(String fileLocation, long fileSize, boolean success) {
file = new File(fileLocation);
Expand Down
68 changes: 68 additions & 0 deletions src/main/java/com/ptsmods/impulse/utils/upnp/UPnP.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.ptsmods.impulse.utils.upnp;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import com.ptsmods.impulse.Main.LogType;
import com.ptsmods.impulse.miscellaneous.Main;
import com.ptsmods.impulse.utils.ArraySet;
import com.ptsmods.impulse.utils.Downloader;

public class UPnP {

private UPnP() {
}

public static void portForward(UPnPProtocol protocol, int port, String description) throws IOException {
getPortmapper();
String cmd = "java -jar libs/portmapper.jar -add -internalPort " + port + " -externalPort " + port + " -description \"" + description + "\" ";
if (Main.isWindows()) cmd = "cmd /c " + cmd;
switch (protocol) {
case TCP:
Runtime.getRuntime().exec(cmd + "-protocol TCP");
break;
case UDP:
Runtime.getRuntime().exec(cmd + "-protocol UDP");
break;
case BOTH:
Runtime.getRuntime().exec(cmd + "-protocol TCP");
Runtime.getRuntime().exec(cmd + "-protocol UDP");
break;
}
Main.print(LogType.INFO, "Successfully portforwarded port", port + ".");
}

public static boolean checkPortmapper() {
return new File("libs/portmapper.jar").exists();
}

public static void getPortmapper() {
if (!checkPortmapper()) try {
Main.print(LogType.DEBUG, "Could not find portmapper, downloading it now...");
if (!Downloader.downloadFile("https://kent.dl.sourceforge.net/project/upnp-portmapper/v2.1.1/portmapper-2.1.1.jar", "libs/portmapper.jar").succeeded()) throw new IOException("Could not download portmapper.jar.");
} catch (IOException e) {
Main.throwCheckedExceptionWithoutDeclaration(e);
}
}

public static List<UPnPEntry> getUPnPEntries() throws IOException {
getPortmapper();
List<UPnPEntry> entries = new ArraySet();
Process process = Runtime.getRuntime().exec((Main.isWindows() ? "cmd /c " : " ") + "java -jar libs/portmapper.jar -list");
Main.sleep(7500);
List<String> lines = new ArrayList();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
lines.add(line);
for (String line0 : lines)
if (line0.startsWith("TCP") || line0.startsWith("UDP")) entries.add(new UPnPEntry(line0.startsWith("TCP") ? UPnPProtocol.TCP : UPnPProtocol.UDP, Integer.parseInt(line0.substring(5).split(" ")[0]), Main.join(Main.removeArgs(line0.split(" "), 0, 0, 0, 0, 0)), InetAddress.getByName(line0.split(" ")[3].split(":")[0]), line0.split(" ")[4].equals("enabled")));
return entries;
}

}
Loading

0 comments on commit 7e7e577

Please sign in to comment.